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

com.zuora.sdk.ZuoraClient Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package com.zuora.sdk;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.openapitools.client.ApiClient;
import org.openapitools.client.api.*;

import java.io.IOException;
import java.util.*;

public class ZuoraClient {

    public enum ZuoraEnv {
        LOCAL("http://localhost:3000"),
        STG("https://rest-staging2.zuora.com"),
        SBX("https://rest.apisandbox.zuora.com"),
        CSBX("https://rest.test.zuora.com"),
        SBX_NA("https://rest.sandbox.na.zuora.com"),
        PROD("https://rest.zuora.com"),
        PROD_NA("https://rest.na.zuora.com"),
        SBX_EU("https://rest.sandbox.eu.zuora.com"),
        PROD_EU("https://rest.eu.zuora.com");

        private final String baseUrl;

        ZuoraEnv(String baseUrl){
            this.baseUrl = baseUrl;
        }
    }

    public static final Map zuoraBaseUrls = Collections.unmodifiableMap(new HashMap() {{
        put("LOCAL", "http://localhost:3000");
        put("STG", "https://rest-staging2.zuora.com");
        put("SBX", "https://rest.apisandbox.zuora.com");
        put("CSBX", "https://rest.test.zuora.com");
        put("SBX_NA", "https://rest.sandbox.na.zuora.com");
        put("PROD", "https://rest.zuora.com");
        put("PROD_NA", "https://rest.na.zuora.com");
        put("SBX_EU","https://rest.sandbox.eu.zuora.com");
        put("PROD_EU","https://rest.eu.zuora.com");
    }});

    private final String clientId;
    private final String clientSecret;
    private final String baseUrl;
    private final String oauthUrl;
    private final ApiClient apiClient;
    private final Timer timer;
    private TimerTask reinitTask;
    private String bearerToken = null;
    private final Map defaultHeaders = new HashMap();
    private int connectionTimeout = 65000;
    private int readTimeout = 65000;
    private int writeTimeout = 65000;

    /**
     * Initialize the Zuora Client
     *
     * @param clientId zuora client Id
     * @param clientSecret zuora client secret
     * @param env Zuora Environment
     *
     * Call initialize() prior to using
     */
    public ZuoraClient(String clientId, String clientSecret, ZuoraEnv env) {
        this(clientId, clientSecret, env.baseUrl);
    }

    /**
     * Initialize the Zuora Client
     *
     * @param clientId zuora client Id
     * @param clientSecret zuora client secret
     * @param zuoraBaseUrl Base URL for Zuora REST Endpoints - use ZuoraClient.zuoraBaseUrls.get({env})
     *
     * Call initialize() prior to using
     */
    public ZuoraClient(String clientId, String clientSecret, String zuoraBaseUrl) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;

        if (zuoraBaseUrls.get("LOCAL").equals(zuoraBaseUrl)) {
            this.oauthUrl = zuoraBaseUrls.get("SBX");
            this.baseUrl = zuoraBaseUrl;
        } else {
            this.oauthUrl = zuoraBaseUrl;
            this.baseUrl = oauthUrl + "/v2";
        }
        this.apiClient = new ApiClient();
        this.apiClient.setBasePath(this.baseUrl);
        this.apiClient.setConnectTimeout(this.connectionTimeout);
        this.apiClient.setReadTimeout(this.readTimeout);
        this.apiClient.setWriteTimeout(this.writeTimeout);
        this.timer = new Timer();
    }

    /**
     * Initialize the Zuora Client from Walled Garden
     *
     * @param baseUrl BaseUrl (required)
     * @param headers Set the following headers "zuora-cache-enabled" "zuora-request-id" "zuora-entity-ids" "zuora-tenant-id" "zuora-token-id" "zuora-track-id"
     * "zuora-user-id" "zuora-version"
     *
     * Do not call initialize()
     */
    private ZuoraClient(String baseUrl, Map headers) {
        this.clientId = null;
        this.clientSecret = null;
        this.oauthUrl = null;
        this.baseUrl = baseUrl;
        this.timer = null;
        this.apiClient = new ApiClient();
        this.apiClient.setBasePath(this.baseUrl);

        headers.forEach(this.apiClient::addDefaultHeader);
    }

    public void addDefaultHeaders(Map defaultHeaders){
        this.defaultHeaders.putAll(defaultHeaders);
        defaultHeaders.forEach(this.apiClient::addDefaultHeader);
    }

    public void setAsync(boolean isAsync){
        this.addDefaultHeaders(Collections.singletonMap("async", String.valueOf(isAsync)));
    }

    public String getAsync(){
        return this.defaultHeaders.get("async");
    }

    public void setEntityId(String entityId){
        this.addDefaultHeaders(Collections.singletonMap("zuora-entity-id", entityId));
    }

    public String getEntityId(){
        return this.defaultHeaders.get("zuora-entity-id");
    }

    public void setAcceptEncoding(String acceptEncoding){
        this.addDefaultHeaders(Collections.singletonMap("Accept-Encoding", acceptEncoding));
    }

    public String getAcceptEncoding(){
        return this.defaultHeaders.get("Accept-Encoding");
    }

    public void setContentEncoding(String contentEncoding){
        this.addDefaultHeaders(Collections.singletonMap("Content-Encoding", contentEncoding));
    }

    public String getContentType(){
        return this.defaultHeaders.get("Content-Encoding");
    }

    public void setCacheEnabled(boolean enabled) {
        if (enabled) {
            this.apiClient.addDefaultHeader("zuora-cache-enabled", "true");
            return;
        }
        this.apiClient.addDefaultHeader("zuora-cache-enabled", "false");
    }

    /**
     * Sets the connect timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE.
     * Default is 65000
     *
     * @param connectionTimeout connection timeout in milliseconds
     *
     */
    public void setConnectTimeout(int connectionTimeout){
        this.connectionTimeout = connectionTimeout;
        this.apiClient.setConnectTimeout(this.connectionTimeout);
    }

    /**
     * Sets the read timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE.
     * Default is 65000
     *
     * @param readTimeout connection timeout in milliseconds
     *
     */
    public void setReadTimeout(int readTimeout){
        this.readTimeout = readTimeout;
        this.apiClient.setReadTimeout(this.readTimeout);
    }

    /**
     * Sets the write timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE.
     * Default is 65000
     *
     * @param writeTimeout connection timeout in milliseconds
     *
     */
    public void setWriteTimeout(int writeTimeout){
        this.writeTimeout = writeTimeout;
        this.apiClient.setWriteTimeout(this.writeTimeout);
    }

    protected String fetchBearerToken() {
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("client_id", this.clientId)
                .add("client_secret", this.clientSecret)
                .add("grant_type", "client_credentials")
                .build();

        Request request = new Request.Builder()
                .url(this.oauthUrl + "/oauth/token")
                .headers(Headers.of(this.defaultHeaders))
                .post(formBody)
                .build();

        String token = null;

        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            JsonObject json = JsonParser.parseString(body).getAsJsonObject();
            token = json.get("access_token").getAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return token;
    }

    protected void auth() {
        String token = this.fetchBearerToken();
        this.apiClient.addDefaultHeader("Authorization", "Bearer " + token);
        this.apiClient.addDefaultHeader("x-donut-auth", "Bearer " + token);
        setBearerToken(token);
    }

    public String getBearerToken() {
       return this.bearerToken;
    }

    protected void setBearerToken(String bearerToken){
        this.bearerToken = bearerToken;
    }
    public void initialize() {
        if (reinitTask != null) {
            return;
        }

        this.auth();

        int reinitInterval = 55 * (60 * 1000); // 55 minutes
        ZuoraClient zc = this;
        reinitTask = new TimerTask() {
            @Override
            public void run() {
                zc.auth();
            }
        };
        this.timer.scheduleAtFixedRate(reinitTask, 0, reinitInterval);
    }

    public String getBaseUrl(){
        return this.baseUrl;
    }

    public AccountsApi accounts() {
        return new AccountsApi(this.apiClient);
    }

    public ContactsApi contact() {
        return new ContactsApi(this.apiClient);
    }

    public ProductsApi products() {
        return new ProductsApi(this.apiClient);
    }

    public PricesApi prices() {
        return new PricesApi(this.apiClient);
    }

    public PlansApi plans() {
        return new PlansApi(this.apiClient);
    }

    public BillingDocumentsApi billingDocuments() {
        return new BillingDocumentsApi(this.apiClient);
    }

    public InvoicesApi invoices() {
        return new InvoicesApi(this.apiClient);
    }

    public CreditMemosApi creditMemos() {
        return new CreditMemosApi(this.apiClient);
    }

    public DebitMemosApi debitMemosApi() {
        return new DebitMemosApi(this.apiClient);
    }

    public PaymentMethodsApi paymentMethods() {
        return new PaymentMethodsApi(this.apiClient);
    }

    public SubscriptionsApi subscriptions() {
        return new SubscriptionsApi(this.apiClient);
    }

    public SubscriptionPlansApi subscriptionPlans() {
        return new SubscriptionPlansApi(this.apiClient);
    }

    public PaymentsApi payments() {
        return new PaymentsApi(this.apiClient);
    }

    public WorkflowsApi workflows() {
        return new WorkflowsApi(this.apiClient);
    }

    public CustomObjectsApi customObjects() {
        return new CustomObjectsApi(this.apiClient);
    }

    public OrdersApi orders() { return new OrdersApi(this.apiClient); }

    public UsageRecordsApi usageRecords() { return new UsageRecordsApi(this.apiClient); }

    public TaxationItemsApi taxationItems() { return new TaxationItemsApi(this.apiClient); }

    public InvoiceItemsApi invoiceItems() { return new InvoiceItemsApi(this.apiClient); }
    public BillRunsApi billRuns() { return new BillRunsApi(this.apiClient); }
    public QueryRunsApi queryRuns() { return new QueryRunsApi(this.apiClient); }
    public CreditMemosApi creditMemo() { return new CreditMemosApi(this.apiClient); }
    public DebitMemosApi debitMemos() { return new DebitMemosApi(this.apiClient); }
    public PaymentRunsApi paymentRuns() { return new PaymentRunsApi(this.apiClient); }
    public BillRunPreviewsApi billRunPreviews() { return new BillRunPreviewsApi(this.apiClient); }
    public FulfillmentsApi fulfillments() { return new FulfillmentsApi(this.apiClient); }
    public FulfillmentItemsApi fulfillmentItems() { return new FulfillmentItemsApi(this.apiClient); }
    public SubscriptionItemsApi subscriptionItems() { return new SubscriptionItemsApi(this.apiClient); }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy