WeixinUtil.java 3.91 KB
package com.topdraw.weixin.util;

import com.topdraw.config.WeixinInfoConfig;
import com.topdraw.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Component
@Slf4j
public class WeixinUtil {


    private static WeixinInfoConfig WEIXININFOCONFIG;

    @Autowired
    public void setWeixinInfoConfig(WeixinInfoConfig weixinInfoConfig) {
        WEIXININFOCONFIG = weixinInfoConfig;
    }

    public static Map<String, String> getWeixinInfoByAppid(String appid) {
        if (StringUtils.isBlank(appid)) {
            throw new RuntimeException("wxAppid can not be null");
        }
        List<Map<String, String>> list = WEIXININFOCONFIG.getList();
        Optional<Map<String, String>> weixinInfoOptional = list.stream().filter(o -> o.get("appid").equals(appid)).findFirst();
        if (!weixinInfoOptional.isPresent()) {
            throw new RuntimeException("wxAppid error, appid is : " + appid);
        }
        return weixinInfoOptional.get();
    }


    public static Map<String, String> getWeixinInfoByIndex(Integer index) {
        List<Map<String, String>> list = WEIXININFOCONFIG.getList();
        if (list.size() < index + 1) {
            throw new RuntimeException("wxinfo error, index out of range : {}" + index);
        }
        return list.get(index);
    }
    /**
     * 使用SHA1算法对字符串数组进行加密
     *
     * @param strList
     * @return
     */
    public static String encodeUsingSHA1(String... strList) {
        //将strList的值进行字典排序
        Arrays.sort(strList);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < strList.length; i++) {
            content.append(strList[i]);
        }

        return doEncodeUsingSHA1(content.toString());
    }


    /**
     * SHA1实现
     *
     * @return sha1加密后的字符串
     */
    private static String doEncodeUsingSHA1(String inStr)  {
        byte[] byteArray ;

        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byteArray = sha.digest(inStr.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("no sha-1 algorithm");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("unsupported utf-8 encoding");
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            sb.append(Integer.toString((byteArray[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    /**
     * 公众号,小程序后台配置服务器,初次检验时使用
     * @throws IOException
     */
    public static void doGet(HttpServletRequest request, HttpServletResponse response, Map<String, String> weixinInfo) throws IOException {
        log.info("doGet receive WeChat server request parameters:{}", request.getParameterMap());
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echoStr = request.getParameter("echostr");
        String[] arr = new String[]{weixinInfo.get("token"), timestamp, nonce};
        String encrypt = WeixinUtil.encodeUsingSHA1(arr);
        if (encrypt.equals(signature)) {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(echoStr.getBytes());
            outputStream.flush();
        }
    }


}