Headless Integration using SDK

The Payrails SDK provides a comprehensive set of API methods and query functions for integrating payment processing capabilities into your application. This documentation covers the headless API methods and configuration query functions available through the main Payrails class.

API Methods

The Payrails SDK provides REST API methods through the api() function for making calls to payrails backend directly from the client.

api

ParameterTypeDescription
configApiConfig<TReq> & { operation: TOperation }Configuration object containing operation details

Returns: Promise<Operations[TOperation]['responseType']>

Available Operations

OperationMethodDescriptionRequired Parameters
deleteInstrumentDELETEDeletes a stored payment instrumentresourceId
updateInstrumentPATCHUpdates properties of an existing payment instrumentresourceId, body

Delete Payment Instrument

const result = await payrails.api({
  operation: 'deleteInstrument',
  resourceId: 'instrument_id_here',
});

Response: DeleteInstrumentResponse

FieldTypeDescription
successbooleanIndicates if the deletion was successful

Update Payment Instrument

const result = await payrails.api({
  operation: 'updateInstrument',
  resourceId: 'instrument_id_here',
  body: {
    status: 'enabled',
    default: true,
    merchantReference: 'your_reference',
    networkTransactionReference: 'network_ref',
  },
});

Request Body Fields:

FieldTypeRequiredDescription
status'enabled'| 'disabled'NoEnable or disable the instrument
networkTransactionReferencestringNoNetwork transaction reference
merchantReferencestringNoMerchant reference identifier
paymentMethod'applepay' |'card'|'googlepay'|'paypal'NoPayment Method Type
defaultbooleanNoSet as default payment instrument

Response Fields:

FieldTypeDescription
idstringUnique instrument identifier
createdAtstringCreation timestamp
holderIdstringHolder identifier
paymentMethodPAYMENT_METHOD_CODESPayment method type
statusPAYMENT_INSTRUMENT_STATUSCurrent status
dataINSTRUMENT_OBJECTPayment method specific data

Query Methods

The query system allows you to retrieve configuration data and SDK state information without making external API calls.

query

ParameterTypeRequiredDescription
keyK extends keyof ConfigurationQueryTypesYesThe configuration key to query
paramsRecord<string, any>NoOptional parameters for specific queries

Returns: ConfigurationQueryTypes[K]['returnType'] | null

Available Query Keys

Query KeyParametersReturn TypeDescription
holderReferencestringRetrieves the holder reference for the current session
amountPayrailsAmountGets the current payment amount configuration
executionIdstring|undefinedRetrieves the current workflow execution ID
binLookupLinks|undefinedGets the BIN lookup service endpoint
instrumentDeleteLinks|undefinedGets the instrument deletion endpoint
instrumentUpdateLinks|undefinedGets the instrument update endpoint
paymentMethodConfigpaymentMethodCode: stringStorablePaymentCompositionOption|undefinedRetrieves configuration for a specific payment method
paymentMethodInstrumentspaymentMethodCode: stringStoredPaymentInstrument<CardMetadata|PayPalMetadata[]|undefinedGets stored instruments for a specific payment method

Query Examples

Basic Configuration Queries

// Get holder reference
const holderRef = payrails.query('holderReference');

// Get current amount
const amount = payrails.query('amount');

// Get execution ID
const executionId = payrails.query('executionId');

Link Queries

// Get API endpoints
const binLookupLink = payrails.query('binLookup');
const deleteLink = payrails.query('instrumentDelete');
const updateLink = payrails.query('instrumentUpdate');

Payment Method Queries

// Get payment method configuration
const cardConfig = payrails.query('paymentMethodConfig', {
  paymentMethodCode: 'card',
});

// Get stored instruments for a payment method
const cardInstruments = payrails.query('paymentMethodInstruments', {
  paymentMethodCode: 'card',
});

Error Handling

All API methods may throw PayrailsError exceptions. It's recommended to wrap API calls in try-catch blocks:

try {
  const result = await payrails.api({
    operation: 'deleteInstrument',
    resourceId: 'instrument_id',
  });
  console.log('Instrument deleted successfully:', result.success);
} catch (error) {
  if (error instanceof PayrailsError) {
    console.error('Payrails API error:', error.message);
    // Handle specific error codes
  } else {
    console.error('Unexpected error:', error);
  }
}

Query methods return null instead of throwing errors when data is not found:

const amount = payrails.query('amount');
if (amount === null) {
  console.log('Amount not configured');
} else {
  console.log('Current amount:', amount);
}

Examples

Complete Instrument Management Example

// Initialize Payrails client
const payrails = Payrails.init(initResponse, options);

// Query for stored card instruments
const cardInstruments = payrails.query('paymentMethodInstruments', {
  paymentMethodCode: 'card',
});

if (cardInstruments && cardInstruments.length > 0) {
  const instrument = cardInstruments[0];

  // Update the instrument
  try {
    const updatedInstrument = await payrails.api({
      operation: 'updateInstrument',
      resourceId: instrument.id,
      body: {
        status: 'enabled',
        default: true,
      },
    });

    console.log('Instrument updated:', updatedInstrument);
  } catch (error) {
    console.error('Failed to update instrument:', error);
  }
}

Integration Notes

AspectDescription
AuthenticationAll API calls are automatically authenticated using the SDK's internal token management
Resource IDsWhen working with payment instruments, ensure you have the correct resourceId from previous queries or operations
Error HandlingAlways implement proper error handling for API calls, as network issues or invalid requests can cause exceptions
Query PerformanceQuery methods are fast local operations that don't make network requests, making them suitable for frequent calls
Parameter ValidationSome queries require specific parameters (like paymentMethodCode). Missing required parameters will result in null returns with warning logs

Best Practices

PracticeRecommendation
Cache Query ResultsFor frequently accessed configuration data, consider caching query results to improve performance
Handle Null ReturnsAlways check for null returns from query methods before using the data
Use TypeScriptLeverage the provided TypeScript types for better development experience and error prevention
Error RecoveryImplement appropriate error recovery strategies for failed API operations
LoggingMonitor API usage and errors through your application logging system for better debugging and maintenance