Skip to content

speakeasy-sdks/paddle-ts

Repository files navigation

Typescript SDK

One platform for tax, payments, and subscriptions

SDK Installation

NPM

npm add https://github.com/speakeasy-sdks/paddle-ts

Yarn

yarn add https://github.com/speakeasy-sdks/paddle-ts

SDK Example Usage

Example

import { Paddle } from "Paddle";
import {
    CurrencyCode2,
    CurrencyCodeChargeback,
    CurrencyCodePayouts,
    SchemaAction,
    SchemaStatusAdjustment,
} from "Paddle/sdk/models/shared";

async function run() {
    const sdk = new Paddle({
        security: {
            bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
        },
    });

    const result = await sdk.adjustments.create({
        action: SchemaAction.Refund,
        customerId: "ctm_01grnn4zta5a1mf02jjze7y2ys",
        id: "adj_01gya6twkp8y0tv1e19rsgst9m",
        items: [
            {
                id: "adjitm_01gw4rs4kex0prncwfne87ft8x",
                itemId: "txnitm_01gm302t81w94gyjpjpqypkzkf",
                type: AdjustmentCreateType.Full,
            },
        ],
        payoutTotals: {
            chargebackFee: {
                amount: "1680",
                original: {
                    amount: "1500",
                },
            },
            earnings: "15120",
            fee: "300",
            subtotal: "15000",
            tax: "1500",
            total: "16500",
        },
        reason: "string",
        subscriptionId: "sub_01h04vsc0qhwtsbsxh3422wjs4",
        transactionId: "string",
    });

    // Handle the result
    console.log(result);
}

run();

Available Resources and Operations

  • create - Create an adjustment
  • list - List adjustments
  • create - Create an address for a customer
  • get - Get an address for a customer
  • list - List addresses for a customer
  • update - Update an address for a customer
  • create - Create a business for a customer
  • get - Get a business for a customer
  • list - List businesses for a customer
  • update - Update a business for a customer
  • create - Create a discount
  • get - Get a discount
  • list - List discounts
  • update - Update a discount
  • get - Get Paddle IP addresses

Error Handling

All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type.

Error Object Status Code Content Type
errors.CreateAdjustmentResponseBody 400 application/json
errors.CreateAdjustmentAdjustmentsResponseBody 404 application/json
errors.CreateAdjustmentAdjustmentsResponseResponseBody 409 application/json
errors.CreateAdjustmentAdjustmentsResponse500ResponseBody 500 application/json
errors.SDKError 4xx-5xx /

Example

import { Paddle } from "Paddle";
import * as errors from "Paddle/sdk/models/errors";
import {
    CurrencyCode2,
    CurrencyCodeChargeback,
    CurrencyCodePayouts,
    SchemaAction,
    SchemaStatusAdjustment,
} from "Paddle/sdk/models/shared";

async function run() {
    const sdk = new Paddle({
        security: {
            bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
        },
    });

    let result;
    try {
        result = await sdk.adjustments.create({
            action: SchemaAction.Refund,
            customerId: "ctm_01grnn4zta5a1mf02jjze7y2ys",
            id: "adj_01gya6twkp8y0tv1e19rsgst9m",
            items: [
                {
                    id: "adjitm_01gw4rs4kex0prncwfne87ft8x",
                    itemId: "txnitm_01gm302t81w94gyjpjpqypkzkf",
                    type: AdjustmentCreateType.Full,
                },
            ],
            payoutTotals: {
                chargebackFee: {
                    amount: "1680",
                    original: {
                        amount: "1500",
                    },
                },
                earnings: "15120",
                fee: "300",
                subtotal: "15000",
                tax: "1500",
                total: "16500",
            },
            reason: "string",
            subscriptionId: "sub_01h04vsc0qhwtsbsxh3422wjs4",
            transactionId: "string",
        });
    } catch (err) {
        switch (true) {
            case err instanceof errors.CreateAdjustmentResponseBody: {
                console.error(err); // handle exception
                return;
            }
            case err instanceof errors.CreateAdjustmentAdjustmentsResponseBody: {
                console.error(err); // handle exception
                return;
            }
            case err instanceof errors.CreateAdjustmentAdjustmentsResponseResponseBody: {
                console.error(err); // handle exception
                return;
            }
            case err instanceof errors.CreateAdjustmentAdjustmentsResponse500ResponseBody: {
                console.error(err); // handle exception
                return;
            }
            default: {
                throw err;
            }
        }
    }

    // Handle the result
    console.log(result);
}

run();

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIdx optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:

# Server Variables
0 https://api.paddle.com None
1 https://sandbox-api.paddle.com None
import { Paddle } from "Paddle";
import {
    CurrencyCode2,
    CurrencyCodeChargeback,
    CurrencyCodePayouts,
    SchemaAction,
    SchemaStatusAdjustment,
} from "Paddle/sdk/models/shared";

async function run() {
    const sdk = new Paddle({
        serverIdx: 1,
        security: {
            bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
        },
    });

    const result = await sdk.adjustments.create({
        action: SchemaAction.Refund,
        customerId: "ctm_01grnn4zta5a1mf02jjze7y2ys",
        id: "adj_01gya6twkp8y0tv1e19rsgst9m",
        items: [
            {
                id: "adjitm_01gw4rs4kex0prncwfne87ft8x",
                itemId: "txnitm_01gm302t81w94gyjpjpqypkzkf",
                type: AdjustmentCreateType.Full,
            },
        ],
        payoutTotals: {
            chargebackFee: {
                amount: "1680",
                original: {
                    amount: "1500",
                },
            },
            earnings: "15120",
            fee: "300",
            subtotal: "15000",
            tax: "1500",
            total: "16500",
        },
        reason: "string",
        subscriptionId: "sub_01h04vsc0qhwtsbsxh3422wjs4",
        transactionId: "string",
    });

    // Handle the result
    console.log(result);
}

run();

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL optional parameter when initializing the SDK client instance. For example:

import { Paddle } from "Paddle";
import {
    CurrencyCode2,
    CurrencyCodeChargeback,
    CurrencyCodePayouts,
    SchemaAction,
    SchemaStatusAdjustment,
} from "Paddle/sdk/models/shared";

async function run() {
    const sdk = new Paddle({
        serverURL: "https://api.paddle.com",
        security: {
            bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
        },
    });

    const result = await sdk.adjustments.create({
        action: SchemaAction.Refund,
        customerId: "ctm_01grnn4zta5a1mf02jjze7y2ys",
        id: "adj_01gya6twkp8y0tv1e19rsgst9m",
        items: [
            {
                id: "adjitm_01gw4rs4kex0prncwfne87ft8x",
                itemId: "txnitm_01gm302t81w94gyjpjpqypkzkf",
                type: AdjustmentCreateType.Full,
            },
        ],
        payoutTotals: {
            chargebackFee: {
                amount: "1680",
                original: {
                    amount: "1500",
                },
            },
            earnings: "15120",
            fee: "300",
            subtotal: "15000",
            tax: "1500",
            total: "16500",
        },
        reason: "string",
        subscriptionId: "sub_01h04vsc0qhwtsbsxh3422wjs4",
        transactionId: "string",
    });

    // Handle the result
    console.log(result);
}

run();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native Fetch API. This client is a thin wrapper around fetch and provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient constructor takes an optional fetcher argument that can be used to integrate a third-party HTTP client or when writing tests to mock out the HTTP client and feed in fixtures.

The following example shows how to use the "beforeRequest" hook to to add a custom header and a timeout to requests and how to use the "requestError" hook to log errors:

import { Paddle } from "Paddle";
import { HTTPClient } from "Paddle/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  }
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000);
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Paddle({ httpClient });

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
bearerAuth http HTTP Bearer

You can set the security parameters through the security optional parameter when initializing the SDK client instance. For example:

import { Paddle } from "Paddle";
import {
    CurrencyCode2,
    CurrencyCodeChargeback,
    CurrencyCodePayouts,
    SchemaAction,
    SchemaStatusAdjustment,
} from "Paddle/sdk/models/shared";

async function run() {
    const sdk = new Paddle({
        security: {
            bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
        },
    });

    const result = await sdk.adjustments.create({
        action: SchemaAction.Refund,
        customerId: "ctm_01grnn4zta5a1mf02jjze7y2ys",
        id: "adj_01gya6twkp8y0tv1e19rsgst9m",
        items: [
            {
                id: "adjitm_01gw4rs4kex0prncwfne87ft8x",
                itemId: "txnitm_01gm302t81w94gyjpjpqypkzkf",
                type: AdjustmentCreateType.Full,
            },
        ],
        payoutTotals: {
            chargebackFee: {
                amount: "1680",
                original: {
                    amount: "1500",
                },
            },
            earnings: "15120",
            fee: "300",
            subtotal: "15000",
            tax: "1500",
            total: "16500",
        },
        reason: "string",
        subscriptionId: "sub_01h04vsc0qhwtsbsxh3422wjs4",
        transactionId: "string",
    });

    // Handle the result
    console.log(result);
}

run();

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

SDK Created by Speakeasy