微信小程序根据wx.login得到的code从Csharp后台获取openid和session_key(后台实现了4种方式调用jscode2session)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_40333655/article/details/90447500

首先微信小程序部分代码:
pages文件夹下usrinfo页面,路径pages/usrinfo/usrinfo

wx.login得到code,根据code调用后台api部分:

// pages/usrinfo/usrinfo.js

  //点击微信登录
  wechatAction:function(e)
  {
    console.log(e);
    //用户点击授权
    //先临时保存获取到的微信用户信息
    const {nickName,avatarUrl} = JSON.parse(e.detail.rawData)
    this.setData({
      nickName:nickName,   //昵称
      avatarUrl:avatarUrl  //头像
    })
    //获取微信code
    this.reqWechatCode()
  },

  //微信登录:获取code
  reqWechatCode:function(){
    //授权接口登录接口
    let that = this
    //从微信获取code
    wx.showLoading({
      title:'获取code'
    })
    wx.login({
      success:function(res){
        console.log(res)
        if(res.code){
          that.setData({
            code:res.code
          })
          wx.getUserInfo({
            success:function(res){
              //保存微信登录参数
              const {encryptedData,iv,signature,rawData} = res
              that.setData({
                encryptedData:encryptedData,
                iv:iv,
                signature:signature,
                rawData:rawData
              })          
              //根据code向服务器发送登录请求获取token
              that.wxLoginReq(that.data.code)
            }
          })
        }else{
          wx.showToast({
            title:'获取code失败,请重试',
            icon:'none'
          })
        }
        wx.hideLoading()
      }
    })
  },

  //根据获取到的code向服务器发送登录请求获取token
  wxLoginReq:function(code){
    let that = this
    console.log("wxLoginReq:",code)
    wx.showLoading({
      title:'获取token中',
    })
    //拿到code再加上encrytedData,iv,rawData,signature等参数,请求token
    let encryptedData = that.data.encryptedData
    let iv = that.data.iv
    let signature = that.data.signature
    let rawData = that.data.rawData
    var req = require('../../utils/util.js')
    //请求成功
    let success = function(res){
      console.log("request sucesss : ",res)
      wx.hideLoading()
      //缓存token
      const{token,user_id} = res.data.data
      let userInfo = {
        token:token,
        user_id:user_id,
        nickName:that.data.nickName,
        avatarUrl:that.data.avatarUrl
      }
    }

    //请求失败
    let fail = function(res){
      wx.hideLoading()
      wx.showToast({
        title:'获取token失败,请重试',
        icon:'none'
      })
    }

    //登录请求
    req.reqLogin(code,encryptedData,iv,rawData,signature,success,fail)
  },

路径pages/utils/util
通过wx.request调用后台的具体实现

const reqLogin = (code, encryptedData, iv, rawData, signature, success, fail) => {
  wx.request({
    url: 'http://********/api/Values/login', // 仅为示例,非真实的接口地址
    method:"POST",
    data:{
      'encryptedData': encryptedData,
      'iv':iv,
      'rawData':rawData,
      'signature':signature,
      'js_code': code
    },
    header:{
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8'//'application/json' //默认值
    },
    success(res)
    {
      console.log(res);
      success(res);
    },
    fail:function(res)
    {
      console.log(res)
      fail(res)
    }
  })
}

module.exports = {
  formatTime: formatTime,
  reqLogin: reqLogin
}

后台使用的VS2015平台下,WEB API工程。
新建工程后,修改了下路由设置。
在WebApiConfig.cs文件中修改

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var format = GlobalConfiguration.Configuration.Formatters;
            //默认输出方式为xml和json,清除XML则只有json了。清除默认xml
            format.XmlFormatter.SupportedMediaTypes.Clear();
//通过参数设置返回格式
format.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("t", "json", "application/json"));
format.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("t", "xml", "application/xml"));
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

控制器直接使用的ValuesContorller.cs, 没有新增控制器。
后台http请求的一种方式如下

        [HttpPost]
        public void login([FromBody]JObject ob)
        {
            //临时登录凭证code 获取 session_key 和 openid
            string js_code = Convert.ToString(ob["js_code"]);
            //此处填写自己小程序的appid和secret
            string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=自己的appID&secret=自己的secret&js_code=" + 自己的code+ "&grant_type=authorization_code";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "textml;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string jsonData = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            var res = new
            {
                data = jsonData,
                Success = true
            };
            Formatting microsoftDataFormatSettings = default(Formatting);
            string result = JsonConvert.SerializeObject(res, microsoftDataFormatSettings);
            //向客户端写出内容
            //https://blog.csdn.net/hk8846/article/details/1648711?utm_source=blogxgwz1
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Write(result);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

具体源码

展开阅读全文

没有更多推荐了,返回首页