获取微信小程序access token

2022-04-26  本文已影响0人  一介书生独醉江湖
# 第三方平台   调用服务平台接口
https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/servicemarket/serviceMarket.invokeService.html
# 微信证件OCR识别能力开放
https://developers.weixin.qq.com/community/develop/doc/000888093f4650c1c5c8208405bc01?highLine=%25E5%25BE%25AE%25E4%25BF%25A1OCR%25E8%25AF%2586%25E5%2588%25AB
# OCR接口文档
https://developers.weixin.qq.com/doc/offiaccount/Intelligent_Interface/OCR.html
# 获取access token
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
# access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token
# 正常获取access_token之后,应该放入redis或其他key-value数据库里面,否则每次调用OCR接口时,都要重新调用获取token的接口
# access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
# 我这里为了代码的简洁,所以去掉了redis部分

# 下面的wx_appid、wx_secret 换成你自己的,就可以直接运行;
# 打印如下:
# accessToken : 56_0qVdwb5EV2G7s6X-9gUMu49kmvMtd0GAjNxjNuHsk-zrhT94yQ6aH57nrfj9ZRxDTNUXEX0S9M6LuhGrkrwTkgg0_CqWV3eTFlFGLiadLzM3x9EweFMZpexLhQh67H0mD2f0TNPtrK9aDeyxWOHiAFALDW
package com.example.favoritecode;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author ds
 * @Date 2022-04-26
 */
public class WxOcrTest {

    public static void main(String[] args) throws Exception {
        String accessToken = getWxAccessToken();
        System.out.println("accessToken : " + accessToken);

    }

    /**
     * 获取Access token
     * access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token
     * @return
     * @throws Exception
     */
    public static String getWxAccessToken() throws Exception {

        String ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token";
        String wx_appid = "your app appid";
        String wx_secret = "your app secret";
        String getAccessTokenParam = "appid=" + wx_appid + "&secret=" + wx_secret + "&grant_type=client_credential";
        // 获取凭证
        String wechatResult = HttpUtils.get(ACCESS_TOKEN_API, getAccessTokenParam);
        JSONObject jsonObj = JSONObject.parseObject(wechatResult);
        // 解析微信返回消息
        String token = null;
        if (jsonObj != null) {
            token = (String) jsonObj.get("access_token");
        }
        if (StringUtils.isEmpty(token)) {
            System.err.println("******************** getWxAccessToken ********************");
            System.err.println("**   获取微信凭证失败");
            System.err.println("**   wx_appid:" + wx_appid);
            System.err.println("**   wx_secret:" + wx_secret);
            System.err.println("**   ACCESS_TOKEN_API:" + ACCESS_TOKEN_API);
            System.err.println("**   请求参数:" + getAccessTokenParam);
            System.err.println("**   返回结果:" + wechatResult);
            throw new Exception("调用微信接口,取 AccessToken 失败,返回结果:" + wechatResult);
        }

        return token;
    }
}

package com.example.favoritecode;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

/**
 * @author ds
 * @date 2022.04.26
 */
public class HttpUtils {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String get(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String api = "";
            if (StringUtils.isEmpty(param)) {
                api = url;
            } else {
                api = url + "?" + param;
            }
            URL realUrl = new URL(api);
            // 打开和URL之间的连接
            if (api.startsWith("https://")) {
                HttpsURLConnection httpConn = (HttpsURLConnection) realUrl.openConnection();
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                //第一个参数为 返回实现指定安全套接字协议的SSLContext对象。第二个为提供者
                TrustManager[] tm = {new MyX509TrustManager()};
                sslContext.init(null, tm, new SecureRandom());
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                httpConn.setSSLSocketFactory(ssf);
                // 设置通用的请求属性
                httpConn.setRequestProperty("accept", "*/*");
                httpConn.setRequestProperty("connection", "Keep-Alive");
                httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                httpConn.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = httpConn.getHeaderFields();
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } else {
                URLConnection httpConn = realUrl.openConnection();
                // 设置通用的请求属性
                httpConn.setRequestProperty("accept", "*/*");
                httpConn.setRequestProperty("connection", "Keep-Alive");
                httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                httpConn.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = httpConn.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}

class MyX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

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

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
上一篇下一篇

猜你喜欢

热点阅读