For this tutorial we will see how to create a subscription to charge periodically a service to a customer.
Say you have a service where you offer a one month trial and then you charge a monthly fee of $ 99.99 pesos indefinitely (or until your customer cancels the service).
You have to do the following:
- Create a plan
- Create a token of debit or credit card using Openpay.js
- Create customer
- Card token association with customer
- Subscribe customer
Create a plan
A plan is a template for a subscription that contains the cost, charge frequency, trial period, etc.
To create a plan we have two options:
Option 1.- Creation from the API
You can have as many plans as you want. For example you can have a Gold, Platinum and Bronze plan for different levels of service.
If the request is successful we will have a response that contains the
id of the plan
For more information about the plan parameters go to "Add Plan"
Option 2.- Creation from the dashboard
You can also create plans from the dashboard in Planes -> Agregar:
To tokenize a customer card using the library Openpay.js.
First add the
head and Openpay.js files to the head:
Now let’s set the
merchant-id and the
public-key to the Openpay library:
Card token creation
Once you have installed and you set up the library, you’ll need to call the OpenPay.token.create () method in order to create a token.
The parameters for this method are:
SUCCESS_CALLBACK defines the function to be called if the operation was successful.
ERROR_CALLBACK defines the function to be called if the operation failed.
Example of creating a token:
The method returns an object type token with an id which you’ll need later. You’ll find the definition of the token object here.
For further reference on the use of the library, see the Openpay.js
Now we’ll create the customer we want to subscribe:
Customer card token association
Now this only requires to use the
token_id that comes with the request to save and assign the card to the customer.
The card object has an id which has to be saved in your server in order to make future charges to that card. For more information go to Create Card with a Token.
"holder_name":"Juan Perez Ramirez",
Notes: You can simulate different results using the cards Testing
Finally we create the subscription with the plan
id (psjubnktzpofhakixfkp), the customer
id (axapgwwolofnckfui2wx) and
id de tarjeta (kokzmiiwephcdmq1h2qr), con lo cual la petición quedaría así:
Ready, we have created the subscription, which will be automatically charged each month for $ 99.99 after trial period.
- You can simulate different results using the cards Testing
- Implement the Notifications to know the status of payments in real time