您的当前位置:首页正文

二维码简介

2024-11-10 来源:个人技术集锦

微信公共接口(token、ticket)

package com.nanning.agriculture.trace.service.impl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.nanning.agriculture.trace.controller.MyX509TrustManager;
import com.nanning.agriculture.trace.service.IWeiXinService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
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;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 微信 Service实现
 *
 * @author wanggeying
 * @date 2021-08-13
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class WeiXinServiceImpl implements IWeiXinService{


    public String getToken(String appid, String secret) {
        // 获取公众号access_token的链接
        String access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String requestUrl = access_token.replace("APPID", appid).replace("APPSECRET", secret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        System.out.println("获取access_token,与微信地址交互输出的jsonObject是:"+jsonObject);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                String access=jsonObject.getString("access_token");
                if(access==null || access.equals("")){
                    String error=jsonObject.getString("errmsg");
                    return error;
                }else{
                    return access;
                }
            } catch (JSONException e) {
            }
        }
        return null;
    }


    public String getTicket(String accessToken) {
        // 获取公众号jsapi_ticket的链接
        String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        if (accessToken != null) {
            String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", accessToken);
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            System.out.println("获取ticket值,输出jsonObject是:"+jsonObject);
            // 如果请求成功
            if (null != jsonObject) {
                try {
                    return jsonObject.getString("ticket");
                } catch (JSONException e) {
                }
            }
        } else {
            System.out.println("*****token为空 获取ticket失败******");
        }
        return null;
    }

    public JSONObject getSignature(String appid,String secret,String nonceStr,String url) {//String ticket,
        String signature = "";
        //String nonceStr = "lh123456";//获取noncestr
        //String nonceStr = "lhru6eQ0Dj8oCLLCiY";//获取noncestr
        String access_token = getToken(appid,secret);//获取access_token
        String jsapi_ticket = getTicket(access_token);//获取jspai_ticket
        String timestamp = Long.toString(System.currentTimeMillis() / 1000); //获取timestamp
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;//将四个数据进行组合,传给SHA1进行加密
        System.out.println("str:"+str);
        //sha1加密
        signature = SHA1(str);
        System.out.println("signature:"+signature);

        JSONObject result = new JSONObject();
        result.put("timestamp",timestamp);
        result.put("signature",signature);
        return result ;
    }

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        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 httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Top