微信获取手机号

前端


js

  //获取手机号授权
  getPhoneNumber: function(e) {
    let that = this;
    // 用户拒绝授权
    if(e.detail.errMsg == "getPhoneNumber:fail user deny") {
      wx.showToast({
        icon: "none",
        title: '请允许获取手机号,否则功能不可用!',
      })
      return
    }
    // 1.获取临时登录凭证code
    let code = '';
    wx.login({
      success: (res) => {
        code = res.code;
        this.getSessionKey(res.code, e.detail.encryptedData, e.detail.iv);
      }, 
    });
  },
  // 2.访问登录凭证校验接口获取session_key(后续改成后台实现)
  getSessionKey: function(js_code, encryptedData, iv) {
    util.request(api.GetSessionKey, {
      code: js_code
    }, 'POST').then(function (res) {
      console.log(encryptedData);
      console.log(iv);
      console.log(res);
    })
  }

后端

    /**
     * 微信小程序获取session_key
     */
    @RequestMapping(value = {"getSessionKey"}, method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject getSessionKey(@RequestBody JSONObject param) throws Exception {
        //获取session_key和openid
        PageData pd = Tools.readProperties("config/wxauth.properties");
        String uri = "https://api.weixin.qq.com/sns/jscode2session?appid="+pd.get("appid")+"&secret="+pd.get("secret")+"&js_code="+param.get("code")+"&grant_type=authorization_code";
        String result = Tools.doCurl(uri);
        return JSONObject.fromObject(result);
    }

    /**
     * 微信小程序通过session_key获取手机号
     * @param param{"code":"","nickname":""}
     * @return {"session_key":"","openid":""}
     */
    @RequestMapping(value = {"wxauth"}, method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject wxauth(@RequestBody JSONObject param) throws Exception {
        JSONObject json = new JSONObject();
        String encryptedData;
        try {// 解码
            encryptedData = URLDecoder.decode(param.getString("encryptedData"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("encryptedData,decode失败!\n" + e);
            json.put("errinfo", "encryptedData,decode失败");
            return json;
        }
        String phone = WechatDecryptDataUtil.deciphering(encryptedData, param.getString("session_key"), param.getString("iv"));
        json.put("phone", phone);
        return json;
    }

用到的工具类

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import org.bouncycastle.util.encoders.Base64;

/**
 * @function 微信工具类
 * @author: Liweihua
 * @date 2023-05-10 18:06
 */
public class WechatDecryptDataUtil {
    public static String deciphering(String encrypdata,String ivdata, String sessionkey) {
        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str="";
        try {
            str = decrypt(sessionKey,ivData,encrypData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }
    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}

	/**
	 * 读取Properties文件里的全部内容
	 * @param fileP  文件路径
	 */
	public static PageData readProperties(String fileP) {
		PageData pd = new PageData();
		Properties properties = new Properties();
		// 使用ClassLoader加载properties配置文件生成对应的输入流
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileP);
		try {
			// 使用properties对象加载输入流
			properties.load(in);
			//获取key对应的value值
			Enumeration enumeration = properties.propertyNames();
			while(enumeration.hasMoreElements()){
				String key = enumeration.nextElement().toString();
				pd.put(key,properties.getProperty(key));
			}
		} catch (IOException e) {
			System.out.println("读取文件内容出错");
		}
		return pd;
	}



    // 跳转url
    public static String doCurl(String uri) {
        String result = "";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map data = new HashMap();
                data.put("code", "001");
                data.put("name", "测试");

                HttpPost httpPost = new HttpPost(uri + "/test");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

你可能感兴趣的:(前端,javascript,css)