微信小程序授权获取手机号

微信小程序获取手机号官方文档链接:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

wxml文件 点击事件:


前端JS代码截图:
微信小程序授权获取手机号_第1张图片
java 后台代码:

import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
	 * @author kemi
	 * 微信小程序绑定手机号  不发送验证码
	 * @param request
	 * @param encryptedData
	 * @param iv
	 * @param session_key
	 * @return
	 */
    @PostMapping("binding/mobilePhone")
	@ResponseBody
	public ReturnJsonUtil getPhone(HttpServletRequest request, @Param("encryptedData")String encryptedData,@Param("iv")String iv,@Param("session_key")String session_key){
		JSONObject obj=getPhoneNumber(session_key,encryptedData,iv);
		String phone=obj.get("phoneNumber").toString();
		return weChatService.bindingPhoneNew(phone,userId);
	}

	/**
	 * 解密手机号
	 * @author kemi
	 * @param session_key
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
	public JSONObject getPhoneNumber(String session_key,String encryptedData,String iv ){
		byte[] dataByte = Base64.decode(encryptedData);
		byte[] keyByte = Base64.decode(session_key);
		byte[] ivByte = Base64.decode(iv);
		try {
			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				return JSONObject.parseObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return  null;
	}

你可能感兴趣的:(微信小程序授权获取手机号)