【小程式】java 後臺獲取使用者資訊(解密encryptedData)
阿新 • • 發佈:2019-01-11
首先java 後端依賴兩個jar
<dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-core</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version>1.46</version> </dependency>
流程:1.需要微信前端呼叫wx.login介面獲取code。 然後再呼叫wx.getuserInfo介面獲取使用者的資訊。
獲取到的資訊包含有使用者基本資訊(這裡面沒有openid),以及encryptedData,這個encryptedData含有完整使用者資訊(含openid),但是資料是加密的,需要伺服器端來解析。
2. 前端呼叫伺服器介面,將獲取到的code,以及encryptedData,和iv一起傳送到後端。
3. 伺服器在解密encryptedData之前,需要呼叫微信介面獲取sessionkey. 有了encryptedData才能解密。
前端呼叫程式碼:
wx.login({ success: function (res_login) { if (res_login.code){ wx.getUserInfo({ success:function(res){ console.log(res) var jsonData = { code: res_login.code, encryptedData: res.encryptedData, iv: res.iv }; wx.request({ url: 'http://domain/miniapp/login/userinfo', header: { 'Content-Type': 'application/json' }, method:'POST', data: jsonData, success: res => { console.log(res.data) wx.hideLoading() this.setData({ projectlist: res.data.content }) } }) } }) } } })
伺服器端程式碼:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.channels.ScatteringByteChannel;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.codehaus.xfire.util.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.wqdata.miniapp.utils.CommonUtil;
import com.wqdata.miniapp.utils.WeChatConfig;
import com.wqdata.miniapp.utils.WeixinMessageDigest;
@Controller
@RequestMapping("/wechat")
public class WeChatController {
private Logger logger = Logger.getLogger(WeChatController.class);
@RequestMapping("/init")
@ResponseBody
public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {
String echostr = this.initWechat(request);
PrintWriter out = response.getWriter();
out.print(echostr);
out.close();
out = null;
}
@RequestMapping(value = "/login/userinfo", method = RequestMethod.POST)
@ResponseBody
public void login(@RequestBody String infoData, HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println("infoData" + infoData);
JSONObject dataObj = JSONObject.parseObject(infoData);
String code = (String) dataObj.get("code");
String encryptedData = (String) dataObj.get("encryptedData");
String iv = (String) dataObj.get("iv");
String sessionkey = getSessionKey(code);
JSONObject userInfo = this.getUserInfo(encryptedData, sessionkey, iv);
System.out.println(userInfo);
}
public String getSessionKey(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeChatConfig.APP_ID + "&secret="
+ WeChatConfig.APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
String reusult = CommonUtil.httpGet(url);
JSONObject oppidObj = JSONObject.parseObject(reusult);
String openid = (String) oppidObj.get("openid");
String session_key = (String) oppidObj.get("session_key");
return session_key;
}
public String initWechat(HttpServletRequest request) {
String signature = request.getParameter("signature"); // 加密需要驗證的簽名
String timestamp = request.getParameter("timestamp");// 時間戳
String nonce = request.getParameter("nonce");// 隨機數
String echostr = request.getParameter("echostr");
WeixinMessageDigest wxDigest = WeixinMessageDigest.getInstance();
boolean bValid = wxDigest.validate(WeChatConfig.TOKEN, signature, timestamp, nonce);
logger.info("initWechat --- valid:" + bValid);
if (bValid) {
return echostr;
}
return "";
}
/**
* 獲取資訊
*/
public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
// 被加密的資料
byte[] dataByte = Base64.decode(encryptedData);
// 加密祕鑰
byte[] keyByte = Base64.decode(sessionkey);
// 偏移量
byte[] ivByte = Base64.decode(iv);
try {
// 如果金鑰不足16位,那麼就補足. 這個if 中的內容很重要
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/PKCS7Padding","BC");
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 (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return null;
}
}