用微信的东西,总要避免到各种与微信那边的交互。
1.首先要有个接口,证明你是服务端(填写服务器配置)
接入概述 | 微信开放文档
主代码
/*** 服务器配置验证* @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 "失败";}
Md5Tools工具类
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;}}
}
2.JSSDK验证,前端需要这个去请求权限
概述 | 微信开放文档
签名算法
@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 {//获取tokenString 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);//获取ticketString 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());}}
SignatureUtil工具类
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,去微信比对,如果你生成的和微信生成一样,就没问题。
微信 JS 接口签名校验工具