@tesouro/tesouro-sdk-for-node
v0.0.7
Published
TypeScript-first Node.js SDK for GraphQL API with OpenID Connect authentication
Readme
Tesouro SDK for Node.js
A TypeScript-first GraphQL SDK for the Tesouro payment platform with built-in OAuth 2.0 authentication and comprehensive error handling.
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-nodeBasic 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}`);
}Documentation
- Quick Start Guide - Get up and running in minutes
- API Reference - Complete API documentation
- Examples - Working code examples for common use cases
- Test Project - Runnable examples and testing patterns
Examples
The SDK includes comprehensive examples for common use cases:
Query Patterns
- Basic Queries - Simple data retrieval
- Pagination - Handle large datasets
- Concurrent Requests - Parallel API calls
Payment Operations
- Mutations - Payment authorization, capture, and refund
- Complete Payment Lifecycle - End-to-end payment processing
Authentication & Security
- Authentication Patterns - OAuth setup and token management
- Token Refresh - Advanced token handling strategies
- Proxy Configuration - HTTP proxy setup and corporate network support
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 configurationConfiguration
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:8080Client 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:[email protected]:8080Explicit 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
- Explicit proxy configuration (highest priority)
HTTPS_PROXYenvironment variableHTTP_PROXYenvironment variablehttps_proxyenvironment variable (lowercase)http_proxyenvironment variable (lowercase)
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 installScripts
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 documentationTesting
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 testsLicense
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📚 Documentation: docs/ and Tesouro API Docs
- 📧 Email: [email protected]
Made with ❤️ by the Tesouro team
