Tesouro SDK for Node.js

June 17, 2025 ยท View on GitHub

A TypeScript-first GraphQL SDK for the Tesouro payment platform with built-in OAuth 2.0 authentication and comprehensive error handling.

npm version TypeScript License

Features

  • ๐Ÿš€ TypeScript-first - Full type safety with auto-generated types from GraphQL schema
  • ๐Ÿ” Automatic Authentication - Built-in OAuth 2.0 client credentials flow with token refresh
  • ๐ŸŒ Proxy Support - HTTP/HTTPS proxy configuration with authentication
  • ๐Ÿ“Š GraphQL Native - Strongly-typed GraphQL operations with automatic query generation
  • โšก Performance Optimized - Concurrent request support and intelligent token management
  • ๐Ÿ›ก๏ธ Error Handling - Comprehensive error types and validation
  • ๐Ÿ“š Well Documented - Extensive examples and JSDoc comments
  • ๐Ÿงช Testing Ready - Built-in testing utilities and mock support

Quick Start

Installation

npm install @tesouro/tesouro-sdk-for-node

Basic Usage

import { TesouroClient } from '@tesouro/tesouro-sdk-for-node';

// Initialize the client
const client = new TesouroClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret'
});

// Query payment transactions
const result = await client.paymentTransactions({
  input: {
    paging: { skip: 0, take: 10 },
    where: {
      transactionActivityDate: {
        gte: '2024-01-01',
        lte: '2024-01-31'
      }
    }
  }
});

console.log(`Found ${result.data?.paymentTransactions.items.length} transactions`);

Process a Payment

import { randomUUID } from 'crypto';

const result = await client.authorizeCustomerInitiatedTransaction({
  authorizeCustomerInitiatedTransactionInput: {
    acceptorId: 'your-acceptor-id',
    transactionReference: randomUUID(),
    automaticCapture: 'NEVER',
    transactionAmountDetails: {
      totalAmount: 25.99,
      currency: 'USD'
    },
    paymentMethodDetails: {
      cardWithPanDetails: {
        accountNumber: '4100000000000001',
        paymentEntryMode: 'KEYED',
        expirationMonth: '12',
        expirationYear: '2025',
        securityCode: { value: '123' }
      }
    }
  }
});

const authResponse = result.data?.authorizeCustomerInitiatedTransaction.authorizationResponse;
if (authResponse) {
  console.log(`Payment authorized! Transaction ID: ${authResponse.transactionId}`);
}

๐Ÿ“– Full Quick Start Guide โ†’

Documentation

Examples

The SDK includes comprehensive examples for common use cases:

Query Patterns

Payment Operations

Authentication & Security

Running Examples

cd examples/test-project
npm install
cp .env.example .env   # Add your credentials
npm run test:query     # Test query operations
npm run test:auth      # Test authentication
npm run test:mutations # Test payment operations
npm run test:proxy     # Test proxy configuration

Configuration

Environment Variables

Create a .env file in your project:

TESOURO_CLIENT_ID=your-client-id
TESOURO_CLIENT_SECRET=your-client-secret
TESOURO_ENDPOINT=https://api.sandbox.tesouro.com/graphql
TESOURO_TOKEN_ENDPOINT=https://api.sandbox.tesouro.com/openid/connect/token

# Optional: Proxy configuration
HTTPS_PROXY=http://proxy.company.com:8080
HTTP_PROXY=http://proxy.company.com:8080

Client Configuration

const client = new TesouroClient({
  // Required
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  
  // Optional
  endpoint: 'https://api.sandbox.tesouro.com/graphql', // Defaults to sandbox
  tokenEndpoint: 'https://api.sandbox.tesouro.com/openid/connect/token', // Auto-derived
  timeout: 30000, // Request timeout in ms
  headers: {
    'X-API-Version': '2024-01-01' // Default headers
  },
  
  // Proxy configuration (optional)
  proxy: {
    url: 'http://proxy.company.com:8080',
    username: 'proxy-user', // Optional
    password: 'proxy-pass'  // Optional
  }
});

Error Handling

The SDK provides comprehensive error handling with specific error types:

import { GraphQLError, NetworkError, SdkError } from '@tesouro/tesouro-sdk-for-node';

try {
  const result = await client.paymentTransactions(variables);
  
  if (result.errors?.length) {
    console.log('GraphQL validation errors:', result.errors);
  }
  
} catch (error) {
  if (error instanceof NetworkError) {
    console.error('Network issue:', error.message);
  } else if (error instanceof GraphQLError) {
    console.error('API errors:', error.errors);
  } else if (error instanceof SdkError) {
    console.error('SDK error:', error.message);
  }
}

TypeScript Support

The SDK is built with TypeScript and provides full type safety:

import type {
  TesouroClient,
  QueryPaymentTransactionsArgs,
  PaymentTransactionCollection,
  CustomerInitiatedTransactionAuthorizationInput
} from '@tesouro/tesouro-sdk-for-node';

// All types are automatically generated from the GraphQL schema
const variables: QueryPaymentTransactionsArgs = {
  input: {
    paging: { skip: 0, take: 10 },
    where: {
      transactionActivityDate: {
        gte: '2024-01-01',
        lte: '2024-01-31'
      }
    }
  }
};

Proxy Support

The SDK supports HTTP/HTTPS proxies for corporate environments:

Environment Variable Configuration (Automatic)

# Set proxy via environment variables (recommended)
export HTTPS_PROXY=http://proxy.company.com:8080
export HTTP_PROXY=http://proxy.company.com:8080

# With authentication
export HTTPS_PROXY=http://username:password@proxy.company.com:8080

Explicit Configuration

const client = new TesouroClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  proxy: {
    url: 'http://proxy.company.com:8080',
    username: 'proxy-username', // Optional
    password: 'proxy-password'  // Optional
  }
});

Proxy Priority

  1. Explicit proxy configuration (highest priority)
  2. HTTPS_PROXY environment variable
  3. HTTP_PROXY environment variable
  4. https_proxy environment variable (lowercase)
  5. http_proxy environment variable (lowercase)

๐Ÿ“– Complete Proxy Examples โ†’

๐Ÿงช Test Proxy Setup โ†’

Advanced Features

Concurrent Requests

const [transactions, summaries] = await Promise.all([
  client.paymentTransactions(transactionVariables),
  client.paymentTransactionSummaries(summaryVariables)
]);

Custom Request Options

const result = await client.paymentTransactions(variables, {
  timeout: 10000,
  headers: {
    'X-Request-ID': 'unique-request-id'
  }
});

Token Management

// Automatic refresh (recommended)
const client = new TesouroClient(config);

// Access to low-level auth if needed
import { AuthManager } from '@tesouro/tesouro-sdk-for-node';
const authManager = new AuthManager(authConfig);

Development

Prerequisites

  • Node.js 18+
  • npm 8+
  • TypeScript 4.8+

Setup

git clone https://github.com/tesourohq/tesouro-sdk-for-node.git
cd tesouro-sdk-for-node
npm install

Scripts

npm run build            # Build the project
npm run test             # Run all tests
npm run lint             # Lint code
npm run typecheck        # Type checking
npm run docs             # Generate documentation

Testing

The SDK includes comprehensive test suites:

  • Unit Tests - Fast, isolated component testing
  • Integration Tests - Real API testing with mocked responses
  • Example Tests - Verification that all examples work correctly
npm test                   # All tests
npm test:unit              # Unit tests
npm test:integration       # Integration tests

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


Made with โค๏ธ by the Tesouro team