小程序 获取微信用户 openID

本文介绍了一种通过C#实现的小程序openID获取方法,包括定义数据模型、API调用及异常处理。通过示例代码,展示了如何从小程序传来的code中获取用户的唯一标识openID,并将其用于后续的业务逻辑中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建类 接收小程序返回的值(类名随便改,但不要修改类字段名)

  public class xcxModel
    {
        public string openid { get; set; }

        public string session_key { get; set; }
    }

在添加获取API的值的函数

  private string GetDataFromServerApi(string url, string body)
        {
            string str = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = 1500;
                if (!string.IsNullOrEmpty(body))
                {
                    byte[] data = Encoding.UTF8.GetBytes(body);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    request.ContentLength = data.Length;
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    str = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                //_logger.Error("获取小程序openID异常 exception:" + ex);
            }
            return str;

        }

获取小程序的openID,Get方法

 		[HttpGet]
        [Route("/GetopenID")]
        public string GetCode(string code)
        {
            string openid = "";
            try
            {
                // 微信小程序ID
                string appid = "***";
                // 微信小程序秘钥
                string secret = "***";
                // 根据小程序传过来的code想这个url发送请求
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
                // 发送请求,返回Json字符串
                string str = GetDataFromServerApi(url, "");
                // 转成Json对象 获取openid
                var jsondata = JsonConvert.DeserializeObject<xcxModel>(str);
                // 我们需要的openid,在一个小程序中,openid是唯一的
                openid = jsondata.openid;
                //_logger.Error("GetCode openid:" + openid);
            }
            catch (Exception ex)
            {
                //_logger.Error("GetCode Exception:" + ex.Message);
            }
            return openid;
        }

小程序中需要获取的地方

 wx.login({
        success: function (res) {
          if (res.code) {
            // 获取openID
            wx.request({
              url:  '***',
              data: {
                code: res.code
              },
              success: function (res) {
              //存入缓存
                wx.setStorageSync("OPEN_ID", res.data);
              }
            })
          } else {
            console.log('获取失败!' + res.errMsg)
          }
        }
      })

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值