Skip to main content
The customer lifecycle in Paygentic involves creating customer relationships, establishing subscriptions, and tracking usage. This guide covers the programmatic approach to managing customers through the API.

Overview

Paygentic supports two distinct types of consumer accounts, each with different capabilities and use cases:

Managed Consumers

Created via API by merchants for quick onboarding. Customers only access Paygentic in relation to this one merchant. These customer do not have Paygentic users and only use Paygentic through the merchant integration.

Full Consumer Accounts

When the customer interacts with multiple merchants they can choose to keep everything in one account and sign in to Paygentic to manage their usage.
Normally customers will start off as a managed customer and only transition to a full account when needed. The key point for merchants is that in managed accounts the account funds are exclusively available to that merchant.

Creating Customers via API

Prerequisites

  • Valid merchant API key
  • Merchant account ID
  • Customer email and preferable address
API Reference: See the Create Customer API endpoint for complete request and response schemas.
  • New Managed Consumer
  • Existing Managed Consumer
When creating a new customer with consumer data, you’re establishing a managed consumer account:
const axios = require('axios');

async function createManagedCustomer() {
  try {
    const response = await axios.post(
      'https://api.paygentic.io/v0/customers',
      {
        merchantId: 'org_YS8jkP59V71TdUvj',
        consumer: {
          name: 'John Doe',
          email: 'john.doe@example.com',
          phone: '+1-555-0100',
          address: {
            line1: '123 Main St',
            city: 'San Francisco',
            state: 'CA',
            country: 'US',
            zipCode: '94105'
          }
        }
      },
      {
        headers: {
          'Authorization': 'Bearer sk_live_YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('Customer created:', response.data.customerId);
    return response.data.customerId;
  } catch (error) {
    console.error('Error creating customer:', error.response?.data);
    throw error;
  }
}
Idempotency: If a customer already exists for the consumer-merchant pair, the API returns 200 with the existing customer ID instead of creating a duplicate.

Creating Subscriptions

Once you have a customer, you can create subscriptions. When creating a subscription you can define the amounts for flat billable metrics. These are recurring fees for every subscription period. Flat fees that have instantly charged prices need to be paid before the subscription starts. In the subscription response there will be a payment link where the customer can pay for this charge. The payment link is also present if the subscription has a “prefundAmount”, this should be used to add funds for pay as go (instantly priced usage billable metrics).
API Reference: See the Create Subscription API endpoint for complete request and response schemas.
async function createPostpaidSubscription(customerId, planId) {
  try {
    const response = await axios.post(
      'https://api.paygentic.io/v0/subscriptions',
      {
        customerId: customerId,
        planId: planId,
        name: 'Monthly API Service',
        startedAt: new Date().toISOString(),
        prefundAmount: "25"
      },
      {
        headers: {
          'Authorization': 'Bearer sk_live_YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      }
    );

    const subscription = response.data;
    console.log('Subscription created:', subscription.id);
    console.log('Payment link (if payment is required):', subscription.payment?.checkoutUrl);
    
    return subscription;
  } catch (error) {
    console.error('Error creating subscription:', error.response?.data);
    throw error;
  }
}

Customer Portal

The customer portal allows your customers to view their subscription details, usage metrics, invoices, and manage payment sources - all within a secure, hosted interface.
  • Managed Consumer Portal
  • Full Platform Access
For managed consumers, generate portal links via the subscription endpoint:
API Reference: See the Generate Portal Link API endpoint for complete request and response schemas.
async function generatePortalLink(subscriptionId) {
  try {
    const response = await axios.post(
      `https://api.paygentic.io/v0/subscriptions/${subscriptionId}/portal`,
      {},
      {
        headers: {
          'Authorization': 'Bearer sk_live_YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      }
    );

    const portalUrl = response.data.url;
    console.log('Portal URL:', portalUrl);
    return portalUrl;
  } catch (error) {
    console.error('Error generating portal link:', error.response?.data);
    throw error;
  }
}
This provides read-only access to subscription data, source management, and usage tracking.

Embedding the Portal

You can embed the customer portal directly into your application, providing a seamless experience without redirecting users away.

Setup Requirements

Before embedding:
  1. Domain Whitelisting: Contact support@paygentic.io to whitelist your domain(s)
  2. CSP Configuration: Add platform.paygentic.io to your CSP frame-src directive:
Content-Security-Policy: frame-src 'self' https://platform.paygentic.io;

Implementation

<!DOCTYPE html>
<html>
<body>
  <iframe
    src="https://platform.paygentic.io/portal/access/PORTAL_ACCESS_TOKEN"
    width="100%"
    height="800px"
    sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
    style="border: none; border-radius: 8px;"
  ></iframe>
</body>
</html>
Important:
  • Portal URLs are single-use - generate a fresh URL for each session or page reload
  • The sandbox attribute is required for security
The sandbox attribute is required for security:
  • allow-scripts - Portal functionality
  • allow-same-origin - Communication with your site
  • allow-forms - Form submission
  • allow-popups - 3D Secure authentication

Payment Checkout

Payment checkout provides a hosted payment form for collecting payments on invoices or subscription fees.

Creating Payment Sessions

  • For Invoices
  • For Subscriptions
Create a checkout session for an existing invoice:
async function createInvoiceCheckout(invoiceId) {
  const response = await axios.post(
    `https://api.paygentic.io/v0/invoices/${invoiceId}/checkout`,
    {
      redirectUrls: {
        onSuccess: 'https://yourapp.com/success',
        onFailure: 'https://yourapp.com/failure'
      },
      savePaymentMethod: true
    },
    {
      headers: {
        'Authorization': 'Bearer sk_live_YOUR_API_KEY',
        'Content-Type': 'application/json'
      }
    }
  );

  return response.data.paymentUrl;
}

Embedding Payment Checkout

<!DOCTYPE html>
<html>
<body>
  <iframe
    src="https://platform.paygentic.io/portal/pay/ps_SESSION_ID"
    width="100%"
    height="800px"
    sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
    style="border: none; border-radius: 8px;"
  ></iframe>

  <script>
    window.addEventListener('message', function(event) {
      if (event.origin !== 'https://platform.paygentic.io') return;
      
      if (event.data?.type === 'payment_success') {
        window.location.href = '/success';
      } else if (event.data?.type === 'payment_error') {
        alert('Payment failed. Please try again.');
      }
    });
  </script>
</body>
</html>

Handling Payment Events

The payment checkout communicates completion status via postMessage events:
Event TypeWhen Triggered
payment_successPayment completed successfully
payment_errorPayment failed or was cancelled
How redirects work:
  • Standalone page: Customers are redirected to your specified redirectUrls
  • Embedded iframe: postMessage events are sent instead of redirecting
  • The system automatically detects the context
Success handling example:
if (event.data?.type === 'payment_success') {
  // Update UI to show success
  showSuccessMessage();
  
  // Optionally redirect
  setTimeout(() => {
    window.location.href = '/dashboard';
  }, 2000);
}
Error handling example:
if (event.data?.type === 'payment_error') {
  // Show error message
  showError('Payment failed. Please check your payment method.');
  
  // Log for debugging
  console.error('Payment failed');
  
  // Offer to retry
  showRetryButton();
}

Next Steps

  • Learn about Usage Events for tracking consumption
  • Explore Pricing for billing configuration
  • Understand Accounts for payment management