微信小程序--對接用戶信息(後端解密 unionId 和手機號)
背景
最近做小程序的工程。剛好負責用戶體系構建。這個需求的用例有以下幾點:
- 既然是微信小程序,不需要用戶登錄,免得用戶感覺繁瑣。
- 預留用戶信息,以便用戶留檔
交互流程
這個流程還是比較清楚的。這一套下來主要是爲了獲取用戶的信息(openId,unionId)。有以下幾個比較重要的背景:
- 同一個用戶在同一個企業下的小程序中和公衆號中的 openId 是不一樣的。但是 unionId 是一樣的。
- 獲取 unionId 有以下限制和開放的場景。大部分說的是關注了公衆號既可以直接獲取到 unionId
- 沒有關注公衆號,直接進入小程序如何獲取 unionId
小程序前端授權獲取用戶加密信息 。調用接口爲 wx.getUserInfo ,或者使用小程序封裝好的組件
<!-- 需要使用 button 來授權登錄 -->
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登錄</button>
<view wx:else>請升級微信版本</view>
獲取到的返回 Json 中的加密字段爲 encryptedData 。解密方式有三種:
- 前端解密。官網提供了DEMO
- JAVA 後端解密。官網未提供 DEMO 。
基於安全考慮,我們選擇後端解密。
使用的 包
package com.yiyibang.internethospital.controller.rest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
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 javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.HttpRequest;
import org.jeecgframework.core.util.JSONHelper;
import org.jeecgframework.core.util.PropertiesUtil;
import org.jeecgframework.core.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bantu.frame.core.utils.UUIDUtils;
import com.yiyibang.internethospital.constant.BusinessConstants;
import com.yiyibang.internethospital.constant.PageCodeEnum;
import com.yiyibang.internethospital.model.dataobject.HmPatientAccountDO;
import com.yiyibang.internethospital.model.dataobject.YebWxxcxpayDO;
import com.yiyibang.internethospital.model.viewobject.RestResponseObjectVO;
import com.yiyibang.internethospital.service.PatientService;
import net.sf.json.JSONObject;
核心解密方法,適用於 unionId 和 手機號
private static AjaxJson decryptS5(String encrypData, String sessionKey, String ivParameter) {
AjaxJson j = new AjaxJson();
logger.info("wxxcx decryptS5 param ,encrypData:" + encrypData + ",sessionKey:" + sessionKey + ",ivParameter:"
+ ivParameter);
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] raw = decoder.decodeBuffer(sessionKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] myendicod = decoder.decodeBuffer(encrypData);
byte[] original = cipher.doFinal(myendicod);
String originalString = new String(original, "UTF-8");
JSONObject jsonObject = JSONHelper.toJSONObject(originalString);
j.setObj(jsonObject);
return j;
} catch (Exception ex) {
logger.info("wxxcx Decryption applet mobile phone number abnormal,error info ==>:", ex);
j.setSuccess(false);
j.setMsg("解密小程序手機號異常");
return j;
}
}
調用方法
// 獲取用戶信息 加密串
String encryptedData = request.getParameter("encryptedData");
if (StringUtils.isEmpty(encryptedData)) {
restResponseObjectVO.setStatus(PageCodeEnum.INPUT_ARGS_EMPTY.getCode());
restResponseObjectVO.setDesc("encryptedData 爲空!");
logger.error("xcxdecryptUnionId || encryptedData is empty");
return restResponseObjectVO;
}
// 獲取微信的解密串
String sessionKey = SessionUtils.getSessionToken();
if (StringUtils.isEmpty(sessionKey)) {
restResponseObjectVO.setStatus(PageCodeEnum.INPUT_ARGS_EMPTY.getCode());
restResponseObjectVO.setDesc("sessionKey is empty!");
logger.error("xcxdecryptUnionId || wxxcx sessionKey is empty! ");
return restResponseObjectVO;
}
String iv = request.getParameter("iv");
if (StringUtils.isEmpty(iv)) {
restResponseObjectVO.setStatus(PageCodeEnum.INPUT_ARGS_EMPTY.getCode());
restResponseObjectVO.setDesc("請輸入待解密的iv");
logger.error("xcxdecryptUnionId || wxxcx iv is empty");
return restResponseObjectVO;
}
AjaxJson obj = decryptS5(encryptedData, sessionKey, iv);
我自己已經驗證通過,就不上效果截圖了!!!