微信公众号请求获取相关权限后端代码

发布时间:2024年01月03日

用微信的东西,总要避免到各种与微信那边的交互。

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 {
            //获取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());

        }
    }

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 接口签名校验工具

文章来源:https://blog.csdn.net/qq_38403590/article/details/135371094
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。