자바 위 챗 공식 번호 JS - SDK 서명 인터페이스 생 성

76469 단어 작은 편지
package com.zichan360.controller;

import com.alibaba.fastjson.JSONObject;
import com.zichan360.common.result.Result;
import com.zichan360.common.result.ResultUtil;
import com.zichan360.common.utils.MD5Util;
import com.zichan360.common.utils.weChatUtils.WeChatCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: WeChatController
 * @Author zhaohp
 * @Date 2019/2/18 14:57
 * @Description:       
 */

@RestController
@RequestMapping("/weChat")
@Api(description = "      ")
@Slf4j
public class WeChatController {

    @Value("${weChat.APP_ID}")
    private String APP_ID;
    @Value("${weChat.APP_SECRET}")
    private String APP_SECRET;
    @Value("${weChat.USER_CODE_GET_TOKEN_URL}")
    private String USER_CODE_GET_TOKEN_URL;
    @Value("${weChat.ACCESS_TOKEN}")
    private String ACCESS_TOKEN;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ApiOperation("  OpenId")
    @GetMapping("/saveOpenId")
    public Result saveOpenId(@RequestParam("code") @ApiParam(value = "code", required = true) String code) throws Exception {

        //  code     openId token
        String url = USER_CODE_GET_TOKEN_URL.replace("APPID", APP_ID).replace("SECRET", APP_SECRET).replace("JSCODE", code);
        JSONObject jsonObject = WeChatCommonUtil.httpsRequest(url, "GET", null);
        if (jsonObject.containsKey("openid")) {
            String openid = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");
            String token = MD5Util.md5(openid, sessionKey);
            //redis      
            redisTemplate.opsForValue().set("WeChatAppletAiExperience:weChat:session_key:" + token, openid + "," + sessionKey, 30, TimeUnit.MINUTES);
            return ResultUtil.success(token);
        }
        return ResultUtil.error(jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
    }

    @ApiIgnore
    @ApiOperation("        ")
   @GetMapping("/getToken")
    public JSONObject getToken() {
        //  redis  
        if (redisTemplate.hasKey("weixin:access_token")) {
            JSONObject jsonObject = new JSONObject();
            String accessToken = redisTemplate.opsForValue().get("weixin:access_token");
            Long expiresIn = redisTemplate.getExpire("weixin:access_token", TimeUnit.SECONDS);
            jsonObject.put("access_token", accessToken);
            jsonObject.put("expires_in", expiresIn);
            return jsonObject;
        }
        JSONObject jsonObject = WeChatCommonUtil.getToken(APP_ID, APP_SECRET);
        System.out.println(jsonObject.toJSONString());
        redisTemplate.opsForValue().set("weixin:access_token", jsonObject.getString("access_token"), jsonObject.getLong("expires_in"), TimeUnit.SECONDS);
        return jsonObject;
    }


    @GetMapping("/getTicket")
    public JSONObject getTicket(@RequestParam(value = "accessToken", required = false) String accessToken) {
        //  redis  
        if (redisTemplate.hasKey("weixin:jsapi_ticket")) {
            JSONObject jsonObject = new JSONObject();
            String ticket = redisTemplate.opsForValue().get("weixin:jsapi_ticket");
            Long expiresIn = redisTemplate.getExpire("weixin:jsapi_ticket", TimeUnit.SECONDS);
            jsonObject.put("ticket", ticket);
            jsonObject.put("expires_in", Math.toIntExact(expiresIn));
            jsonObject.put("errcode", 0);
            jsonObject.put("errmsg", "OK");
            return jsonObject;
        }
        if (StringUtils.isNotBlank(accessToken)) {
            redisTemplate.opsForValue().set("weixin:access_token", accessToken, 7200L, TimeUnit.SECONDS);
            return CommonUtil.getTicket(accessToken);
        }
        accessToken = getToken().getString("access_token");
        JSONObject jsonObject = WeChatCommonUtil.getTicket(accessToken);
        redisTemplate.opsForValue().set("weixin:jsapi_ticket", jsonObject.getString("ticket"), jsonObject.getLong("expires_in"), TimeUnit.SECONDS);
        return jsonObject;
    }


    /**
     *                  
     * 

* * * @param url URL * @param timestamp * @param ticket ticket * @param echostr * @return echostr */

@GetMapping("/getSignature") public Map<String, String> checkName(@RequestParam(name = "url") String url, @RequestParam(name = "timestamp", required = false) String timestamp, @RequestParam(name = "ticket", required = false) String ticket, @RequestParam(name = "echostr", required = false) String echostr) { if (StringUtils.isBlank(timestamp)) { timestamp = String.valueOf(System.currentTimeMillis() / 1000); } if (StringUtils.isBlank(echostr)) { echostr = RandomStringUtils.randomAlphanumeric(10); } if (StringUtils.isBlank(ticket)) { JSONObject jsonObject = getTicket(""); ticket = jsonObject.getString("ticket"); } logger.info(" - "); logger.info(" echostr :{}", echostr); /* / : *1. token、timestamp、nonce * 2. sha1 * 3. signature , */ logger.info(" - "); // 1. String sortString = sort(url, timestamp, ticket, echostr); logger.info(" - sha1 "); // 2.sha1 String signature = sha1(sortString); // // String signature = DigestUtils.sha1Hex(sortString); Map map = new HashMap<>(); map.put("appId", APP_ID); map.put("url", url); map.put("timestamp", timestamp); map.put("ticket", ticket); map.put("echostr", echostr); map.put("str", sortString); map.put("signature", signature ); return map; } /** * @Author zhaohp * @Date 2018/12/10 19:50 * @Param [signature, timestamp, ticket, echostr] * @Return java.lang.String * @Description: ASCII */ public String sort(String url, String timestamp, String ticket, String echostr) { return "jsapi_ticket=" + ticket + "&noncestr=" + echostr + "&timestamp=" + timestamp + "&url=" + url; } /** * @Author zhaohp * @Date 2018/12/10 19:51 * @Param [str] * @Return java.lang.String * @Description: sha1 */ public String sha1(String str) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); // 16 StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } /** * * * @param encrypdata * @param ivdata * @param loginKey * @return * @throws Exception */ @ApiOperation(" ") @GetMapping("/deciphering") public String deciphering(@ApiParam(value = "encrypdata", required = true) @RequestParam("encrypdata") String encrypdata, @ApiParam(value = "ivdata", required = true) @RequestParam("ivdata") String ivdata, @CookieValue("loginKey")String loginKey) { byte[] encrypData = Base64.decode(encrypdata); byte[] ivData = Base64.decode(ivdata); String sessionkey = redisTemplate.opsForValue().get("WeChatAppletAiExperience:weChat:session_key:" + loginKey); sessionkey = sessionkey.substring(sessionkey.indexOf(",") + 1); byte[] sessionKey = Base64.decode(sessionkey); String str = ""; try { str = decrypt(sessionKey, ivData, encrypData); } catch (Exception e) { e.printStackTrace(); } log.info(str); return str; } public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception { AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); // return new String(cipher.doFinal(encData), "UTF-8"); } }
package com.zichan360.common.utils.weChatUtils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

/**
 * @ClassName: WeChatCommonUtil 
 * @Author zhaohp
 * @Date 2018/12/10 18:18
 * @Description:      
 */
@Slf4j
public class WeChatCommonUtil {

    public static String token_url;
    @Value("${weChat.ACCESS_TOKEN}")
    public void token_url(String url) {
        WeChatCommonUtil.token_url = url;
    }

    public static String ticket_url;
    @Value("${weChat.ACCESS_TICKET}")
    public void ticket_url(String url) {
        WeChatCommonUtil.token_url = url;
    }

    /***
     * @Author zhaohp
     * @Date 2018/12/14 10:57
     * @Param [requestUrl     , requestMethod     (GET、POST), outputStr      ]
     * @Return com.alibaba.fastjson.JSONObject
     * @Description: JSONObject(  JSONObject.get(key)     json      )
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            //   SSLContext  ,                
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            //    SSLContext     SSLSocketFactory  
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            //       (GET/POST)
            conn.setRequestMethod(requestMethod);

            //  outputStr  null        
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                //       
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            //           
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            //     
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("    :{}", ce);
        } catch (Exception e) {
            log.error("https    :{}", e);
        }
        return jsonObject;
    }

    /***
     * @Author zhaohp
     * @Date 2018/12/14 10:56
     * @Param [appid, appsecret]   ,  
     * @Return com.zichan360.domain.weChat.Token
     * @Description:         
     */
    public static JSONObject getToken(String appid, String appsecret) {
        String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        //   GET      
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        return jsonObject;
    }


    /*** 
     * @Author zhaohp
     * @Date 2018/12/14 10:56 
     * @Param [accessToken]
     * @Return com.alibaba.fastjson.JSONObject
     * @Description:   access_token
     */
    public static JSONObject getTicket(String accessToken) {

        String requestUrl = ticket_url.replace("ACCESS_TOKEN", accessToken);
        //   GET      
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        return jsonObject;
    }

}

package com.zichan360.common.utils.weChatUtils;

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @ClassName: MyX509TrustManager
 * @Author zhaohp
 * @Date 2018/12/10 18:18
 * @Description:      
 */
public class MyX509TrustManager implements X509TrustManager {

    //        
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    //         
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    //       X509    
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
weChat:
  #  token
  USER_CODE_GET_TOKEN_URL: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
  ACCESS_TOKEN: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  ACCESS_TICKET: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  APP_ID: ************
  APP_SECRET: ***********************

좋은 웹페이지 즐겨찾기