新建类 接收小程序返回的值(类名随便改,但不要修改类字段名)
public class xcxModel
{
public string openid { get; set; }
public string session_key { get; set; }
}
在添加获取API的值的函数
private string GetDataFromServerApi(string url, string body)
{
string str = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = 1500;
if (!string.IsNullOrEmpty(body))
{
byte[] data = Encoding.UTF8.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
request.ContentLength = data.Length;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
str = reader.ReadToEnd();
}
}
catch (Exception ex)
{
//_logger.Error("获取小程序openID异常 exception:" + ex);
}
return str;
}
获取小程序的openID,Get方法
[HttpGet]
[Route("/GetopenID")]
public string GetCode(string code)
{
string openid = "";
try
{
// 微信小程序ID
string appid = "***";
// 微信小程序秘钥
string secret = "***";
// 根据小程序传过来的code想这个url发送请求
string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
// 发送请求,返回Json字符串
string str = GetDataFromServerApi(url, "");
// 转成Json对象 获取openid
var jsondata = JsonConvert.DeserializeObject<xcxModel>(str);
// 我们需要的openid,在一个小程序中,openid是唯一的
openid = jsondata.openid;
//_logger.Error("GetCode openid:" + openid);
}
catch (Exception ex)
{
//_logger.Error("GetCode Exception:" + ex.Message);
}
return openid;
}
小程序中需要获取的地方
wx.login({
success: function (res) {
if (res.code) {
// 获取openID
wx.request({
url: '***',
data: {
code: res.code
},
success: function (res) {
//存入缓存
wx.setStorageSync("OPEN_ID", res.data);
}
})
} else {
console.log('获取失败!' + res.errMsg)
}
}
})
END