用微信的东西,总要避免到各种与微信那边的交互。
/**
* 服务器配置验证
* @param
* @return
*/
@PassToken
@GetMapping("/giveWxCheck")
public String giveWxCheck(@RequestParam(required = false) String signature, @RequestParam(required = false) String timestamp, @RequestParam(required = false) String nonce, @RequestParam(required = false) String echostr) {
String[] array = {"需要填写的token", timestamp, nonce};
Arrays.sort(array);
System.out.println("微信发来的是"+signature);
String str = Md5Tools.sha1(StringUtils.join(array));
System.out.println("我生成的是"+s);
if (str.equals(signature)) {
return echostr;
}
return "失败";
}
package com.dengta.tanzhiwcustomermarket.tools;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Md5Tools {
public static String generateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
//生成随机字符串
public static String suijiStr(){
// 指定随机字符串的长度
int length = 16;
// 可选的字符集合
String charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 使用安全的随机数生成器生成随机字符串
SecureRandom secureRandom = new SecureRandom();
StringBuilder noncestr = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = secureRandom.nextInt(charset.length());
noncestr.append(charset.charAt(randomIndex));
}
// 打印生成的随机字符串
//System.out.println("noncestr=" + noncestr);
return noncestr.toString();
}
public static String sha1(String input){
// 将输入字符串转换为字节数组
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
byte[] inputBytes = input.getBytes();
byte[] digestBytes = messageDigest.digest(inputBytes);
StringBuilder stringBuilder = new StringBuilder();
for (byte b : digestBytes) {
stringBuilder.append(String.format("%02x", b));
}
System.out.println(stringBuilder);
return stringBuilder.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
@PassToken
@ApiOperation(value = "微信公众号token SDK")
@RequestMapping(value = "/wxSdkInfo2", method = {RequestMethod.POST})
public CommonResult wxSdkInfo2(@RequestBody CustomerMarket market){
if(market.getUrl()==null||market.getUrl()==""){
return CommonResult.failed("必须传入当前网页的url");
}
String appId="xx";
String appSecret ="xxx";
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
"appid="+appId+"&secret="+appSecret;
try {
//获取token
String access_token=null;
JSONObject jsonObject = HttpUtils.httpGet(url);
System.out.println("1.------------请求微信access_token的返回值:"+jsonObject);
if(jsonObject.getString("access_token")!=null){
access_token = jsonObject.getString("access_token");
Integer expires_in = jsonObject.getInteger("expires_in");//设置过期时间
}else {
logger.info("错误,请求微信获取access_token失败"+url);
return CommonResult.failed("获取微信access_token失败");
}
System.out.println("access_token是"+access_token);
//获取ticket
String ticket =null;
url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
"access_token=" + access_token +
"&type=jsapi";
jsonObject = HttpUtils.httpGet(url);
System.out.println("2.------------请求微信ticket的返回值:"+jsonObject);
if(jsonObject.getString("ticket")!=null){
ticket = jsonObject.getString("ticket");
Integer expires_in = jsonObject.getInteger("expires_in");
}else{
logger.info("错误,请求微信获取ticket失败"+url);
return CommonResult.failed("获取微信ticket失败");
}
System.out.println("ticket是"+ticket);
//生成签名
String nonceStr = Md5Tools.suijiStr();
//生成时间戳
long currentTimeMillis = System.currentTimeMillis();
long currentTimestampInSeconds = currentTimeMillis / 1000;
String[] parameters = new String[]{"jsapi_ticket=" + ticket, "timestamp=" + currentTimestampInSeconds,
"noncestr=" + nonceStr, "url=" + market.getUrl()};
String signature = SignatureUtil.generateSignature(parameters);
JSONObject rs = new JSONObject();
rs.put("appId",appId);
rs.put("timestamp",currentTimestampInSeconds);
rs.put("nonceStr",nonceStr);
rs.put("signature",signature);
logger.info("封装返回的结果是"+rs);
return CommonResult.success(rs);
} catch (Exception e) {
e.printStackTrace();
return CommonResult.failed(e.toString());
}
}
package com.dengta.tanzhiwcustomermarket.tools;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class SignatureUtil {
public static String generateSignature(String[] parameters) throws NoSuchAlgorithmException {
Arrays.sort(parameters);
StringBuilder stringBuilder = new StringBuilder();
for (String parameter : parameters) {
stringBuilder.append(parameter).append("&");
}
System.out.println("拼接的字符是"+stringBuilder.toString());
String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
System.out.println("切分后的是"+substring);
// appKey
// stringBuilder.append("key=").append(appKey);
String signature = Md5Tools.sha1(substring);
return signature;
}
}
最后拿返回的请求还有日志的ticket,去微信比对,如果你生成的和微信生成一样,就没问题。