服务器后台是C#,通过小程序一键获取绑定的手机号
2022-11-18T02:54:42.png

用户点击获取用户手机号码按钮

<button class="weui-btn_cell weui-btn_cell-primary" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">一键获取手机号</button>

弹出授权图片
2022-11-18T02:56:49.png

小程序JS代码

//一键获取手机号
getPhoneNumber: function(e) {
  if (!e.detail.iv) {
        wx.showToast({
            title: '获取手机号失败',
            icon: 'none'
        })
        return;
  }
  var that = this;   
  wx.login({
    success: res1 => {
      wx.request({ 
        method: "get",
        url: getApp().globalData.apiUrl,
        data: {
          opt: 'getTelNum',
          code: res1.code,
          IV: e.detail.iv,
          encryptedData: e.detail.encryptedData,
          shopid: getApp().globalData.shopId
        },
        success: function (res) {
          app.globalData.user_tel=res.data.tel;
          console.log("bbbbbbbbbbbb"+res1.code);
        },
        fail: function (res) {
          
        }
      })
    }
  })
},

C#服务器后台代码

public void getTelNum()
        {
            string code = Request["code"];
            string shopid = Request["shopid"];
            string encryptedData = Request["encryptedData"];
            string IV = Request["IV"];
            string Str = GetJson("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
            WeixinOpenid info = JsonConvert.DeserializeObject<WeixinOpenid>(Str);

            //获取微信绑定手机号
            string tel = getPhoneNumber(encryptedData, IV, info.session_key);
            string strJson = "{\"tel\":\"" + tel + "\"  }"; 
            Response.Write(strJson);
            Response.End();
        }

        //获取微信绑定手机号
        private string getPhoneNumber(string encryptedData, string IV, string Session_key)
        {
            try
            {

                byte[] encryData = Convert.FromBase64String(encryptedData);
                System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(Session_key);
                rijndaelCipher.IV = Convert.FromBase64String(IV);
                rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
                rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);

                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                return model.phoneNumber;

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

标签: none

评论已关闭