【微信小程序】如何获取用户手机号授权登录

一. 前置条件

  • 目前该接口针对非个人开发者,且完成了认证的小程序开放(不包含海外主体),也就是说只针对企业认证小程序开放。若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限。
  • 在使用该接口时,用户可使用微信绑定手机号进行授权,也添加非微信绑定手机号进行授权。若开发者仅通过手机号作为业务关联凭证,在重点场景可适当增加短信验证码逻辑。

二. 开始接入

1. 服务端接入

1.1 引入maven配置

<dependency>
   <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>${wechat.sdk.version}</version>
</dependency>

1.2 配置小程序相关信息

#微信小程序配置
wx.ma.enable=true
wx.ma.configs[0].appId=xxxxxxxxx
wx.ma.configs[0].secret=xxxxxxxxx

1.3 相关配置类文件代码编写

WxMaConfiguration.java

package com.xxx

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ConditionalOnProperty("wx.ma.enable")
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
    private WxMaProperties properties;

    private static WxMaService wxMaService;
    private static Map<String, WxMaProperties.Config> maConfigs = Maps.newHashMap();


    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    @Bean
    public static WxMaService getMaService() {
        return wxMaService;
    }

    public static WxMaProperties.Config getMaConfig(String wxAppId) {
        WxMaProperties.Config config = maConfigs.get(wxAppId);
        if (config == null) {
            throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置,请核实!", wxAppId));
        }
        return config;
    }

    @PostConstruct
    public void init() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("没有读取到配置!");
        }

        WxMaService maService = new WxMaServiceImpl();
        maService.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                            config.setAppid(a.getAppId());
                            config.setSecret(a.getSecret());
                            config.setToken(a.getToken());
                            config.setAesKey(a.getAesKey());
                            config.setMsgDataFormat(a.getMsgDataFormat());
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        wxMaService = maService;
        maConfigs = configs.stream().collect(Collectors.toMap(WxMaProperties.Config::getAppId, config -> config));
    }
}

WxMaProperties.java

package com.xxxx;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

@Data
@ConfigurationProperties(prefix = "wx.ma")
public class WxMaProperties {

    private List<Config> configs;

    @Data
    public static class Config {
        /**
         * 设置微信小程序的appId
         */
        private String appId;

        /**
         * 设置微信小程序的Secret
         */
        private String secret;

        /**
         * 设置微信小程序消息服务器配置的token
         */
        private String token;

        /**
         * 设置微信小程序消息服务器配置的EncodingAESKey
         */
        private String aesKey;

        /**
         * 消息格式,XML或者JSON
         */
        private String msgDataFormat;
    }
}

1.4 登录相关业务代码

  WxMaService maService = WxMaConfiguration.getMaService();
  WxMaJscode2SessionResult jsCodeResult = maService.jsCode2SessionInfo(request.getCode());

  WxMaPhoneNumberInfo newPhoneNoInfo = maService.getUserService().getNewPhoneNoInfo(request.getPhoneCode());
  if(Objects.isNull(newPhoneNoInfo)) {
      throw new CustomException(ResultCode.LOGIN_ERROR);
  }

2. 小程序端接入

wxml vant

  <van-button round type="info" open-type="getPhoneNumber" bind:getphonenumber="getPhoneNumber">微信授权登录</van-button>

js

  getPhoneNumber(e) {
    if(e.detail.code == undefined) {
      //拒绝获取手机号 无需登录操作
      return;
    }
	//将 e.detail.code 传到后端接口进行登录

3. 完成后的效果如下

飞鸽投递登录页

4. 至此,小程序的获取手机号授权登录接入完成了,是不是so easy。

三. 体验更多

想体验更多小程序的功能,欢迎扫以下的小程序码,博主自研产品,捧个场,感谢Thanks♪(・ω・)ノ
飞鸽投递

下一期想讲解哪一部分,欢迎评论区留言 ~

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值