微信小程序获取OpenID

项目:

openID在globalData定义

// 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          
          //获取openId
          var that = getApp();
          wx.request({
            url: '你的服务器接口地址',
            data: { 
              code: res.code
            },
            method: 'GET',
            header: { 'content-type': 'application/json' },
            success: function (openIdRes) {
              console.info("获取用户openId成功");
              that.globalData.openID = openIdRes.data.openid;
            },
            fail: function (error) {
              console.info("获取用户openId失败");
              this.globalData.openID = "失败2";
              console.info(error);
            },
            complete: function (openIdRes){
              //this.globalData.openID ="Complete";
            }
          })
        }
      }
    })
C#

 public async Task<Models.WXDPC_GetOpenIDModel> GetOpenID(string Code)
        {
            string url = "https://api.weixin.qq.com/sns/jscode2session";
            string appid = "你的appid";
            string secret = "你的secret";
            string grant_type = "authorization_code";
            string js_code = Code;
            string reauestUrl = url + "?"
                + nameof(appid) + "=" + appid + "&"
                + nameof(secret) + "=" + secret + "&"
                + nameof(grant_type) + "=" + grant_type + "&"
                + nameof(js_code) + "=" + js_code;
            HttpClient httpClient = new HttpClient();
            try
            {
                string json = await httpClient.GetStringAsync(reauestUrl);
                Models.WXDPC_GetOpenIDModel getOpenID = JsonConvert.DeserializeAnonymousType(json, new Models.WXDPC_GetOpenIDModel());
                return getOpenID;
            }
            catch { return null; }
        }

C# WXDPC_GetOpenIDModel

public class WXDPC_GetOpenIDModel
    {
        /// <summary>
        /// 
        /// </summary>
        public string session_key { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string openid { get; set; }
    }



展开阅读全文

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