Complete API Documentation for Third-Party Integration
v1.0.0Production Ready100% Test Coverage
📋 Overview
The Appfinity Pay Later SDK enables third-party platforms to seamlessly integrate our Pay Later solution into their applications. Our SDK provides a complete credit system with instant approvals, flexible repayment options, and comprehensive fraud protection.
✨ Key Features
Instant Credit Approval: Real-time credit decisions using advanced algorithms
Flexible Repayment: Multiple repayment options and schedules
Recurring Payments: Automated subscription billing and installment management
Advanced Security: CreepJS-powered fraud detection and device fingerprinting
Multi-Currency Support: Support for multiple currencies and countries
Real-time Notifications: Webhook support for transaction updates
Easy Integration: Simple JavaScript SDK with comprehensive documentation
🎯 Perfect For: E-commerce platforms, gaming platforms, subscription services, marketplace applications, and any platform requiring flexible payment solutions.
Callback URL Behavior
The SDK forwards callbackUrl to your Telegram bot/server for server-side notifications.
By default it does not automatically redirect the page after payment. You can either
enable auto-redirect in the SDK or manually handle it via events.
Auto-redirect: set autoRedirect: true in DirectPayment.init.
Manual redirect: listen for payment_success or payment_verified and redirect.
Include transaction_id (and any fields you need) as query params.
// Example: redirect after success or verified Telegram payment
DirectPayment.onEvent(function (evt) {
if (!evt) return;
var isSuccess = evt.type === 'payment_success' && evt.payload && evt.payload.success;
var isVerified = evt.type === 'payment_verified' && evt.payload && evt.payload.verified;
if (isSuccess || isVerified) {
var tx = (evt.payload && (evt.payload.transaction_id || evt.transaction_id)) || '';
var redirectUrl = 'https://yourapp.com/telegram/callback?tx=' + encodeURIComponent(tx);
window.location.href = redirectUrl;
}
});
🔐 Authentication
All API requests require authentication using Platform API Keys. Contact our team to get your production API keys.
API Key Types
Environment
Key Format
Usage
Sandbox
pk_test_...
Development and testing
Production
pk_live_...
Live transactions
Authentication Headers
// Required headers for all API requests
Headers:
'X-Platform-API-Key': 'your_platform_api_key'
'X-Platform-ID': 'your_platform_id'
'Content-Type': 'application/json'
🪙 Crypto Payment
Create cryptocurrency payments using NOWPayments. You pass a fiat amount and currency
(e.g., USD) and select a crypto to pay with (e.g., USDT, BTC, ETH). The response includes
a payment address and estimated crypto amount to transfer. Optionally provide a
clientWebhook URL to receive forwarded IPN updates.
What is a webhook?
A webhook is an HTTP callback endpoint on your server. When the payment status changes,
our server sends a POST request to your webhook URL so your app can automatically update
the order state and notify users without polling.
Endpoint
POST /checkout/crypto
Headers:
'Content-Type': 'application/json'
'x-api-key': 'YOUR_PLATFORM_API_KEY'
Request Body
Name
Type
Required
Description
order_id
string
Required
Alphanumeric identifier for your order (max 64 chars)
fiat_amount
number
Required
Fiat amount to charge (e.g., 49.99)
fiat_currency
string
Required
Fiat currency code (e.g., USD)
pay_currency
string
Required
Crypto currency code to pay with (e.g., USDT, BTC, ETH)
customer
object
Optional
{ user_id, email } to associate payment with a user
clientWebhook
string
Optional
HTTPS URL to receive forwarded IPN payloads from our server
NOWPayments sends IPN callbacks to your server at /webhook/crypto-payment. Our server verifies
signatures when NOWPAYMENTS_IPN_SECRET is configured and will forward the received payload to your
provided clientWebhook URL. You receive events for statuses like paid,
partially_paid, expired, cancelled, failed, and pending.
// Example IPN payload (forwarded to your clientWebhook)
{
"order_id": "ORDER_12345",
"payment_id": "np_abc123",
"payment_status": "paid",
"pay_amount": "49.99",
"pay_currency": "USDT"
}
Notes:
Ensure your clientWebhook is publicly reachable over HTTPS.
Store order_id in your system to reconcile IPN events.
Forwarding failures are logged and do not block processing.
Telegram Crypto (TON)
Create a crypto payment via Telegram using TON. The SDK opens the Telegram payment bot in a new tab
and provides an overlay to verify payment status. Fiat and crypto currencies are fixed to
USD and TON respectively; the SDK auto-generates the order_id internally.
SDK Usage
// Include SDK
// Initialize and start Telegram crypto
DirectPayment.init({ apiBase: window.location.origin, debug: true });
await DirectPayment.startTelegramCrypto({
// Optional inputs; if omitted, the SDK overlay collects values
customerEmail: 'user@example.com',
platformId: 'Appfinity Store',
gameId: 'HINGEY',
credits: 100, // optional: purchase app credits with the payment
callbackUrl: 'https://yourapp.com/telegram/callback'
});
Parameters
Name
Type
Required
Description
customerEmail
string
No
User email for receipts and verification; shown in overlay if omitted.
platformId
string
No
Your platform identifier/name for multi-tenant setups.
gameId
string
No
Optional game/app identifier for attribution.
credits
number
No
Optional numeric credits to purchase alongside the Telegram payment.
callbackUrl
string (URL)
No
Optional URL to receive server-side updates related to the Telegram transaction.
Behavior & Internals:
orderId is auto-generated by the SDK.
fiatCurrency is fixed to USD; payCurrency is fixed to TON.
userId is auto-assigned per request as a random 6-digit number.
The SDK creates the transaction via your bot API and opens telegram_payment_url in a new tab.
Bot Config Endpoint
The SDK fetches the Telegram bot API URL and key from your server:
The SDK posts to the Telegram bot API to create the transaction and opens the returned payment URL in a new tab.
A simplified response from the bot looks like:
Use the overlay's Verify Payment button, or call these endpoints programmatically:
// Check status
GET /api/transaction/{transaction_id}
// Verify on blockchain if still pending
POST /api/transaction/{transaction_id}/check-blockchain
// Headers
'Accept': 'application/json'
'x-api-key': 'YOUR_PLATFORM_API_KEY'
Notes:
The SDK hides internal-only fields (order ID, user/platform IDs) but uses fixed values internally.
The SDK opens response.data.telegram_payment_url in a new tab automatically.
The overlay includes a Verify Payment button to check status and perform blockchain verification.
callbackUrl is forwarded to your bot/server for server-side notifications; the SDK does not auto-redirect.
To redirect after verification, handle events via DirectPayment.onEvent:
Render a centered modal overlay with an iframe to complete card payments. A spinner appears while the iframe loads and during message processing. Your callback receives the full payload for both success and failure.
This initializes Direct Payment for a one-time card checkout. It does not set up
recurring charges or subscriptions.
DirectPayment.init({
apiKey: 'YOUR_PLATFORM_API_KEY',
debug: true,
apiBase: "https://appfinitystore.com",
onEvent: function (payload) {
// Called for both success and failure
console.log('Callback payload:', payload);
if (payload && payload.success) {
console.log('Payment success!');
// e.g., update UI, call backend, redirect
DirectPayment.close();
} else {
console.log('Payment not successful');
// e.g., show retry option
DirectPayment.close();
}
}
});
For Recurring: Initialize and Save Identifiers
Initialize the SDK and capture identifiers for recurring charges. On a successful
payload, save the following per user for future billing:
payload.customer_id — the customer identifier on the gateway
payload.gateway — the gateway used (e.g., flutterwave, stripe)
payload.payment_method_id — the saved payment method/token id
DirectPayment.init({
apiKey: 'YOUR_PLATFORM_API_KEY',
debug: true,
apiBase: " `https://appfinitystore.com` ",
onEvent: function (payload) {
// Called for both success and failure
console.log('Callback payload:', payload);
if (payload && payload.success) {
console.log('Payment success!');
// Save identifiers per user for recurring charges
// e.g., persist payload.customer_id, payload.gateway, payload.payment_method_id
DirectPayment.close();
} else {
console.log('Payment not successful');
// e.g., show retry option
DirectPayment.close();
}
}
});
After saving these identifiers, use them to perform actual recurring billing
with the SDK method below.
Recurring: chargeByMethod
Server-side recurring charge using saved customer and payment method identifiers.
No iframe is rendered; results are delivered via your onEvent callback.
Omit containerId to use overlay mode (centered modal). Provide containerId to render inline.
(async function startPayment() {
try {
await DirectPayment.initiate({
email: 'user@example.com',
amount: 100,
platformId: 'Appfinity Store',
currency: 'USD'
// containerId: 'payment-container' // optional for inline mount
});
} catch (err) {
console.error('Failed to initiate payment:', err);
alert('Failed to initiate payment: ' + err.message);
}
})();
Close Overlay
DirectPayment.close();
Behavior: Spinner shows before iframe load and while processing messages; hides after processing. Background scrolling is disabled while overlay is open. Iframe height defaults to ~88vh.
Telegram Crypto (SDK)
The Direct Payment SDK also supports a Telegram-based crypto flow for TON. This presents a
guided overlay to collect required fields, creates the transaction via your Telegram bot API,
opens the payment in Telegram, and provides a verification button.
Overlay shows fixed fiat/crypto values at the top (USD / TON).
Order ID is auto-generated and hidden from the form.
Transaction is created and telegram_payment_url opens in a new tab.
Use Verify Payment to check status and perform blockchain verification.
userId is auto-assigned per request as a random 6-digit number.
If credits is provided, it is included in the transaction payload.
⚡ SDK Integration Flow
Complete guide to integrating Appfinity Pay Later SDK into your application:
Step 1: Include the SDK
Add our JavaScript SDK to your website. The SDK handles all Pay Later interactions, UI components, and API communications:
<!-- Include the Appfinity Pay Later SDK -->
<script src="https://appfinitystore.com/js/appfinity-sdk.js"></script>
<!-- Optional: Include CSS for default styling -->
<link rel="stylesheet" href="https://appfinitystore.com/css/paylater-ui.css">
Step 2: Initialize the SDK
Initialize the SDK with your platform credentials:
Note: The deductAmount parameter is optional and is used when you want to immediately purchase coins from the Appfinity wallet. When provided, the system will attempt to deduct the specified amount from the user's wallet during Step 1 of the flow. The response of this deduction operation will be received in the callbackFunction, allowing you to handle success or failure scenarios accordingly.
Expected Response Format
The callbackFunction(res) will receive a response object with the following structure:
// Success Response (Top Up - Step 3)
{
type: 'top-up',
step: 3,
success: true,
message: 'TopUp successful',
data: {
success: true,
message: "Wallet balance deducted successfully",
data: {
wallet: {
amountDeducted: 50,
currency: "USD",
description: "SDK deduction",
email: "user@example.com",
eventId: 98,
newBalance: 250,
platformId: "your_platform_id",
previousBalance: 300,
transactionAt: "2025-09-23T11:32:58.947Z",
userId: "your_user_id"
}
}
}
}
// Error Response
{
success: false,
message: "Insufficient wallet balance",
error: {
code: "INSUFFICIENT_FUNDS",
details: "Current balance: $25.50, Required: $50.00"
}
}
// Other possible error codes:
// "INVALID_AMOUNT" - Amount is invalid or negative
// "USER_NOT_FOUND" - User account not found
// "WALLET_LOCKED" - User wallet is temporarily locked
// "NETWORK_ERROR" - Connection or server error
The type field in the callback can be "step", "deduction", or "top-up".
To get a callback for Step 3 (card save), check response.type == "step" and response.step == 3.
For deductions, response.type == "deduction". For top up, response.type == "top-up".
// Examples of handling callback types
Appfinity.startFlow({
email: "user@example.com",
callbackFunction: (response) => {
// Step 3: card save completed
if (response.type === 'step' && response.step === 3) {
console.log('Card saved / Step 3 completed');
// Handle post-card-save logic
}
// Deduction event (wallet deduction during Step 1)
else if (response.type === 'deduction') {
console.log('Wallet deduction event:', response);
// Handle deduction success/failure
}
// Top Up flow completed
else if (response.type === 'top-up') {
console.log('Top Up successful:', response);
// Handle top-up success
}
}
});
// Note: If your integration wraps callback payload under `data`,
// you can equivalently check:
// response.data && response.data.type === 'step' && response.data.step === 3
// response.data && response.data.type === 'deduction'
// response.data && response.data.type === 'top-up'
Top-Up Flow Function
The startTopupThenFlow function is designed specifically for displaying the top-up interface to users.
This function opens the top-up modal where users can add funds to their wallet, and provides a callback mechanism
to handle the top-up completion events.
The startFlow function can contain additional user parameters for better user experience:
// The startFlow can contain other parameters like first_name, last_name, date_of_birth, address, city, zip, country
Appfinity.startFlow({
email: "user@example.com",
first_name: "John",
last_name: "Doe"
}); // etc
Step 5: Wallet API Endpoints
Use these wallet API endpoints to manage user balances and transactions:
Contact our team to obtain your production API credentials.
Test All Scenarios
Run the complete test suite and verify all integration points.
Configure Webhooks
Set up webhook endpoints for real-time transaction updates.
Monitor Performance
Implement logging and monitoring for production usage.
🎉 Ready for Production! The Appfinity Pay Later SDK is production-ready with 100% test coverage, comprehensive documentation, and full technical support.