TransFi SDK Documentation


TransFi SDK Documentation

Programmatically create and manage payment invoices using the TransFi Checkout API. SDKs are available for Node.js and Python.


Prerequisites

Before using any SDK, you need:

  1. A TransFi merchant accountSign up here
  2. Your Public Key and Secret Key from the TransFi dashboard
  3. A Payment Link ID — create one in the TransFi dashboard before making API calls

Security notice: Never hardcode your Public Key or Secret Key in source code. Always store them in environment variables.


Installation

npm install transfi-checkout
pip install transfi-sdk
Maven/Gradle via JitPack (com.github.Trans-Fi:transfi-checkout-java-sdk:v1.0.0)
composer require transfi/payment-sdk

Authentication

Both SDKs use HMAC-based authentication built in automatically — you only need to pass your keys when initializing the client.

const { TransFiPaymentAPI } = require("transfi-checkout");

const client = new TransFiPaymentAPI({
  publicKey: process.env.TRANSFI_PUBLIC_KEY,
  secretKey: process.env.TRANSFI_SECRET_KEY,
});
from transfi import TransFiPaymentAPI

api = TransFiPaymentAPI(
    public_key="YOUR_PUBLIC_KEY",
    secret_key="YOUR_SECRET_KEY",
)
sdkConfig config = new sdkConfig("YOUR_PUBLIC_KEY", "YOUR_SECRET_KEY");
transfiPaymentApi api = new transfiPaymentApi(config);
use TransFi\TransFiPaymentAPI;
use TransFi\TransFiError;
use TransFi\PaymentInvoiceRequest;
use TransFi\Individual;
use TransFi\ProductDetails;

$api = new TransFiPaymentAPI([
    'publicKey' => 'YOUR_PUBLIC_KEY',
    'secretKey' => 'YOUR_SECRET_KEY',
]);
ParameterTypeRequiredDescription
publicKey / public_keystringYesYour TransFi API public key
secretKey / secret_keystringYesYour TransFi API secret key

Quick Start

const { TransFiPaymentAPI } = require("transfi-checkout");

const client = new TransFiPaymentAPI({
  publicKey: process.env.TRANSFI_PUBLIC_KEY,
  secretKey: process.env.TRANSFI_SECRET_KEY,
});

client
  .createPaymentInvoice({
    paymentLinkId: "your-payment-link-id",
    amount: "100",
    currency: "USD",
    productDetails: {
      name: "Premium Annual Plan",
      description: "12-month access to all premium features",
      imageUrl: "https://example.com/product-image.png",
    },
    successRedirectUrl: "https://yourapp.com/payment/success",
    failureRedirectUrl: "https://yourapp.com/payment/failure",
  })
  .then((paymentUrl) => {
    console.log("Redirect customer to:", paymentUrl);
  })
  .catch((error) => {
    console.error("Error:", error.message);
  });
from transfi import TransFiPaymentAPI, TransFiError
from transfi.types import PaymentInvoiceRequest, ProductDetails

api = TransFiPaymentAPI(
    public_key="YOUR_PUBLIC_KEY",
    secret_key="YOUR_SECRET_KEY",
)

request = PaymentInvoiceRequest(
    payment_link_id="your-payment-link-id",
    amount="100",
    currency="USD",
    product_details=ProductDetails(
        name="Premium Annual Plan",
        description="12-month access to all premium features",
        image_url="https://example.com/product-image.png",
    ),
    success_redirect_url="https://yourapp.com/payment/success",
    failure_redirect_url="https://yourapp.com/payment/failure",
)

try:
    payment_url = api.create_payment_invoice(request)
    print("Redirect customer to:", payment_url)
except TransFiError as e:
    print("Error:", e)
paymentInvoiceRequest request = paymentInvoiceRequest.builder()
    .paymentLinkId("YOUR_PAYMENT_LINK_ID")
    .amount("100.00")
    .currency("USD")
    .productDetails(productDetails.builder()
        .name("Premium Subscription")
        .description("Monthly subscription plan")
        .build())
    .individual(individual.builder()
        .firstName("John")
        .lastName("Doe")
        .email("[email protected]")
        .phone("1234567890")
        .phoneCode("+1")
        .country("US")
        .build())
    .successRedirectUrl("https://yoursite.com/success")
    .failureRedirectUrl("https://yoursite.com/failure")
    .customerOrderId("order-" + System.currentTimeMillis())
    .build();

try {
    String paymentUrl = api.createPaymentInvoice(request);
    System.out.println("Payment URL: " + paymentUrl);
    // Redirect user to paymentUrl to complete payment
} catch (transfiError e) {
    System.err.println("Error: " + e.getMessage());
    System.err.println("Status Code: " + e.getStatusCode());
    System.err.println("Response: " + e.getResponseData());
}

use TransFi\TransFiPaymentAPI;
use TransFi\TransFiError;
use TransFi\PaymentInvoiceRequest;
use TransFi\Individual;
use TransFi\ProductDetails;

$api = new TransFiPaymentAPI([
    'publicKey' => 'YOUR_PUBLIC_KEY',
    'secretKey' => 'YOUR_SECRET_KEY',
]);

$product = new ProductDetails('Premium Plan');
$product->description = 'Monthly subscription';

$individual = new Individual('John', 'Doe', '[email protected]');
$individual->phone     = '1234567890';
$individual->phoneCode = '+1';
$individual->country   = 'US';

$paymentData = new PaymentInvoiceRequest(
    'LINK_ID',
    '100',
    'USD',
    'https://example.com/success',
    'https://example.com/failure'
);
$paymentData->productDetails  = $product;
$paymentData->individual      = $individual;
$paymentData->customerOrderId = 'order-001';

try {
    $paymentUrl = $api->createPaymentInvoice($paymentData);
    echo 'Checkout URL: ' . $paymentUrl . PHP_EOL;
} catch (TransFiError $e) {
    echo 'API Error   : ' . $e->getMessage() . PHP_EOL;
    echo 'Status Code : ' . $e->getStatusCode() . PHP_EOL;
    echo 'Response    : ' . json_encode($e->getResponseData(), JSON_PRETTY_PRINT) . PHP_EOL;
}

Methods

createPaymentInvoice / create_payment_invoice

Creates a payment invoice for a customer and returns a payment URL to redirect the customer to complete the payment.

const paymentUrl = await client.createPaymentInvoice(paymentData);
// Returns: Promise<string> — the checkout URL
payment_url = api.create_payment_invoice(request)
# Returns: str — the checkout URL
String paymentUrl = api.createPaymentInvoice(request);
//// Returns: String — the checkout URL
    $paymentUrl = $api->createPaymentInvoice($paymentData);
    echo 'Checkout URL: ' . $paymentUrl . PHP_EOL;

Parameters

Payment Invoice Request

{
  paymentLinkId: "string",        // Required
  amount: "string",               // Required — e.g. "100" or "49.99"
  currency: "string",             // Required — ISO 4217, e.g. "USD"
  successRedirectUrl: "string",   // Required
  failureRedirectUrl: "string",   // Required
  productDetails: { ... },        // Optional — see below
  individual: { ... },            // Optional — see below
  customerOrderId: "string",      // Optional — your internal order ID
}
PaymentInvoiceRequest(
    payment_link_id="string",         # Required
    amount="string",                  # Required — e.g. "100" or "49.99"
    currency="string",                # Required — ISO 4217, e.g. "USD"
    success_redirect_url="string",    # Required
    failure_redirect_url="string",    # Required
    product_details=ProductDetails(), # Optional — see below
    individual=Individual(),          # Optional — see below
    customer_order_id="string",       # Optional — your internal order ID
)
//Builder pattern for creating payment requests:

paymentInvoiceRequest.builder()
    .paymentLinkId(String)           // Required: Payment link identifier
    .amount(String)                  // Required: Payment amount
    .currency(String)                // Required: Currency code (USD, EUR, etc.)
    .productDetails(productDetails)  // Optional — see below
    .individual(individual)          // Optional — see below
    .successRedirectUrl(String)      // Required: Success redirect URL
    .failureRedirectUrl(String)      // Required: Failure redirect URL
    .customerOrderId(String)         // Optional — see below
     .build();

$paymentData = new PaymentInvoiceRequest(
    'LINK_ID',
    '100',
    'USD',
    'https://example.com/success',
    'https://example.com/failure'
);
$paymentData->productDetails  = $product;
$paymentData->individual      = $individual;
$paymentData->customerOrderId = 'order-001';

ParameterNode.js keyPython keyPHP KeyJava KeyTypeRequiredDescription
Payment Link IDpaymentLinkIdpayment_link_idpaymentLinkIdpaymentLinkIdstringYesThe Payment Link ID from your TransFi dashboard
AmountamountamountamountamountstringYesAmount to charge, e.g. "100" or "49.99"
CurrencycurrencycurrencycurrencycurrencystringYesISO 4217 code, e.g. "USD", "EUR", "SGD"
Success URLsuccessRedirectUrlsuccess_redirect_urlsuccessRedirectUrlsuccessRedirectUrlstringYesRedirect URL after successful payment
Failure URLfailureRedirectUrlfailure_redirect_urlfailureRedirectUrlfailureRedirectUrlstringYesRedirect URL after failed payment
Product DetailsproductDetailsproduct_detailsproductDetailsproductDetailsobjectNoProduct info shown at checkout
CustomerindividualindividualindividualindividualobjectNoCustomer details for pre-fill / KYC
Order IDcustomerOrderIdcustomer_order_idcustomerOrderIdcustomerOrderIdstringNoYour internal order reference ID

productDetails / ProductDetails

Product information displayed on the checkout page.

FieldNode.js keyPython keyRequiredDescription
NamenamenameYesName of the product or service
DescriptiondescriptiondescriptionNoShort description of the product
Image URLimageUrlimage_urlNoURL of a product image
productDetails: {
  name: "Premium Annual Plan",
  description: "12-month access to all features",
  imageUrl: "https://example.com/product.png",
}
from transfi.types import ProductDetails

ProductDetails(
    name="Premium Annual Plan",
    description="12-month access to all features",
    image_url="https://example.com/product.png",
)
productDetails(productDetails.builder()
        .name("Premium Subscription")
        .description("Monthly subscription plan")
        .build())
'productDetails'     => [
        'name'        => 'Premium Plan',
        'description' => 'Monthly subscription',
    ]

individual / Individual

Customer information used to pre-fill the checkout form or speed up KYC verification.

FieldNode.js keyPython keyRequiredDescription
First namefirstNamefirst_nameYesCustomer's first name
Last namelastNamelast_nameYesCustomer's last name
EmailemailemailYesCustomer's email address
PhonephonephoneNoPhone number without country code
Phone codephoneCodephone_codeNoDialing code, e.g. "+1", "+91"
CountrycountrycountryNoISO 3166-1 alpha-3 (Node.js: "USA") or alpha-2 (Python: "US")
AddressaddressaddressNoCustomer's address (see below)
individual: {
  firstName: "Jane",
  lastName: "Smith",
  email: "[email protected]",
  phone: "9876543210",
  phoneCode: "+1",
  country: "USA",
  address: {
    street: "123 Main St",
    city: "New York",
    state: "NY",
    postalCode: "10001",
  },
}
from transfi.types import Individual, Address

Individual(
    first_name="Jane",
    last_name="Smith",
    email="[email protected]",
    phone="9876543210",
    phone_code="+1",
    country="US",
    address=Address(
        street="123 Main St",
        city="New York",
        state="NY",
        postal_code="10001",
    ),
)
individual(individual.builder()
        .firstName("John")
        .lastName("Doe")
        .email("[email protected]")
        .phone("1234567890")
        .phoneCode("+1")
        .country("US")
        .build())
'individual'         => [
        'firstName' => 'John',
        'lastName'  => 'Doe',
        'email'     => '[email protected]',
        'phone'     => '1234567890',
        'phoneCode' => '+1',
        'country'   => 'US',
    ]

address / Address

FieldNode.js keyPython keyDescription
StreetstreetstreetStreet address
CitycitycityCity name
StatestatestateState or province
Postal codepostalCodepostal_codeZIP or postal code

Error Handling

Both SDKs throw a TransFiError when an API call fails.

PropertyNode.jsPythonTypeDescription
Messageerror.messagestr(e)stringHuman-readable error message
Status codeerror.statusCodee.status_codenumberHTTP status code, e.g. 400, 401, 500
Response bodyerror.responseDatae.response_dataanyRaw JSON response from the API
const { TransFiPaymentAPI, TransFiError } = require("transfi-checkout");

try {
  const paymentUrl = await client.createPaymentInvoice({ ... });
} catch (error) {
  if (error instanceof TransFiError) {
    console.error("TransFi API Error:", error.message);
    console.error("HTTP Status:", error.statusCode);   // e.g. 401, 400
    console.error("API Response:", error.responseData); // full error body
  } else {
    // Network error, timeout, etc.
    console.error("Unexpected error:", error.message);
  }
}
from transfi import TransFiPaymentAPI, TransFiError

try:
    payment_url = api.create_payment_invoice(request)
except TransFiError as e:
    print("API Error:   ", e)
    print("Status Code: ", e.status_code)
    print("Response:    ", e.response_data)
except Exception as e:
    # Network error, timeout, etc.
    print("Unexpected error:", e)
try {
    String paymentUrl = api.createPaymentInvoice(request);
    System.out.println("Payment URL: " + paymentUrl);
    // Redirect user to paymentUrl to complete payment
} catch (transfiError e) {
    System.err.println("Error: " + e.getMessage());
    System.err.println("Status Code: " + e.getStatusCode());
    System.err.println("Response: " + e.getResponseData());
}
try {
    $paymentUrl = $api->createPaymentInvoice($paymentData);
    echo 'Checkout URL: ' . $paymentUrl . PHP_EOL;
} catch (TransFiError $e) {
    echo 'API Error   : ' . $e->getMessage() . PHP_EOL;
    echo 'Status Code : ' . $e->getStatusCode() . PHP_EOL;
    echo 'Response    : ' . json_encode($e->getResponseData(), JSON_PRETTY_PRINT) . PHP_EOL;
}

Common HTTP status codes

StatusMeaningCommon cause
400Bad RequestMissing required fields or invalid parameter values
401UnauthorizedInvalid or missing API keys
404Not FoundpaymentLinkId does not exist in your account
500Server ErrorTemporary TransFi API issue — retry with backoff

Full Example

const { TransFiPaymentAPI, TransFiError } = require("transfi-checkout");

const client = new TransFiPaymentAPI({
  publicKey: process.env.TRANSFI_PUBLIC_KEY,
  secretKey: process.env.TRANSFI_SECRET_KEY,
});

async function createInvoice() {
  try {
    const paymentUrl = await client.createPaymentInvoice({
      paymentLinkId: "your-payment-link-id",
      amount: "149.99",
      currency: "USD",
      customerOrderId: "order-" + Date.now(),
      productDetails: {
        name: "Premium Annual Plan",
        description: "12-month access to all premium features",
        imageUrl: "https://example.com/product-image.png",
      },
      individual: {
        firstName: "Jane",
        lastName: "Smith",
        email: "[email protected]",
        phone: "9876543210",
        phoneCode: "+1",
        country: "USA",
        address: {
          street: "123 Main St",
          city: "New York",
          state: "NY",
          postalCode: "10001",
        },
      },
      successRedirectUrl: "https://yourapp.com/payment/success",
      failureRedirectUrl: "https://yourapp.com/payment/failure",
    });

    console.log("Invoice created! Redirect user to:");
    console.log(paymentUrl);
  } catch (error) {
    if (error instanceof TransFiError) {
      console.error(`API Error [${error.statusCode}]: ${error.message}`);
      console.error("Details:", error.responseData);
    } else {
      console.error("Network or unexpected error:", error.message);
    }
  }
}

createInvoice();
from transfi import TransFiPaymentAPI, TransFiError
from transfi.types import PaymentInvoiceRequest, Individual, ProductDetails, Address
import time

api = TransFiPaymentAPI(
    public_key="YOUR_PUBLIC_KEY",
    secret_key="YOUR_SECRET_KEY",
)

request = PaymentInvoiceRequest(
    payment_link_id="your-payment-link-id",
    amount="149.99",
    currency="USD",
    customer_order_id=f"order-{int(time.time())}",
    product_details=ProductDetails(
        name="Premium Annual Plan",
        description="12-month access to all premium features",
        image_url="https://example.com/product-image.png",
    ),
    individual=Individual(
        first_name="Jane",
        last_name="Smith",
        email="[email protected]",
        phone="9876543210",
        phone_code="+1",
        country="US",
        address=Address(
            street="123 Main St",
            city="New York",
            state="NY",
            postal_code="10001",
        ),
    ),
    success_redirect_url="https://yourapp.com/payment/success",
    failure_redirect_url="https://yourapp.com/payment/failure",
)

try:
    payment_url = api.create_payment_invoice(request)
    print("Invoice created! Redirect user to:")
    print(payment_url)
except TransFiError as e:
    print(f"API Error [{e.status_code}]: {e}")
    print("Details:", e.response_data)
except Exception as e:
    print("Network or unexpected error:", e)
paymentInvoiceRequest request = paymentInvoiceRequest.builder()
    .paymentLinkId("YOUR_PAYMENT_LINK_ID")
    .amount("100.00")
    .currency("USD")
    .productDetails(productDetails.builder()
        .name("Premium Subscription")
        .description("Monthly subscription plan")
        .build())
    .individual(individual.builder()
        .firstName("John")
        .lastName("Doe")
        .email("[email protected]")
        .phone("1234567890")
        .phoneCode("+1")
        .country("US")
        .build())
    .successRedirectUrl("https://yoursite.com/success")
    .failureRedirectUrl("https://yoursite.com/failure")
    .customerOrderId("order-" + System.currentTimeMillis())
    .build();

try {
    String paymentUrl = api.createPaymentInvoice(request);
    System.out.println("Payment URL: " + paymentUrl);
    // Redirect user to paymentUrl to complete payment
} catch (transfiError e) {
    System.err.println("Error: " + e.getMessage());
    System.err.println("Status Code: " + e.getStatusCode());
    System.err.println("Response: " + e.getResponseData());
}
$api = new TransFiPaymentAPI([
    'publicKey' => 'YOUR_PUBLIC_KEY',
    'secretKey' => 'YOUR_SECRET_KEY',
]);

$product = new ProductDetails('Premium Plan');
$product->description = 'Monthly subscription';

$individual = new Individual('John', 'Doe', '[email protected]');
$individual->phone     = '1234567890';
$individual->phoneCode = '+1';
$individual->country   = 'US';

$paymentData = new PaymentInvoiceRequest(
    'LINK_ID',
    '100',
    'USD',
    'https://example.com/success',
    'https://example.com/failure'
);
$paymentData->productDetails  = $product;
$paymentData->individual      = $individual;
$paymentData->customerOrderId = 'order-001';

try {
    $paymentUrl = $api->createPaymentInvoice($paymentData);
    echo 'Checkout URL: ' . $paymentUrl . PHP_EOL;
} catch (TransFiError $e) {
    echo 'API Error   : ' . $e->getMessage() . PHP_EOL;
    echo 'Status Code : ' . $e->getStatusCode() . PHP_EOL;
    echo 'Response    : ' . json_encode($e->getResponseData(), JSON_PRETTY_PRINT) . PHP_EOL;
}

Python: Alternative dict syntax

The Python SDK also accepts a plain dict with camelCase keys matching the JSON API directly, if you prefer not to use the dataclasses:

payment_url = api.create_payment_invoice({
    "paymentLinkId": "your-payment-link-id",
    "amount": "100",
    "currency": "USD",
    "productDetails": {
        "name": "Premium Plan",
        "description": "Monthly subscription",
    },
    "individual": {
        "firstName": "John",
        "lastName": "Doe",
        "email": "[email protected]",
        "phone": "1234567890",
        "phoneCode": "+1",
        "country": "US",
    },
    "successRedirectUrl": "https://example.com/success",
    "failureRedirectUrl": "https://example.com/failure",
    "customerOrderId": "order-001",
})

Python: Context manager

The Python client supports the context manager protocol, which ensures the underlying HTTP session is properly closed:

with TransFiPaymentAPI(public_key="...", secret_key="...") as api:
    payment_url = api.create_payment_invoice(request)
    print(payment_url)

SDK Reference Summary

Node.js (transfi-checkout)Java(transfi-checkout)Python (transfi-sdk)PHP (transfi/payment-sdk)
Installnpm install transfi-checkoutMaven/Gradle via JitPack (com.github.Trans-Fi:transfi-checkout-java-sdk:v1.0.0)pip install transfi-sdkcomposer require transfi/payment-sdk
Importrequire("transfi-checkout")No explicit import needed (classes used directly)from transfi import ...use TransFi\TransFiPaymentAPI
Client classTransFiPaymentAPItransfiPaymentApiTransFiPaymentAPITransFiPaymentAPI
Create invoiceclient.createPaymentInvoice(data)api.createPaymentInvoice(request)api.create_payment_invoice(data)$api->createPaymentInvoice($data)
Error classTransFiErrortransfiErrorTransFiErrorTransFiError
Status codeerror.statusCodee.getStatusCode()e.status_code$e->getStatusCode()
Response bodyerror.responseDatae.getResponseData()e.response_data$e->getResponseData()
Context managerNoNoYes (with statement)No
Dict inputYes (camelCase keys)No (Builder pattern)Yes (camelCase keys)Yes (plain array, camelCase keys)
Typed inputNoYes (paymentInvoiceRequest, productDetails, individual builders)Yes (PaymentInvoiceRequest, etc.)Yes (PaymentInvoiceRequest, Individual, ProductDetails, Address)