这位怪蜀黍 中午的时光真难熬!还好有你在!

入坑微信小程序必经之路(九)发送 res.code 到C# API接口换取 openId, sessionKey

复制代码
// 登录
    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;
        }
复制代码

 

posted @   蟾宝  阅读(468)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示