微信小程序获取用户手机号码(后台asp版)

前端微信小程序获取code,后台使用asp获取session_key和openid;然后结合iv和encryptedData解密出微信用户手机号码

【效果图】
在这里插入图片描述

在这里插入图片描述

【开发流程】
第1步:wx.login获取code
第2步:传递code到服务器,获取session_key和openid
第3步:参考官方文档getPhoneNumber,获取iv和encryptedData
第4步:解密返回数据,获取手机号码

【第1步:wx.login获取code】
调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
用户登录凭证(有效期五分钟)。开发者需要在开发者服务器后台调用 auth.code2Session,使用 code 换取 openid 和 session_key 等信息

【第2步:传递code到服务器,获取session_key和openid】
官方文档地址
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
参考示例:GET 方法https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

小程序代码,wxml

<button type="primary" bindtap="mycode">获取code</button>

小程序代码,js

 mycode:function(e){
    wx.login({
      success:function(res){
        console.log(res)
        console.log(res.code)
        var code = res.code
        wx.request({
          url: 'http://www.yaoyiwangluo.com/tel/asp.asp',
          data:{
            code
          },
          success:function(res2){
            //console.log("服务器:" + res2)
            console.log("服务器:" + res2.data)
            console.log("openid:" + res2.data.openid)
            console.log("session_key:" + res2.data.session_key)
          }
        })

      }
    })
  }

后台asp代码

<!--#include file="Fun.asp" -->

<%
Response.Charset = "utf-8"
Session.CodePage = 65001
str_code = request.QueryString("code")
'response.write str_code

str_token = ""
'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
str_token  = str_token  & "https://api.weixin.qq.com/sns/jscode2session"
str_token  = str_token  & "?appid=wx686e9a0d46f8e***&secret=9f4a19057b35276dbf8710741b5fb***"
str_token  = str_token  & "&js_code="&str_code&"&grant_type=authorization_code"

neirong_token = getHTTPPage2(str_token)
response.write neirong_token

%>  

【第3步:参考官方文档getPhoneNumber,获取iv和encryptedData】
官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。
注意:目前该接口针对非个人开发者,且完成了认证的小程序开放(不包含海外主体)。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限。

【第4步:解密返回数据,获取手机号码】
官方文档:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
接口如果涉及敏感数据(如wx.getUserInfo当中的 openId 和unionId ),接口的明文内容将不包含这些敏感数据。开发者如需要获取敏感数据,需要对接口返回的加密数据( encryptedData )进行对称解密。 解密算法如下:
微信官方提供了多种编程语言的示例代码(点击下载)。
下载地址: https://res.wx.qq.com/wxdoc/dist/assets/media/aes-sample.eae1f364.zip

欢迎收看完整的视频课程
微信小程序获取用户手机号码(后台asp版)
在这里插入图片描述

发布了305 篇原创文章 · 获赞 45 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u013818205/article/details/103662862