当前位置:   article > 正文

微信授权获取手机号

微信授权获取手机号

首先去微信官方文档可以看到获取手机号的接口需要用到token权限。因此我们需要先拿到token。

在获取个人信息授权时候可以直接在前端调用getUserProfile方法

  1. getUserProfile : function(){
  2. uni.getUserProfile({
  3. desc:'用于测试开发',
  4. success:function(infoRes){
  5. console.log(infoRes)
  6. },
  7. fail : function(err){
  8. console.log(err);
  9. }
  10. })
  11. }

 在开发工具中点击按钮可以看到开始拉取授权,需要主要的是,getUserProfile方法是一定要在用户参与操作下才能启用的,否则该方法无法被调用。 

 然后我们尝试获取手机号,需要用到open-type="getPhoneNumber" @getphonenumber="getTel"

其中getPhoneNumber是官方给我们封装好的函数,getTel是我自己随意写的方法名open-type则是微信开放能力的固定写法。

  1. getTel : function(res){
  2. console.log(res);
  3. let code = res.detail.code;
  4. console.log(res.detail.code);
  5. uni.request({
  6. url:"http://localhost:8080/wx/phone?code="+code,
  7. data:{},
  8. success: (res) => {
  9. console.log("取电话")
  10. console.log(res)
  11. }
  12. })
  13. }

 函数体中可以通过res.detail.code获取后端调用手机号接口所需要的code。

前端代码块:

  1. <template>
  2. <view class="content">
  3. <image class="logo" src="/static/logo.png"></image>
  4. <view class="text-area">
  5. <text class="title">{{title}}</text>
  6. </view>
  7. <button @click="getUserProfile" open-type="getPhoneNumber" @getphonenumber="getTel">开始体验</button>
  8. </view>
  9. </template>
  10. <script>
  11. export default {
  12. data() {
  13. return {
  14. title: 'Hello'
  15. }
  16. },
  17. onLoad() {
  18. uni.login({
  19. provider: 'weixin',
  20. success: function (loginRes) {
  21. uni.request({
  22. url: 'http://localhost:8080/wx/code?code='+ loginRes.code,
  23. data: {},
  24. success: (res) => {
  25. }
  26. });
  27. }
  28. });
  29. },
  30. methods: {
  31. getUserProfile : function(){
  32. uni.getUserProfile({
  33. desc:'用于开发测试',
  34. success:function(infoRes){
  35. console.log(infoRes)
  36. },
  37. fail : function(err){
  38. console.log(err);
  39. }
  40. })
  41. },
  42. getTel : function(res){
  43. console.log(res);
  44. let code = res.detail.code;
  45. console.log(res.detail.code);
  46. uni.request({
  47. url:"http://localhost:8080/wx/phone?code="+code,
  48. data:{},
  49. success: (res) => {
  50. console.log("取电话")
  51. console.log(res)
  52. }
  53. })
  54. }
  55. }
  56. }
  57. </script>
  58. <style>
  59. .content {
  60. display: flex;
  61. flex-direction: column;
  62. align-items: center;
  63. justify-content: center;
  64. }
  65. .logo {
  66. height: 200rpx;
  67. width: 200rpx;
  68. margin-top: 200rpx;
  69. margin-left: auto;
  70. margin-right: auto;
  71. margin-bottom: 50rpx;
  72. }
  73. .text-area {
  74. display: flex;
  75. justify-content: center;
  76. }
  77. .title {
  78. font-size: 36rpx;
  79. color: #8f8f94;
  80. }
  81. </style>

后端首先新建一个Util类构造获取token的方法,这里我们使用同步锁以应对高并发,保障线程安全。并使用双重校验,保证运行过程中不会出现因系统编译排序导致的逻辑问题(概率极低,相当于一个人一辈子被雷劈中十次)

  1. @Component
  2. public class WXUtil {
  3. String appId = "这里是APPID";
  4. String secret = "这里是小程序秘钥";
  5. String accessToken = "";
  6. LocalDateTime passTime = null;
  7. @Autowired
  8. RestTemplate restTemplate;
  9. public String getAccessToken() {
  10. LocalDateTime current = LocalDateTime.now();
  11. //同步锁,使用当前对象作为锁头(spring中bean的声明周期默认单例,可以配置,request、session)
  12. //第一次校验:如果一个对象抢到锁头。
  13. if (StringUtils.isEmpty(this.accessToken) || null == passTime || current.isAfter(passTime)) {
  14. synchronized (this) {
  15. //双重校验,第二次校验
  16. //预防代码编译顺序被打乱。
  17. if (StringUtils.isEmpty(this.accessToken) || null == passTime || current.isAfter(passTime)) {
  18. //申请获取token
  19. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId
  20. + "&secret=" + secret;
  21. ResponseEntity<JSONObject> wxResult = restTemplate.getForEntity(url, JSONObject.class);
  22. this.accessToken = wxResult.getBody().getString("access_token");
  23. Long expiresIn = wxResult.getBody().getLong("expires_in");
  24. passTime = current.plusSeconds(expiresIn);
  25. }
  26. }
  27. }
  28. return this.accessToken;
  29. }
  30. }

然后在获取到token后发送请求,获取到手机号信息。

  1. @RestController
  2. @RequestMapping("/wx")
  3. public class WxSystemController {
  4. String appId = "这里是APPID";
  5. String secret = "这里是小程序秘钥";
  6. @Autowired
  7. RestTemplate restTemplate;
  8. @Autowired
  9. IUserService IUserService;
  10. @Autowired
  11. WXUtil wxutil;//将util文件注入进来
  12. @GetMapping("/code")
  13. public JSONObject code(String code) {
  14. JSONObject result = new JSONObject();
  15. // 向微信发请求 获取onenId
  16. String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code="
  17. + code + "&grant_type=authorization_code";
  18. // 发送HTTP请求
  19. ResponseEntity<String> wxResult = restTemplate.getForEntity(url, String.class);
  20. // 把String转换成JSON
  21. JSONObject wxJsonObject = JSONObject.parseObject(wxResult.getBody());
  22. // 获取openId
  23. String openId = wxJsonObject.getString("openid");
  24. QueryWrapper<User> ifOppenIdqueryWaQueryWrapper = new QueryWrapper<>();
  25. ifOppenIdqueryWaQueryWrapper.eq("openId", openId);
  26. List<User> userList = IUserService.list(ifOppenIdqueryWaQueryWrapper);
  27. if (0 == userList.size()) {
  28. result.put("result", false);
  29. return result;
  30. } else {
  31. result.put("result", true);
  32. return result;
  33. }
  34. }
  35. @GetMapping("/phone")
  36. public JSONObject Phone(String code) {
  37. String accessToken = wxutil.getAccessToken();
  38. String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
  39. Map<String, Object> requestParam = new HashMap<String, Object>();
  40. requestParam.put("code", code);
  41. ResponseEntity<JSONObject> wxResult = restTemplate.postForEntity(url, requestParam, JSONObject.class);
  42. JSONObject phoneInfo = wxResult.getBody().getJSONObject("phone_info");
  43. return phoneInfo;
  44. }
  45. }

运行后可在微信开发者工具上打印出结果:

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号