java后台微信小程序获取手机号

首先我们获取手机号需要合法域名的比如(https://www.baidu.com)自己的域名

在这里我们看,我这个请求地址是会提示不合法的,所以无法请求
在这里插入图片描述
现在我们利用合法的域名来获取手机的接口,是Ok的
在这里插入图片描述
在这里插入图片描述

话不多说,我们直接干代码

首先wxml文件显示的ui

  <view class='head head-height'>
    <block wx:if="{{phone==null||phone==''}}">
      <view class="userinfo">
        <image class="userinfo-avatar" src="../me/img/p.jpg" mode="cover"></image>
      </view>
      <button class="login-button head-height" open-type="getPhoneNumber" type='primary' bindgetphonenumber="getPhoneNumber" hover-class> 获取手机号登录 </button>
    </block>
    <block wx:else>
      <view class="userinfo">
        <image bindtap="bindViewTap" class="userinfo-avatar" src="../me/img/p.jpg" mode="cover"></image>
        <text class="userinfo-nickname">{{userName}}</text>
      </view>
    </block>
  </view>
  <view class="hr"></view>
<block wx:if="{{phone==null||phone==''}}">
    <view><text>\n</text></view>
    <button open-type="getPhoneNumber" type='primary' bindgetphonenumber="getPhoneNumber">更换绑定手机</button>
    <text>\n</text>
    <button type="primary" bindtap='clearStorage'>退出登录</button>
  
    
</block>
<block wx:else>
<view class='item'>
  <view class="title" style="margin-left:35%; font-size:20px;font-weight:bold">XX科技</view>
  <view class="detail2">
  </view>
</view>
<view class='item'>
  <view class="title">用户名称:{{userName}}</view>
  <view class="detail2">
  </view>
</view>
<view class='item'>
  <view class="title">用户别名:{{userid}}</view>
  <view class="detail2">
  </view>
</view>
<view class='item'>
  <view class="title">手机号码:{{phone}}</view>
  <view class="detail2">
  </view>
</view>

<view><text>\n</text></view>
<button open-type="getPhoneNumber" type='primary' bindgetphonenumber="getPhoneNumber">更换绑定手机</button>
<text>\n</text>
<button type="primary" bindtap='clearStorage'>退出登录</button>

</block>

然后是wxss文件 就是样式

.head-height {
  height: 240rpx;
  line-height: 240rpx;
  font-size: 25px;
}

.head {
  display:flex;
  width: 100%;
  background-color: #15c261;
  align-items: center;
}

.login-button {
  /* opacity: 0;  */
  width: 100%;
  /* position: fixed; */
  
}

.userinfo {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  position: fixed;
}

.userinfo-avatar {
  width: 150rpx;
  height: 150rpx;
  margin: 30rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #333333;
  font-size: 25px;
}

/* 个人中心下面 */
 .hr {
  width: 100%;
  height: 15px;
  background-color: #f4f5f6;
}

.item {
  display: flex;
  flex-direction: row;
}

.title {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  font-size: 15px;
}

.detail2 {
  font-size: 15px;
  position: absolute;
  right: 10px;
  height: 50px;
  line-height: 50px;
  color: #888;
}

.line {
  border: 1px solid #ccc;
  opacity: 0.2;
}

/* .userview{
  width: 80%;
  background-color: aqua;
} */


随后是我们主要的地方,请求方法的地方 微信小程序js文件

//获取应用实例

const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 用户登录信息
    userInfo: {},
    userName:"",
    userid:"",
    // 用户的openid
    userInfoid: "",
    // phone: wx.getStorageSync('phone'),
    phone:"",
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that = this;
  getPhoneNumber: function (e) {
    var that = this;
    wx.login({
      success: res => {
        // 获取到用户的 code 之后:res.code
        console.log("用户的code:" + res.code);
        // 可以传给后台,再经过解析获取用户的 openid
        // 或者可以直接使用微信的提供的接口直接获取 openid ,方法如下:
        wx.request({
          method: "POST",
          //首先这里去得到当前用户的session_key(下面请求接口写你自己的地址)
          url: app.globalData.serverUrl+'/Asset/getsessionkey',
          data: {
            code:res.code
          },
          header: {
            'Content-Type': 'application/json' // 默认值
          },
          success: res => {
            // 获取到用户的 session_key
            console.log("用户的session_key:" + res.data.data);
          
            wx.checkSession({
              success: function () {
                var ency = e.detail.encryptedData;
                var iv = e.detail.iv;
                var sessionk = res.data.data;
                if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
                  wx.showToast({
                    title: '您拒绝了授权',
                    icon: 'loading',
                    duration: 2000
                  })

                } else {//同意授权
                //如果同意了,就去解密并且获取用户手机号码
                  wx.request({
                    method: "POST",
                    url: app.globalData.serverUrl+'/Asset/WXgetPhone',  //请求的地址根据你自己实际情况来
                    data: {
                      encrypdata: ency,
                      ivdata: iv,
                      sessionkey: sessionk
                    },
                    header: {
                      'Content-Type': 'application/json' // 默认值
                    },
                    success: (res) => {
                      console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~");
                      var phone = res.data.phoneNumber;
                       //1.存用户信息到本地存储(我这里存在本地,你也可以弹出来看一下)
                       wx.setStorageSync('phone',phone)
                      that.onLoad();
                    }, fail: function (res) {
                      console.log("解密失败~~~~~~~~~~~~~");
                    
                    }
                  });

                }

              },

              fail: function () {

                console.log("session_key 已经失效,需要重新执行登录流程");

                that.wxlogin(); //重新登录

              }

            });


          }
        });
      }
    });
 },
 onShow: function () {
   
 },
 clearStorage:function(e){
   var that = this;
  wx.showModal({
    title: '提示',
    content: '是否退出账号',
    success (res) {
      if (res.confirm) {
        wx.clearStorageSync();
        that.setData({
           userName:"",
           userid:"",
           phone:""
         })
        app.globalData.userid="";
        wx.switchTab({
          url: '../work/work'
        })
      } else if (res.cancel) {
        
      }
    }
  })
 },


})

下面看看我们获取请求的接口controller

/**
 * 获取微信小程序手机号控制类
 */
@Controller
@RequestMapping("/Asset")
public class AssetController {
    /**
     * 微信小程序登录获取session_key
     * https://api.weixin.qq.com/sns/jscode2session
     */
    @PostMapping(value = "/getsessionkey")
    @ResponseBody
    public BaseResponse getsessionkey(@RequestBody Map map)throws Exception {

        String appid = "wx860b3a275b1de0674";  //你自己的,这里我乱写的
        String secret = "f224f4720f28ced1ea5f51d19245c7e4d";  //你自己的,这里我乱写的
        String grant_type = "authorization_code";
        String js_code = String.valueOf(map.get("code"));
        String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容(转换成json对象)
        System.err.println(sr);
        JSONObject json = JSON.parseObject(sr);
        // 获取会话密钥(session_key)
        String session_key = json.get("session_key").toString();
        BaseResponse response = new BaseResponse(StatusCode.Success);
        response.setData(session_key);
        return response;

    }
    /**
     * 微信小程序
     * 解密并且获取用户手机号码
     * @param
     * @param
     * @param
     * @return
     * @throws
     */
    @PostMapping(value = "/WXgetPhone")
    @ResponseBody
    public String deciphering(@RequestBody Map map)throws Exception {
        byte[] encrypData = org.apache.commons.codec.binary.Base64.decodeBase64(String.valueOf(map.get("encrypdata")));
        byte[] ivData = org.apache.commons.codec.binary.Base64.decodeBase64(String.valueOf(map.get("ivdata")));
        byte[] sKey = Base64.decodeBase64(String.valueOf(map.get("sessionkey")));
        String decrypt = decrypt(sKey,ivData,encrypData);
        return decrypt;

    }
//    微信小程序
    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData),"UTF-8");
    }
    }
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值