微信小程序获取电话号码

目录

微信小程序创建项目配置底部导航栏
微信小程序滚动播放内容
微信小程序功能中心模块开发
微信小程序个人中心页面开发
微信小程序获取电话号码
微信小程序显示列表数据
微信小程序显示分页列表
微信小程序添加插屏广告
微信小程序添加激励式广告

最终效果可扫码查看
微信小程序获取电话号码_第1张图片

概述

使用之前已经完成的个人中心页,在这个基础上直接修改。原地址:https://blog.csdn.net/m0_58095675/article/details/121077886
流程分为三步:

  1. 默认情况下没有登录
  2. 点击登录按钮后,提示是否绑定手机号
  3. 点击确定后,获取到手机号码

对应效果如下
微信小程序获取电话号码_第2张图片
微信小程序获取电话号码_第3张图片

微信小程序获取电话号码_第4张图片

技术总结

1 小程序登录wx.login获取code(后台使用该code得到session_key openid unionid)
2 获取手机号码 open-type=“getPhoneNumber”
3 本地存储的使用wx.getStorageSync(‘mobile’) 和 wx.setStorageSync(“mobile”, phoneNumber);
4 后端代码使用的java,如果需要可留言,或添加上图中联系电话对应的微信。

样式

样式仅做了微调,调整了button控件的百分比,其他的和之前代码一样

page {
  background-color: #F8F8F8;
  height: 100%;
  font-size: 32rpx;
  line-height: 1.6;
}

.content { 
  width: 100%; 
  padding: 10px;
  padding-top: 25px;
  justify-content: space-around; 
 } 

 .content-text {
  width: 100%;
  display: flex;
  font-size: 16px;
  line-height: 26px;
}

.content-text-mobile {
  color: #2782D7;
}

.mine-text {
  width: 100%;
  height:120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2782D7;
}
.mine-text.text{
   color: #fff;
   font-size: 44rpx;
   line-height: 51rpx;
   width: 100%;
 }

流程

官方提醒

在获取手机号码的文档中,微信官方有这样的提示:“在回调中调用 wx.login 登录,可能会刷新登录态。此时服务器使用 code 换取的 sessionKey 不是加密时使用的 sessionKey,导致解密失败。建议开发者提前进行 login;或者在回调中先使用 checkSession 进行登录态检查,避免 login 刷新登录态。”

所以,将之前的代码调整为只要onShow就调用一次wx.login,而不是放到获取手机号码的成功回调用。

登录部分微信官方地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
获取手机号码微信官方地址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

后台数据

写了一个获取手机号码的接口
http://yr.lootaa.com/location/wechat/mobile?code=&encryptedData=&iv=&appid=&secret=
几个请求参数说明:
code:wx.login的时候有,必填
encryptedData:获取手机号码的时候有,必填
iv:获取手机号码的时候有,必填
appid:小程序的appid,如果不填,后台默认使用的我自己的
secret:小程序的secret,如果不填,后台默认使用的我自己的

如果请求成功,返回的数据格式

{
  "code": 200,
  "message": "",
  "data": {
    "phoneNumber": "15010563146",
    "purePhoneNumber": "15010563146",
    "countryCode": "86",
    "openid": "omu1A5cusH9k7lKLJVoJGJ6AEkhI",
    "unionid": "oHD8W0tMu5f26AWGvP4sru6lUBzw"
  }
}

其中,unionid不一定有,需要将小程序绑定到微信开放平台才有。开放平台地址https://open.weixin.qq.com/
绑定小程序的时候有个坑,开放平台提示主体比如一致,但是如果没有认证的话,微信就认为开放平台属于个人,即便小程序和开放平台所属公司相同也不行。认证费300大洋。

代码

Page({
  data: {
    login: false,
    code: '',
    userMobile: ''
  },
  onShow: function (options) {
    var that = this;
    var mobile = wx.getStorageSync('mobile');
    var openid = wx.getStorageSync('openid');
    var unionid = wx.getStorageSync('unionid');
    if (mobile && openid && unionid) {
      that.setData({
        userMobile: mobile
      });
      this.setData({
        login: true
      });
    } else {
      this.setData({
        login: false
      });
      wx.login({
        success(res) {
          if (res.code) {
            console.log(res.code)
            that.setData({
              code: res.code
            })
          } else {
            console.log('登录失败!' + res.errMsg)
          }
        }
      })
    }
  },

  call: function () {
    wx.makePhoneCall({
      phoneNumber: '15010563146'
    })
  },

  userLogin: function (e) {
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })
    var that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      console.log(e.detail.iv)
      console.log(e.detail.encryptedData)
      var url = '这里是后台接口地址,如果需要Java版本的可留言?code=' +
        encodeURIComponent(encodeURIComponent(this.data.code)) + '&encryptedData=' + encodeURIComponent(encodeURIComponent(e.detail.encryptedData)) + '&iv=' + encodeURIComponent(encodeURIComponent(e.detail.iv)) + '&appid=&secret=';
      console.log(url)
      wx.request({
        url: url,
        success(res) {
          console.log(res.data.data)
          if (res.data.code != 200) {

          } else {
            wx.setStorageSync("mobile", res.data.data.phoneNumber);
            wx.setStorageSync("openid", res.data.data.openid);
            wx.setStorageSync("unionid", res.data.data.unionid);
            that.setData({
              userMobile: res.data.data.phoneNumber
            });
            that.setData({
              login: true
            });

          }
        }
      })

    }

  }

})

布局

获取手机号码按钮比如用button,同时open-type=“getPhoneNumber”,用bindgetphonenumber指定获取的方法。


  
    {{userMobile}} 欢迎您
  


   
    
  


  提供集装箱、零担、专线运输的数据支持业务,定制开发服务,欢迎来电垂询。


  联系电话15010563146,微信同号



后端代码

后端使用的java编写,为了便于自己测试,请求参数都加上了appid、secret、iv、encryptedData等,真实业务自然是不需要的,直接本地代码配置文件中即可。
入口代码,控制层

	@ApiOperation(value = "获取手机号", notes = "")
	@GetMapping("/mobile")
	public AppResult queryMobile(@RequestParam(required=true, value="code") String code, 
			@RequestParam(required=true, value="iv") String iv,
			@RequestParam(required=true, value="encryptedData") String encryptedData,
			@RequestParam(required=false, value="appid") String appid, 
			@RequestParam(required=false, value="secret") String secret) throws Exception {
		MobileQueryDto param = new MobileQueryDto();
		param.setCode(URLDecoder.decode(code, "utf-8"));
		param.setIv(URLDecoder.decode(iv, "utf-8"));
		if(StringUtils.isNotBlank(appid)) {
			param.setAppid(param.getAppid());
		}
		if(StringUtils.isNotBlank(secret)) {
			param.setSecret(param.getSecret());
		}
		param.setEncryptedData(URLDecoder.decode(encryptedData, "utf-8"));
		return wechatService.queryMobile(param);
	}

服务层代码

	@Override
	public AppResult queryMobile(MobileQueryDto param) throws Exception {
		String codeUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + param.getAppid() + "&secret=" + param.getSecret()
				+ "&js_code=" + param.getCode() + "&grant_type=authorization_code";
		String result = Jsoup.connect(codeUrl).method(Method.GET).ignoreContentType(true).execute().body();
		System.out.println(result);
//{"session_key":"msNg6nBO0dlGo\/Bvst6AXg==","openid":"omu1A5cusH9k7lKLJVoJGJ6AEkhI","unionid":"oHD8W0tMu5f26AWGvP4sru6lUBzw"}
		JSONObject json = JSON.parseObject(result);
		if(!json.containsKey("openid")) {
			return new AppResult().failure("获取数据失败 " + result);
		}
        String result2 = AesCbcUtil.decrypt(param.getEncryptedData(), json.getString("session_key"), param.getIv(), "UTF-8");
        JSONObject json2 = JSON.parseObject(result2);
        if(!json2.containsKey("phoneNumber")) {
        	return new AppResult().failure("获取号码失败 " + result);
        }
        MobileQueryVo vo = new MobileQueryVo();
        vo.setCountryCode(json2.getString("countryCode"));
        vo.setPhoneNumber(json2.getString("phoneNumber"));
        vo.setPurePhoneNumber(json2.getString("purePhoneNumber"));
        vo.setOpenid(json.getString("openid"));
        vo.setUnionid(json.getString("unionid"));
//		{"phoneNumber":"15010563146","purePhoneNumber":"15010563146","countryCode":"86","watermark":{"timestamp":1635753887,"appid":"wxea2d4a5f6537f71f"}}
        return new AppResult(vo);
	}

你可能感兴趣的:(从头搭建微信小程序,微信小程序,小程序)