1. 在小程序的.js 文件中增加代码
1 //加载页面时到后台服务去获取openID 2 onLoad: function (options) { 3 //OpenId 4 wx.login({ 5 //获取code 6 success: (res) => { 7 wx.request({ 8 method: "GET", 9 url: 'https://(自己的域名部分)/api/pc/GetOpenID', //仅为示例,并非真实的接口地址 10 data: { 11 scode: res.code // 使用wx.login得到的登陆凭证,用于换取openid 12 }, 13 header: { 14 'content-type': 'application/json' // 默认值 15 }, 16 success: (res) => { 17 this.setData({ 18 sopenid: res.data 19 }) 20 console.log(this.data.sopenid) 21 } 22 }) 23 console.log(res.code) //这里只是为了在微信小程序客户端好查看结果,找寻问题 24 } 25 }) 26 },
2 . 服务器端Web API 通过小程序界面传递的数据去获取 Open ID
1 #region --- 获取OpenId --- 2 [HttpGet] 3 public string GetOpenID(string scode) 4 { 5 try 6 { 7 8 var _APP_ID = ""; // 你申请的小程序ID 9 var _APP_SECRET = ""; // 小程序的SECRET ,当然这个是可微信公共平台去生成的 10 11 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); 12 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 13 request.Method = "Get"; // 这里是定义请求的方式 14 15 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //对请求返回的结果进行处理 16 Stream io = response.GetResponseStream(); 17 StreamReader sr = new StreamReader(io, Encoding.UTF8); 18 var html = sr.ReadToEnd(); //返回的内容被读取为流 19 sr.Close(); 20 io.Close(); 21 response.Close(); 22 23 string key = ""openid":""; 24 int stratindex = html.IndexOf(key); //截取字符 25 26 if (stratindex != -1) //验证是否存在OpenID ,有时使用过期的登陆凭证,会出现异常 27 { 28 int endindex = html.IndexOf(""}", stratindex); // 这里在截取字符时,要注意内容是否和截取的部分相同,否则截取会失败 29 string _openid = html.Substring(stratindex + key.Length, endindex - stratindex - key.Length); 30 return _openid; 31 } 32 else { 33 return "error"; 34 } 35 36 } 37 catch (Exception ex) 38 { 39 return "error"+ex; 40 } 41 42 43 44 } 45 #endregion