The TypeScript Payments SDK enables you to subscribe users without requiring a particular frontend framework.
Getting Started
1. Install the SDK
Install the SDK with your preferred package manager.
npm install @microapp-io/payments
2. Import and Initialize the Payments SDK
To use the Payments SDK in your code, import it in any file where you need to use it.
import { Payments } from '@microapp-io/payments';
const payments = new Payments();
For local development, we recommend using the sandbox
feature on the Payments
class to return mocked subscriptions:
import { Payments } from '@microapp-io/payments';
const payments = new Payments({
sandbox: {
enabled: process.env.NODE_ENV !== 'production',
subscription: () => ({
id: 'some-subscription-id',
appId: 'some-app-id',
user: {
id: 'some-user-id',
email: '[email protected]',
name: 'FirstName LastName',
},
active: true,
subscriptionPlan: {
id: 'some-subscription-plan-id',
name: 'free',
priceInCents: 0,
cycle: SubscriptionPlanCycle.ONE_TIME,
features: [
{
name: 'some-feature-name',
description: 'some-feature-description'
},
],
createdAt: new Date(),
updatedAt: new Date(),
},
createdAt: new Date(),
updatedAt: new Date(),
}),
},
});
The sandbox
prop should only be used for local development. Do not use it in production.
3. Check if the User is subscribed
The hasSubscription
method returns the user’s subscription status: true
if subscribed and false
otherwise.
import { Payments } from '@microapp-io/payments';
const hasSubscription = await payments.hasSubscription();
if (hasSubscription) {
console.log('User is subscribed');
} else {
console.log('User is not subscribed');
}
The getSubscription
method returns the user’s subscription information.
import { Payments } from '@microapp-io/payments';
const userSubscription = await payments.getSubscription();
console.log('User subscription:', userSubscription);
5. Prompt the User to subscribe
If the user is not subscribed, you can prompt them to subscribe by calling the requireSubscription
method.
import { Payments } from '@microapp-io/payments';
await payments.requireSubscription();
6. Get Notified when the User is subscribed
You can get notified when the user subscribes or changes its subscription using onUserSubscribed
method.
import { Payments } from '@microapp-io/payments';
const unsubscribeCallback = payments.onUserSubscribed((userSubscription) => {
console.log(`User just subscribed`, userSubscription);
});
await payments.requireSubscription();
// Unsubscribe the callback
unsubscribeCallback();