20171018 在小程序页面去获取用户的OpenID

时间:2023-03-08 20:57:46
20171018 在小程序页面去获取用户的OpenID

1. 在小程序的.js 文件中增加代码

 //加载页面时到后台服务去获取openID
onLoad: function (options) {
//OpenId
wx.login({
//获取code
success: (res) => {
wx.request({
method: "GET",
url: 'https://(自己的域名部分)/api/pc/GetOpenID', //仅为示例,并非真实的接口地址
data: {
scode: res.code // 使用wx.login得到的登陆凭证,用于换取openid
},
header: {
'content-type': 'application/json' // 默认值
},
success: (res) => {
this.setData({
sopenid: res.data
})
console.log(this.data.sopenid)
}
})
console.log(res.code) //这里只是为了在微信小程序客户端好查看结果,找寻问题
}
})
},

2 . 服务器端Web API 通过小程序界面传递的数据去获取 Open ID

   #region  --- 获取OpenId ---
[HttpGet]
public string GetOpenID(string scode)
{
try
{ var _APP_ID = ""; // 你申请的小程序ID
var _APP_SECRET = ""; // 小程序的SECRET ,当然这个是可微信公共平台去生成的 var url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", _APP_ID, _APP_SECRET, scode);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "Get"; // 这里是定义请求的方式 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //对请求返回的结果进行处理
Stream io = response.GetResponseStream();
StreamReader sr = new StreamReader(io, Encoding.UTF8);
var html = sr.ReadToEnd(); //返回的内容被读取为流
sr.Close();
io.Close();
response.Close(); string key = "\"openid\":\"";
int stratindex = html.IndexOf(key); //截取字符 if (stratindex != -) //验证是否存在OpenID ,有时使用过期的登陆凭证,会出现异常
{
int endindex = html.IndexOf("\"}", stratindex); // 这里在截取字符时,要注意内容是否和截取的部分相同,否则截取会失败
string _openid = html.Substring(stratindex + key.Length, endindex - stratindex - key.Length);
return _openid;
}
else {
return "error";
} }
catch (Exception ex)
{
return "error"+ex;
} }
#endregion