Java微信获取小程序手机号,肯定能拿到

1.微信官方api文档
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
Java微信获取小程序手机号,肯定能拿到_第1张图片
2.获得结果
Java微信获取小程序手机号,肯定能拿到_第2张图片
3.代码实现
WxPhoneUtil工具类,附带主方法测试
pom.xml加入

<dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.57</version>
</dependency>
package com.shifen.userservice.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;

public class WxPhoneUtil {
    public static void main(String[] args) {
        String result = decryptData(
                "前端传回",
                "sessionKey登录时后台获取的",
                "前端传回"
        );
        System.out.println("result = " + result);
    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        return new String(
                decryptOfDiyIV(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }

    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }
}

4.业务层,根据自己业务需求

@ApiOperation(value = "获取手机号", notes = "获取手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "iv", value = "iv", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "session_key", value = "session_key", required = true, paramType = "query", dataType = "string"),
    })
    @GetMapping("/user/getUserPhone")
    public Result getUserPhone(String encryptedData, String iv, String session_key) {
        try {
            UserVoDetail user = UserContextHolder.getInstance().getUser();
            Long gid = user.getUserId();
            String relust = WxPhoneUtil.decryptData(encryptedData, session_key, iv);
            Map<String, Object> map = JSON.parseObject(relust, HashMap.class);
            User user1 = userService.getUserInfo(gid);
            user1.setPhone(String.valueOf(map.get("phoneNumber")));
            userService.updateUserInfo(user1);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统出错");
        }

    }

session_key在登陆时获取,可在登陆成功传给前端,调用方法是在由前端返回

Java微信获取小程序手机号,肯定能拿到_第3张图片

获取到的结果字符串是这样的(以下是官方)

{
    "phoneNumber": "13580006666",
    "purePhoneNumber": "13580006666",
    "countryCode": "86",
    "watermark":
    {
        "appid":"APPID",
        "timestamp": TIMESTAMP
    }
}

获取手机号,json字符串转map,根据key获取即可

 Map<String, Object> map = JSON.parseObject(relust, HashMap.class);
  String phone= String.valueOf(map.get("phoneNumber"))

最终结果保存到数据库
在这里插入图片描述

你可能感兴趣的:(后端Java)