微信小程序获取电话号码

目录

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

最终效果可扫码查看
可查看效果二维码

概述

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

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

对应效果如下
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

技术总结

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指定获取的方法。

<block wx:if="{{login==true}}">
  <view class="mine-text">
    <text class="mine-text.text">{{userMobile}} 欢迎您</text>
  </view>
</block>
<block wx:else>
  <view class="mine-text"> 
    <button open-type="getPhoneNumber" bindgetphonenumber='userLogin' class="mine-text.text">您尚未登录,点击登录</button>
  </view>
</block>
<view class="content">
  <text class="content-text">提供集装箱、零担、专线运输的数据支持业务,定制开发服务,欢迎来电垂询。</text>
</view>
<view class="content" bindtap='call'>
  <text class="content-text">联系电话<text class="content-text-mobile">15010563146</text>,微信同号</text>
</view>

<ad style="padding-top:40px" unit-id="adunit-6b070048c763394d" ad-type="video" ad-theme="white"></ad>

后端代码

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

	@ApiOperation(value = "获取手机号", notes = "")
	@GetMapping("/mobile")
	public AppResult<MobileQueryVo> 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<MobileQueryVo> 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<MobileQueryVo>().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<MobileQueryVo>().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<MobileQueryVo>(vo);
	}
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lootaa

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值