All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.anjiplus.open.sdk.client.OpenClient Maven / Gradle / Ivy

package com.anjiplus.open.sdk.client;

import com.alibaba.fastjson.JSONObject;
import com.anjiplus.open.sdk.utils.SignUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 开放平台客户端
 *
 * @author lr
 */
public class OpenClient {

    /**
     * 请求客户端
     */
    private RestTemplate restTemplate = new RestTemplate();

    private final static String SUCCESS_CODE = "200";
    private final static String FAILURE_CODE = "500";

    private final static String RESPONSE_CODE = "code";

    /**
     * 开放平台地址
     */
    private String url;

    /**
     * 应用私钥
     */
    private String secret;

    /**
     * 应用appId,在开放平台要先创建
     */
    private String appId;

    /**
     * 请求对应的接口标识
     */
    private String method;

    /**
     * 请求头
     */
    private Map headers;

    /**
     * 路径请求参数
     */
    private Map pathParams;

    /**
     * 请求体
     */
    Object requestBody;

    /**
     * 成功回调
     */
    Consumer success;

    /**
     * 失败回调
     */
    Consumer fail;

    /**
     * 构造器
     * @param builder
     */
    OpenClient(OpenClientBuilder builder) {
        this.secret = builder.secret;
        this.url = builder.url;
        this.appId = builder.appId;
        this.method = builder.method;
        this.headers = builder.headers;
        this.pathParams = builder.pathParams;
        this.requestBody = builder.requestBody;
        this.success = builder.success;
        this.fail = builder.fail;
    }

    /**
     * 开放平台客户端GET调用
     * @return 请求结果
     */
    public JSONObject doGet() {
        //判断必填参数
        JSONObject errorResult = null;
        if((errorResult = processBeforeRequest()) != null) {
            fail.accept(errorResult);
            return errorResult;
        };
        //发送请求
        MultiValueMap multiValueMap = new LinkedMultiValueMap();
        if(headers != null) {
            multiValueMap.setAll(headers);
        }
        HttpEntity httpEntity = new HttpEntity(multiValueMap);
        Map requestParams = getRequestParams();

        ResponseEntity exchange = restTemplate.exchange(getUrl(requestParams), HttpMethod.GET
                , httpEntity, JSONObject.class, requestParams);

        //响应结果处理
        return handleResult(exchange);
    }

    /**
     * 开放平台客户端POST调用
     * @return 请求结果
     */
    public JSONObject doPost() {
        //判断必填参数
        JSONObject errorResult = null;
        if((errorResult = processBeforeRequest()) != null) {
            fail.accept(errorResult);
            return errorResult;
        };
        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        if(headers != null) {
            httpHeaders.setAll(headers);
        }

        HttpEntity httpEntity = new HttpEntity(requestBody, httpHeaders);
        Map requestParams = getRequestParams();
        //发送请求
        ResponseEntity exchange = restTemplate.postForEntity(getUrl(requestParams), httpEntity,
                JSONObject.class, requestParams);

        //响应结果处理
        return handleResult(exchange);
    }

    /**
     * 请求前拦截
     * @return 请求前拦截
     */
    public JSONObject processBeforeRequest(){
        JSONObject jsonObject = new JSONObject();
        if(StringUtils.isBlank(url)) {
            jsonObject.put(FAILURE_CODE,"开放平台地址为空或不合法");
            return jsonObject;
        }
        if(StringUtils.isBlank(appId)) {
            jsonObject.put(FAILURE_CODE,"缺少必填参数:应用appId");
            return jsonObject;
        }

        if(StringUtils.isBlank(method)) {
            jsonObject.put(FAILURE_CODE,"缺少必填参数:调用接口名method");
            return jsonObject;
        }

        if(StringUtils.isBlank(secret)) {
            jsonObject.put(FAILURE_CODE,"缺少必填参数:应用在开放平台的私钥");
            return jsonObject;
        }

        return null;
    }

    /**
     * 处理返回结果
     * @param exchange 请求结果
     * @return 响应结果
     */
    private JSONObject handleResult(ResponseEntity exchange) {
        JSONObject remoteResult = null;
        //成功收到开放平台响应
        if(exchange.getStatusCode().is2xxSuccessful()) {
            remoteResult = exchange.getBody();
            if(StringUtils.equals(SUCCESS_CODE,exchange.getBody().get(RESPONSE_CODE).toString())){
                if(success != null) {
                    success.accept(remoteResult);
                }
            }else{
                if(fail != null) {
                    fail.accept(remoteResult);
                }
            }
        }else{
            remoteResult = new JSONObject();
            remoteResult.put("errorCode",exchange.getStatusCodeValue());
            if(fail != null) {
                fail.accept(remoteResult);
            }
        }
        return remoteResult;
    }

    /**
     * 获取请求参数
     * @return 构造的请求参数
     */
    public Map getRequestParams(){
        long timestamp = System.currentTimeMillis();
        Map requestParams = new HashMap();
        requestParams.put("appId", appId);
        requestParams.put("method", method);
        requestParams.put("timestamp", timestamp);

        if(pathParams != null) {
            requestParams.putAll(pathParams);
        }
        requestParams.put("sign",getSign(requestParams));
        return requestParams;
    }

    /**
     * 拼接正确地url地址
     * @param requestParams 请求参数
     * @return 获取参数拼装的url
     */
    public String getUrl(Map requestParams){
        String paramStr = "?";
        for(String key : requestParams.keySet()) {
            paramStr = paramStr +key+"={"+key+"}&";
        }

        paramStr = paramStr.substring(0,paramStr.length()-1);
        return url + paramStr;
    }

    /**
     * 获取请求秘钥
     * @param requestParams 请求参数(放在路径上的)
     * @return 请求秘钥
     */
    private String getSign(Map requestParams) {
        try {
            String sign = SignUtils.generateSign(requestParams, secret);
            return sign;
        } catch (IOException e) {
            return null;
        }
    }
}