Skip to main content

JavaScript SDK

The Azotte JavaScript SDK provides a comprehensive interface for integrating subscription functionality into web applications.

Installation

npm/yarn Installation

npm install @azotte/sdk
# or
yarn add @azotte/sdk

CDN Installation

<script src="https://js.azotte.com/v1/azotte.js"></script>

Basic Setup

ES6/TypeScript

import { AzotteClient } from '@azotte/sdk';

const azotte = new AzotteClient({
apiKey: process.env.AZOTTE_API_KEY,
tenantId: process.env.AZOTTE_TENANT_ID,
environment: 'sandbox' // or 'production'
});

CommonJS

const { AzotteClient } = require('@azotte/sdk');

const azotte = new AzotteClient({
apiKey: process.env.AZOTTE_API_KEY,
tenantId: process.env.AZOTTE_TENANT_ID,
environment: 'sandbox'
});

Core Features

Customer Management

// Create a customer
const customer = await azotte.customers.create({
email: 'customer@example.com',
name: 'John Doe',
phone: '+1234567890',
metadata: {
source: 'website'
}
});

// Retrieve customer
const customer = await azotte.customers.retrieve('cus_1234567890');

// Update customer
const updatedCustomer = await azotte.customers.update('cus_1234567890', {
name: 'John Smith'
});

// List customers
const customers = await azotte.customers.list({
limit: 10,
starting_after: 'cus_1234567890'
});

Subscription Management

// Create subscription
const subscription = await azotte.subscriptions.create({
customerId: 'cus_1234567890',
priceId: 'price_premium_monthly',
paymentMethodId: 'pm_card_visa',
trialPeriodDays: 14
});

// Modify subscription
const modifiedSub = await azotte.subscriptions.modify('sub_1234567890', {
priceId: 'price_premium_annual',
prorationBehavior: 'create_prorations'
});

// Cancel subscription
const cancelledSub = await azotte.subscriptions.cancel('sub_1234567890', {
cancelAtPeriodEnd: true
});

Payment Processing

// Create payment
const payment = await azotte.payments.create({
amount: 2999, // $29.99 in cents
currency: 'usd',
customerId: 'cus_1234567890',
paymentMethodId: 'pm_card_visa',
description: 'Premium subscription'
});

// Retrieve payment
const payment = await azotte.payments.retrieve('pi_1234567890');

// Refund payment
const refund = await azotte.refunds.create({
paymentIntentId: 'pi_1234567890',
amount: 2999,
reason: 'requested_by_customer'
});

Frontend Widgets

Checkout Widget

import { AzotteCheckout } from '@azotte/sdk';

// Initialize checkout
const checkout = new AzotteCheckout({
apiKey: 'pk_dev_1234567890abcdef',
tenantId: 'tenant_abc123'
});

// Open hosted checkout
const result = await checkout.redirectToCheckout({
priceId: 'price_premium_monthly',
successUrl: 'https://example.com/success',
cancelUrl: 'https://example.com/cancel'
});

// Embedded checkout
const checkoutSession = await checkout.createSession({
priceId: 'price_premium_monthly',
customerId: 'cus_1234567890'
});

checkout.render({
sessionId: checkoutSession.id,
containerId: 'checkout-container'
});

Pricing Widget

import { AzottePricing } from '@azotte/sdk';

const pricing = new AzottePricing({
apiKey: 'pk_dev_1234567890abcdef',
tenantId: 'tenant_abc123'
});

pricing.render({
containerId: 'pricing-table',
bundles: ['basic', 'premium', 'enterprise'],
theme: 'modern',
onPlanSelect: (priceId) => {
// Handle plan selection
console.log('Selected plan:', priceId);
}
});

Error Handling

try {
const subscription = await azotte.subscriptions.create(subscriptionData);
} catch (error) {
if (error.type === 'AzotteCardError') {
// Handle card-specific errors
console.log('Card error:', error.code, error.message);
} else if (error.type === 'AzotteRateLimitError') {
// Handle rate limiting
console.log('Rate limited, retry after:', error.retryAfter);
} else if (error.type === 'AzotteAuthenticationError') {
// Handle authentication errors
console.log('Authentication failed:', error.message);
} else {
// Handle other errors
console.log('Unexpected error:', error.message);
}
}

Webhooks Integration

const express = require('express');
const { webhook } = require('@azotte/sdk');

const app = express();

app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['azotte-signature'];
let event;

try {
event = webhook.constructEvent(req.body, sig, process.env.WEBHOOK_SECRET);
} catch (err) {
console.log('Webhook signature verification failed.', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}

// Handle the event
switch (event.type) {
case 'subscription.created':
console.log('Subscription created:', event.data.object);
break;
case 'payment.succeeded':
console.log('Payment succeeded:', event.data.object);
break;
default:
console.log(`Unhandled event type ${event.type}`);
}

res.status(200).json({received: true});
});

TypeScript Support

import { AzotteClient, Subscription, Customer } from '@azotte/sdk';

interface CreateSubscriptionParams {
customerId: string;
priceId: string;
paymentMethodId: string;
trialPeriodDays?: number;
}

const createSubscription = async (params: CreateSubscriptionParams): Promise<Subscription> => {
return await azotte.subscriptions.create(params);
};

Configuration Options

const azotte = new AzotteClient({
apiKey: 'your-api-key',
tenantId: 'your-tenant-id',
environment: 'sandbox', // 'sandbox' or 'production'
timeout: 30000, // Request timeout in milliseconds
maxRetries: 3, // Maximum number of retries
retryDelay: 1000, // Delay between retries
userAgent: 'MyApp/1.0', // Custom user agent
});

Next Steps