您的位置:首页 > 移动开发 > 微信开发

微信公众号开发——获取access_token

2016-09-29 09:00 495 查看
第一步:登陆公众号 拿到 AppID(应用ID) 和 AppSecret(应用密钥)



第二步:公众号 接口权限 查看 对话服务>基础支持>获取access_token



上代码

写了3个类

BasisSupport 基础支持

CacheHelper 缓存帮助

Sender 发起请求

BasisSupport

using Codeplex.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeiXinPublic.utils;

namespace WeiXinPublic.dialog_service
{
/// <summary>
/// 基础支持
/// 1.获取access_token
/// 2.获取微信服务器IP地址
/// </summary>
public class BasisSupport
{
#region 获取access_token
/// <summary>
/// 获取access_token json字符串 调用微信接口
/// </summary>
/// <returns></returns>
/// <param name="appid"></param>
/// <param name="secret"></param>
/// <returns></returns>
private static string get_accesstoken(string appid, string secret)
{
string res = string.Empty;
object obj = CacheHelper.GetCache("access_token");
if (obj != null)
{
res = obj.ToString();
}
else
{
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
//通过接口去取
res = Sender.Get(url);
CacheHelper.AddCache("access_token", res, DateTime.Now.AddMinutes(120));   //ccess_token的有效期目前为2个小时
}
return res;
}

/// <summary>
/// 获取access_token
/// </summary>
/// <param name="appid"></param>
/// <param name="secret"></param>
/// <returns></returns>
public static Hashtable GetAccessToken(string appid, string secret)
{
string res = get_accesstoken(appid, secret);
var json = DynamicJson.Parse(res);
var access_token = json.access_token;
var expires_in = json.expires_in;

//万能字典
Hashtable ht = new Hashtable();
ht.Add("access_token", access_token);
ht.Add("expires_in", expires_in);
return ht;
}
#endregion
}
}


CacheHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace WeiXinPublic.utils
{
public class CacheHelper
{
public static List<string> AllUseCacheKey = new List<string>();

/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="absoluteExpiration"></param>
public static void AddCa
4000
che(string key, object value, DateTime absoluteExpiration)
{
if (!AllUseCacheKey.Contains(key))
{
AllUseCacheKey.Add(key);
}
HttpContext.Current.Cache.Add(key, value, null, absoluteExpiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}

/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void AddCache(string key, object value)
{
if (!AllUseCacheKey.Contains(key))
{
AllUseCacheKey.Add(key);
}

System.Web.Caching.Cache cache = HttpRuntime.Cache;
cache.Insert(key, value);
}

/// <summary>
/// 从缓存中取数据
/// </summary>
/// <param name="key"> key</param>
/// <returns></returns>
public static object GetCache(string key)
{
if (AllUseCacheKey.Contains(key) && HttpRuntime.Cache[key] != null)
{
return HttpRuntime.Cache[key];
}
else
{
return null;
}
}

/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key"></param>
public static void RemoveCache(string key)
{
if (AllUseCacheKey.Contains(key))
{
AllUseCacheKey.Remove(key);
}
HttpContext.Current.Cache.Remove(key);
}

/// <summary>
/// 清空使用的缓存
/// </summary>
public static void ClearCache()
{
foreach (string value in AllUseCacheKey)
{
HttpContext.Current.Cache.Remove(value);
}
AllUseCacheKey.Clear();
}
}
}


Sender

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WeiXinPublic.utils
{
public class Sender
{
/// <summary>
/// Get方式 访问微信接口
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string Get(string url)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}

/// <summary>
/// Post方式 访问微信接口
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string Post(string url, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
}
}


外部调用

Hashtable ht_access_token = BasisSupport.GetAccessToken(appid, secret);
string access_token = ht_access_token["access_token"].ToString();


类库结构图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信