前言
首先要知道为什么token、openid、sessionKey不能存入session的原因是jQuery的ajax自动会带上cookie,而wx.request不会。wx.request每一次请求相当于一次新的请求导致服务器无法识别单独用户。我这边解决方法是存入缓存。
获取openid和sessionKey的官方接口
参数需要appid,secret,code,
“https://api.weixin.qq.com/sns/jscode2session?appid=null&secret=null” + “&js_code=” + 微信端wx.login获取+ “&grant_type=authorization_code”;
获取token的官方接口,有效期120分钟
参数需要appid,secret
“https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=null&secret=null”;
直接上代码,先是缓存存取的方法,复制即可用
///
/// 创建缓存
///
/// 缓存的Key
/// 缓存的数据
/// 缓存过期时间
public static bool CreateCache(string key, object value, DateTime expiresAt)
{
if (string.IsNullOrEmpty(key) || value == null)
{
return false;
}
HttpRuntime.Cache.Add(key, value, null, expiresAt, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
return true;
}
///
/// 获取缓存
///
///
///
public object GetCache(string key)
{
return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
}
///
/// 移除所有缓存
///
///
public bool RemoveAll()
{
IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
while (iDictionaryEnumerator.MoveNext())
{
HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
}
return true;
}
接口的编写
复制即可用,输入appid和secret
简述:调用接口,如果缓存中不存在token就重新获取并存入缓存,应该token的有效期的120分钟后过期,所以这边是存入缓存110分钟过期,如果存在token就直接返回。
[WebMethod(EnableSession = true)]
public void GetToken()
{
if (GetCache("access_token") == null)
{
string stoken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=“你的”&secret=“你的”";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stoken);
request.Method = "GET";
request.ContentType = "text/html;charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retStringtoken = myStreamReader.ReadToEnd();
myResponseStream.Close();
myStreamReader.Close();
JObject retStringtokenJob = JObject.Parse(retStringtoken);
var obj = new
{
access_token = retStringtokenJob["access_token"].ToString(),
};
//获取当前时间
DateTime dt = DateTime.Now.AddMinutes(110);
Formatting microsoftDataFormatSetting = default(Formatting);
string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSetting);
bool bl = CreateCache("access_token", result, dt);
HttpContext.Current.Response.Write(result);
}
else HttpContext.Current.Response.Write(GetCache("access_token"));
}
getToken: function() {
var that = this;
wx.login({
success: res => {
// ------ 获取凭证 ------
var code = res.code;
if (code) {
console.log('获取用户登录凭证:' + code);
// ------ 发送凭证 ------
wx.request({
url: '你的接口地址',
data: {
'json_code': res.code
},
method: 'GET',
header: {
'content-type': 'appication/x-www-form-urlencoded'
},
success: function(res) {
that.globalData.access_token = res.data.access_token;
console.log(res.data.access_token);
}
})
} else {
console.log('获取用户登录失败:' + res.errMsg);
}
}
})
},
globalData: {
access_token: "",
}