聚水潭授权到期重新授权


/**
 * 
 * 聚水潭授权到期重新授权
 */
public class JstTest01 {

	private static final Logger logger = LoggerFactory.getLogger(JstTest01.class);

    private static final String SIGN_METHOD_MD5 = "md5";

    // TOP服务地址,正式环境需要设置为https://openapi.jushuitan.com
    private static final String url = "/open/orders/single/query";
    private static final String serverUrl = "https://openapi.jushuitan.com";
    private static final String appKey = "44fff47a4cbe4c5590f76dab5ad8139e"; // 可替换为您的应用的appKey
    private static final String appSecret = "153196f0be8b42518b3736791957e64f"; // 可替换为您的应用的appSecret
//    private static final String accessToken = "a3530755a69e4e7a975553de8d60694b"; // 必须替换为授权得到的真实有效accessToken
  private static final String accessToken = "bee99a6fd11e4323ab5ae5e6bd5bddbe"; // 必须替换为授权得到的真实有效accessToken

    
    private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

    
    
    
//    public static void main(String[] args) throws IOException {
//
//    String string =     sendRequest(accessToken, "{\"page_index\":\"1\",\"page_size\":\"100\",\"nicks\":[\"越购优品\"]}", url);
//        System.out.println(string);
//    }


    /**
     * 生成新sign  https://openweb.jushuitan.com/doc?docId=40
     *
     * @param str
     * @return
     */
    public static String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SIGN_METHOD_MD5);
            mdTemp.update(str.getBytes(StandardCharsets.UTF_8));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }


   // 签名
    public static String signTopRequest(Map<String, String> params, String secret, String signMethod) {
        // 第一步:检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步:把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }

        for (String key : keys) {
            String value = params.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }
        return createSign(query.toString());
    }


    /**
     * 店铺授权聚水潭的URL
     *
     * @return
     */
    public static String spliceAuthorizationUrl(String state) throws IOException {
        Map<String, String> params = new HashMap<>();
        // 公共参数
        params.put("app_key", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("state", state);
        params.put("charset", "utf-8");
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        String url = buildQuery(params, "utf-8");
        url = serverUrl + "/auth?" + url;
        return url;
    }


    /**
     * 验证签名
     *
     * @param params
     * @param sign
     * @return
     * @throws IOException
     */
    public static Boolean signatureVerification(Map<String, String> params, String sign) throws IOException {
        String signTopRequest = signTopRequest(params, appSecret, SIGN_METHOD_MD5);
        return sign.equals(signTopRequest);
    }


    /**
     * 获取accessToken'
     *
     * @param code
     * @return
     */
	public static void main(String[] args) throws IOException {
//    public static  void getAccessToken() {
		System.out.println("授权流程\r\n" + "一、获取access_token、refresh_token");
		Map<String, String> params = new HashMap<>();
		params.put("app_key", appKey);
		params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
		params.put("grant_type", "authorization_code");
		params.put("charset", "utf-8");
		params.put("code", "4xFIOC");
		params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));

		// 获取accessToken的地址
		String url = serverUrl + "/openWeb/auth/getInitToken";
		String str = sendByPostMap(url, params);
		System.out.println(str);

		JSONObject jsonObject = JSONObject.parseObject(str);
		ResultUtil resultUtil = JSONObject.toJavaObject(jsonObject, ResultUtil.class);
		Map<Object, Object> resultUtilMap = (Map<Object, Object>) resultUtil.getData();

		System.out.println("二、更新access_token、refresh_token");

		Map<String, String> params01 = new HashMap<>();
		params01.put("app_key", appKey);
		params01.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
		params01.put("grant_type", "authorization_code");
		params01.put("charset", "utf-8");
		params01.put("refresh_token", resultUtilMap.get("refresh_token").toString());
		params01.put("scope", "all");
//       params.put("code", "4xFIOC");
		params01.put("sign", signTopRequest(params01, appSecret, SIGN_METHOD_MD5));

		// 获取accessToken的地址
		String url01 = serverUrl + "/openWeb/auth/refreshToken";
		String str01 = sendByPostMap(url01, params01);
		System.out.println(str01);
		JSONObject jsonObject01 = JSONObject.parseObject(str01);
		ResultUtil resultUtil01 = JSONObject.toJavaObject(jsonObject01, ResultUtil.class);
		Map<Object, Object> resultUtilMap01 = (Map<Object, Object>) resultUtil01.getData();

		System.out.println("三、更新access_token、refresh_token");

	}


    /**
     * 刷新AccessToken
     *
     * @param refreshToken
     * @return
     */
//    public static void main(String[] args) throws IOException {
    public static void refreshToken(String refreshToken) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type", "authorization_code");
        params.put("charset", "utf-8");
        params.put("refresh_token", "27fb7e65bd8146e8a6aa62e9576a0ada");
        params.put("scope", "all");
//        params.put("code", "4xFIOC");
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));

        //获取accessToken的地址
        String url = serverUrl + "/openWeb/auth/refreshToken";
        String str =  sendByPostMap(url, params);
        System.out.println(str);

    }


    /**
     * post方式请求
     * <p>
     * 对于POST请求,请求参数全部放在Body里,不要把参数放在Query里。 -- 聚水潭
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendByPostMap(String url, Map<String, String> params) {
        OkHttpClient client = new OkHttpClient();
        StringBuilder content = new StringBuilder();

        // 拼接请求参数
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            content.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()) {
                content.append("&");
            }
        }
        

        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString());
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
//            String responseBody = response.g;
            return response.body().string();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 发送请求
     *
     * @param accessToken
     * @param biz
     * @param requestUrl
     * @return
     */
    public static String sendRequest(String accessToken, String biz, String requestUrl) {
        // 公共请求参数
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("access_token", accessToken);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz", biz);
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        String url = serverUrl + requestUrl;
        String str = sendByPostMap(url, params);
        return str;
    }


    public static boolean isNotEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if ((!Character.isWhitespace(value.charAt(i)))) {
                return true;
            }
        }
        return false;
    }



 

    /**
     * post方式请求  备用
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendByPostMap(String url, Map<String, String> params, Map<String, String> map) {
        String result;
        OkHttpClient client = new OkHttpClient();
        StringBuilder content = new StringBuilder();

        // 拼接请求参数
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            content.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()) {
                content.append("&");
            }
        }

        // 请求体
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString());

        // 请求头 添加具有名称和值的标头。对于像“Cookie”这样的多值头文件,最好使用这种方法。
        Request.Builder builder = new Request.Builder().url(url);
        if (MapUtils.isNotEmpty(map)) {
            map.forEach(builder::addHeader);
        }


        Request request = builder.url(url).post(requestBody).build();
        Response response;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            result = response.body().string();
            System.out.println("result = " + result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值