微信小程序——获取用户手机号(Java后台)

最后有完整代码
1、获取code

onShow: function() {
   var that = this;
         //获取用户的本地缓存数据,userinfo信息是在用户授权登录时保存的
         var n = wx.getStorageSync("userinfo");
         //当本地缓存的用户名称不为""或者null时,设置userinfo信息
         if(n.nickName != '' && n.nickName != null){
             this.setData({
                 userinfo: n,
                 hasUserInfo:true,
                 canIUseGetUserProfile:true
             })
             // 通过wx.login获取登录凭证(code),然后通过code去获取我们用户的openid
             wx.login({
               success:(res)=>{
                   console.log(res);
                   that.getOpenId();
               },
             })
         }
 },

2、利用code获取sessionkey
小程序端:

getOpenId(){
   var that=this
  wx.login({
    success (res) {
      if (res.code) {
        //发起网络请求
        wx.request({
          url: '自己的Control路径',
          data: {
            code: res.code
          },
          method: 'get',
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function(res) { //res就是接收后台返回的数据
            console.log(res.data);
            that.setData({
              sessionkey:res.data
            })
          },
        })
      } else {
        console.log('登录失败!' + res.errMsg)
      }
    }
  })
 },
  

Java后台:

 @RequestMapping("名称")                             //获取sessionid
    @ResponseBody
    public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String appId="自己的appid";
        String secret="小程序密钥";
        String code=request.getParameter("code");
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //这三个参数就是之后要填上自己的值。
        //替换appid,appsecret,和code
        String requestUrl = url;
        //调用get方法发起get请求,并把返回值赋值给returnvalue
        String  returnvalue=GET(requestUrl);
        System.out.println(requestUrl);//打印发起请求的url
        System.out.println(returnvalue);//打印调用GET方法返回值
        //定义一个json对象。
        JSONObject convertvalue=new JSONObject();

        //将得到的字符串转换为json
        convertvalue=(JSONObject) JSON.parse(returnvalue);


        System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
        System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
        //把openid和sessionkey分别赋值给openid和sessionkey
        String openid=(String) convertvalue.get("openid");
        String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.
        Gson gson=new Gson();
        String json = gson.toJson(sessionkey);
        Writer out = response.getWriter();
        out.write(String.valueOf(json));
        out.flush();
    }
    //发起get请求的方法。
    public static String GET(String url) {
        System.out.println("start");//打印发起请求的url
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // 异常记录
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 异常记录
            }
        }
        return result;
    }

获取小程序密钥:微信公众平台->开发管理->开发设置
3、获取iv和encryptedData并解密获取手机号

getPhoneNumber(e) { 
   var that=this;
   console.log("手机号:") 
   wx.request({
    url: '自己的Control路径',
    data: {
      sessionkey: that.data.sessionkey,
      iv:e.detail.iv,
      encryptedData:e.detail.encryptedData
    },
    method: 'get',
    header: {
      'content-type': 'application/json' //默认值
    },
    success: function(res) { //res就是接收后台返回的数据
      console.log(res.data);
    },
  })
 } 

java后台:

@RequestMapping("decryptS5")                      //解密获取手机号
    @ResponseBody
    public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sSrc=request.getParameter("encryptedData");
        String encodingFormat="utf-8";
        String sKey=request.getParameter("sessionkey");
        String ivParameter=request.getParameter("iv");
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            System.out.println(new String(original, encodingFormat));
            return new String(original, encodingFormat);
        } catch (Exception ex) {
            return null;
        }
    }

如果报错40029则可能是appid不对
4、完整代码
wxml:

<!--index.wxml-->
<view class="banner">
    <view class="topContainer">
        <view catchtap="showBcgImgArea">
            <image class="userinfo-avatar" mode="aspectFill" src="{{userinfo.avatarUrl}}"></image>
        </view>
        <view>
            <text class="userinfo-nickname">{{userinfo.nickName}}</text>
        </view>
    </view>
    <button wx:if="{{!hasUserInfo && canIUseGetUserProfile}}" open-type="getUserInfo" bindtap="getUserProfile" class="userLogin">
        点击登录
    </button>
    <button open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">获取用户手机号</button>
</view>

wxss:

.banner {
  border-radius: 10rpx;
  border: none;
  box-sizing: content-box;
  padding: 20rpx 0;
  width: 90%;
  height: 370rpx;
  margin: 20rpx auto;
  background:linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%);
  /* background-image:image("../../images/cloudbg.jpg"); */
  text-align: center;
}

.topContainer {
  width: 100%;
  height: 260rpx;
  background-size: 100%;
  border-radius: 9px;
}
.userinfo-nickname {
  color:black;
}
.userLogin{
  width: 50%;
  box-sizing: none;
  font-size: medium;
}
.userinfo-avatar {
  width: 150rpx;
  height: 150rpx;
  margin-bottom: 10rpx;
  border-radius: 50%;
}

js:

Page({
  data: {
         //用户基本信息(头像、昵称)
         userinfo: {
             avatarUrl:'../../images/ckbg1.png',
             nickName:'未授权'
         },
         //是否已经获取用户信息
         hasUserInfo: false,
         //是否可以调用获取信息得函数
         canIUseGetUserProfile: false,
         sessionkey:"",
         
     },
  //第一次获取用户信息
 getUserProfile : function(e){
         wx.getUserProfile({
           desc: '获取您的微信个人信息',
           success:(res)=>{
               this.setData({
                 userinfo:res.userInfo,
                 hasUserInfo:true
               })
               wx.setStorageSync('userinfo', res.userInfo)
           },
           fail:function(e){
               wx.showToast({
                 title: '你选择了取消',
                 icon: "none",
                 duration: 1500,
                 mask: true
               })
           }
         })
 },
  onLoad: function(n) {
     this.setData({
         canIUseGetUserProfile : true
     })
  
 },
 onShow: function() {
   var that = this;
         //获取用户的本地缓存数据,userinfo信息是在用户授权登录时保存的
         var n = wx.getStorageSync("userinfo");
         //当本地缓存的用户名称不为""或者null时,设置userinfo信息
         if(n.nickName != '' && n.nickName != null){
             this.setData({
                 userinfo: n,
                 hasUserInfo:true,
                 canIUseGetUserProfile:true
             })
             // 通过wx.login获取登录凭证(code),然后通过code去获取我们用户的openid
             wx.login({
               success:(res)=>{
                   console.log(res);
                   that.getOpenId();
               },
             })
         }
 },
 
 getOpenId(){
   var that=this
  wx.login({
    success (res) {
      if (res.code) {
        wx.request({
          url: '       ',
          data: {
            code: res.code
          },
          method: 'get',
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function(res) { //res就是接收后台返回的数据
            console.log(res.data);
            that.setData({
              sessionkey:res.data
            })
          },
        })
      } else {
        console.log('登录失败!' + res.errMsg)
      }
    }
  })
 },
 getPhoneNumber(e) { 
   var that=this;
   console.log("手机号:") 
   wx.request({
    url: '                   ',
    data: {
      sessionkey: that.data.sessionkey,
      iv:e.detail.iv,
      encryptedData:e.detail.encryptedData
    },
    method: 'get',
    header: {
      'content-type': 'application/json' //默认值
    },
    success: function(res) { //res就是接收后台返回的数据
      console.log(res.data);
    },
  })
 } 
 })

Java后台

 @RequestMapping("    ")                             //获取sessinoid
    @ResponseBody
    public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String appId="                      ";
        String secret="                    ";
        String code=request.getParameter("code");
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //这三个参数就是之后要填上自己的值。
        //替换appid,appsecret,和code
        String requestUrl = url;
        //调用get方法发起get请求,并把返回值赋值给returnvalue
        String  returnvalue=GET(requestUrl);
        System.out.println(requestUrl);//打印发起请求的url
        System.out.println(returnvalue);//打印调用GET方法返回值
        //定义一个json对象。
        JSONObject convertvalue=new JSONObject();

        //将得到的字符串转换为json
        convertvalue=(JSONObject) JSON.parse(returnvalue);


        System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
        System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
        //把openid和sessionkey分别赋值给openid和sessionkey
        String openid=(String) convertvalue.get("openid");
        String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.
        Gson gson=new Gson();
        String json = gson.toJson(sessionkey);
        Writer out = response.getWriter();
        out.write(String.valueOf(json));
        out.flush();
    }
    //发起get请求的方法。
    public static String GET(String url) {
        System.out.println("start");//打印发起请求的url
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // 异常记录
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 异常记录
            }
        }
        return result;
    }


    /**
     * 解密工具直接放进去即可
     */
    @RequestMapping("decryptS5")                      //解密获取手机号
    @ResponseBody
    public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sSrc=request.getParameter("encryptedData");
        String encodingFormat="utf-8";
        String sKey=request.getParameter("sessionkey");
        String ivParameter=request.getParameter("iv");
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            System.out.println(new String(original, encodingFormat));
            return new String(original, encodingFormat);
        } catch (Exception ex) {
            return null;
        }
    }
### Java环境下uni-app微信小程序获取用户手机号的方法 在Java环境中使用uni-app开发微信小程序获取用户手机号涉及多个方面。具体来说,在前端部分,通过调用微信提供的接口实现授权登录以及请求用户手机号码;而在服务端,则需处理来自客户端的数据验证与存储。 #### 客户端(uni-app) 为了能够成功获取用户手机号,应用程序需要先完成基础的登录操作[^2]: ```javascript // 登录函数定义 login() { let that = this; uni.login({ provider: 'weixin', success(res) { console.log('Login Success', res); // 将code发送给服务器换取openid等信息 that.getCode(); }, fail(err) { console.error('Login Failed', err); } }); } ``` 当应用已经获得了必要的权限之后,可以进一步尝试去取得用户的电话号码。这一步骤同样依赖于`wx.getPhoneNumber()` API 的调用: ```javascript getPhoneNumber(e){ if (!e.detail.errMsg || e.detail.errMsg !== "getPhoneNumber:ok") { wx.showToast({title:'您拒绝了提供手机号'}); return false; } else { const iv = e.detail.iv; const encryptedData = e.detail.encryptedData; // 发送加密数据至后台解密 uni.request({ url: `${this.serverUrl}/decryptPhone`, // 后台地址 method:"POST", data:{ code:this.code, iv:iv, encryptedData:encryptedData }, success:(res)=>{ console.log("Get Phone Number Result:",res.data.phoneNumber); } }) } } ``` 上述代码片段展示了如何捕获用户同意分享其手机号后的回调事件,并将获得的信息传递给后端进行下一步处理。 #### 服务端(Java) 对于Java编写的服务端而言,主要职责在于接收从前端传来的参数并对这些经过AES算法加密过的资料做解析工作。通常情况下会利用WeChat官方所提供的工具类或者第三方库来简化这个过程。下面给出了一段简单的Spring Boot风格的例子用于演示目的: ```java @RestController @RequestMapping("/api") public class WechatController { @PostMapping("/decryptPhone") public ResponseEntity<String> decryptPhone(@RequestBody Map<String, String> params) throws Exception{ WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appid); String session_key = getSessionKey(params.get("code")); // 自行实现此方法以交换session key JSONObject json = JSON.parseObject(pc.decrypt(encryptedData,params.get("iv"),session_key)); return ResponseEntity.ok(json.getString("pureMsg")); } private String getSessionKey(String js_code){ RestTemplate restTemplate=new RestTemplate(); HttpHeaders headers = new HttpHeaders(); HttpEntity entity = new HttpEntity(headers); ResponseEntity<Map> response=restTemplate.exchange( "https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code="+js_code+"&grant_type=authorization_code", HttpMethod.GET,entity,Map.class,"your_app_id","your_secret"); return (String)((LinkedHashMap)(response.getBody())).get("session_key"); } } ``` 这段程序说明了怎样设置一个RESTful Web Service 来接受来自uni-app的小程序请求,并执行相应的业务逻辑——即对接收到的数据实施解密动作从而得到真实的手机号码。 请注意以上仅为概念性的指导而非完整的解决方案,实际项目中还需要考虑更多的细节比如安全性保障措施、异常情况下的错误提示等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值