【⼩程序】java后台获取⽤户信息(解密encryptedData)
⾸先java 后端依赖两个jar
<dependency>
<groupId&dehaus.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>
有趣的java小程序</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 (de){
success:function(res){
console.log(res)
var jsonData = {
code: de,
encryptedData: ptedData,
iv: res.iv
};
url: 'domain/miniapp/login/userinfo',
header: { 'Content-Type': 'application/json' },
method:'POST',
data: jsonData,
success: res => {
console.log(res.data)
wx.hideLoading()
this.setData({
projectlist: t
})
}
})
}
})
}
}
})
服务器端代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.channels.ScatteringByteChannel;
import java.security.AlgorithmParameters;
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;
pto.BadPaddingException;
pto.Cipher;
pto.IllegalBlockSizeException;
pto.NoSuchPaddingException;
pto.spec.IvParameterSpec;
pto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
dehaus.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(WeChatController.class);
@RequestMapping("/init")
@ResponseBody
public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {
String echostr = this.initWechat(request);
PrintWriter out = Writer();
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) ("code");
String  encryptedData =  (String) ("encryptedData");
String  iv =  (String) ("iv");
String sessionkey = getSessionKey(code);
JSONObject userInfo = UserInfo(encryptedData, sessionkey, iv);
System.out.println(userInfo);
}
public String getSessionKey(String code) {
String url = "api.weixin.qq/sns/jscode2session?appid=" + WeChatConfig.APP_ID + "&secret="
+ WeChatConfig.APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
String reusult = CommonUtil.httpGet(url);
String reusult = CommonUtil.httpGet(url);
JSONObject oppidObj = JSONObject.parseObject(reusult);
String openid = (String) ("openid");
String session_key = (String) ("session_key");
return session_key;
}
public String initWechat(HttpServletRequest request) {
String signature = Parameter("signature"); // 加密需要验证的签名
String timestamp = Parameter("timestamp");// 时间戳
String nonce = Parameter("nonce");// 随机数
String echostr = Parameter("echostr");
WeixinMessageDigest wxDigest = Instance();
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 = Instance("AES/CBC/PKCS7Padding","BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = Instance("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) {
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {            e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return null;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。