SecurionPay Subscriptions in Node Js
TL;DR Setup a repeating subscription for a customer using Securion Pay in Node Js with their NPM package.
Final code is here
I am in no way affiliated with Securion Pay, I implemented it in a project.
Project setup
Create a Securion Pay account and use the Secret Key from the API keys
I’m using
- Node Js 8.9.4
- Securionpay npm package 1.0.0
const securionpay = require(‘securionpay’)(process.env.SECURIONPAY_API_KEY);
Create plan
Setup a plan to define the subscription charging details (eg name, amount, interval). Save the returned Plan Id as it is required for creating subscriptions.
async createPlan() {
return await securionpay.plans.create({
amount: 2000,
currency: ‘GBP’,
interval: ‘month’,
name: ‘my first plan’
}).then(result => {
console.log(result);
return result;
});
}
Create Customer
Create a customer to which the subscription will be associated. The Customer Id from the returned values could be saved against the user in your own users repository as it is required when creating a subscription.
async createCustomer() {
return await securionpay.customers.create({
email: ‘user@example.com’,
description: ‘User description’
}).then(result => {
console.log(result);
return result;
});
}
Add payment card
Add a payment card for the customer as a subscription cannot be created for a customer that does not have an active card. (TODO: Check PCI compliance regarding the card details you store)
async createCard(customer) {
return await securionpay.cards.create(customer.id, {
number: ‘4242424242424242’,
expMonth: ‘12’,
expYear: ‘2020’,
cvc: ‘123’,
cardholderName: ‘John Smith’
}).then(result => {
console.log(result);
});
}
Create subscription
Create the subscription by supplying the Customer id and Plan id
async subscribeToPlan(customer, plan) {
await securionpay.subscriptions.create(customer.id, {
'planId': plan.id
}).then(result => {
console.log(result);
});
}
Wire it up
Add the methods above to a class called `SecurionPayService` and run the following. Check in your Securion Pay dashboard for the new records after running the method.
const go = async () => {
const payService = new SecurionPayService();
const plan = await payService.createPlan();
const customer = await payService.createCustomer();
await payService.createCard(customer);
await payService.subscribeToPlan(customer, plan);
}go();
Payments — Web hooks
Create services to listen to events such as subscription payments and charge statuses — i hope to cover this in a future post.
Links
The Securion Pay documentation is pretty good