// 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey if(res.code){ //获取到code wx.request({ url: this.globalData.url+'WxGetOpenid', data:{ json_code:res.code, }, method:'GET', header: { 'content-type': 'application/x-www-form-urlencoded', }, success(res2){ var data=JSON.parse(res2.data); var data1=JSON.parse(data.data); var openid=data1.openid; var session_key=data1.session_key; if(openid!=null&&session_key!=null){ wx.setStorageSync('openid', openid); } } }) }else{ wx.showToast({ icon:'none', title: '微信登录失败,请重新进入小程序', duration:3000 }) } } })
C# API 接口
/// <summary> /// 根据用户code,获取openid /// </summary> /// <param name="json_code"></param> /// <returns></returns> [HttpGet, Route("api/WxGetOpenid"), AllowAnonymous] public string WxGetOpenid(string json_code) { string AppID = "我是小程序ID"; string AppSecret = "我是小程序密钥"; string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppID + "&secret=" + AppSecret + "&js_code=" + json_code + "&grant_type=authorization_code"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); 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 retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); var obj = new { data = retString, Success = true }; Formatting microsoftDataFormatSettings = default(Formatting); string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSettings); return result; }