This is very useful when a customer comes to our site and we just want to make a charge at that moment, but when we want to keep the card info, so that the client can use it multiple times without having to re-enter data, we have to save the card information. This tutorial will show you how to do it.
The steps to save the customer card info are:
- Create a form to request the information
- Create a token
- Create a customer
- Create a customer card using the token
- Create a charge using the token
Create a form to request the information
First create the form to request information from your customer (name and email) and card details (number, expiration date, etc).
It’s very important that the fields used to enter the card information have the
data_openpay_card attribute because this allows the Openpay library to find the information.
Note that the attribute
name isn’t being used to store the card information , this is because when you submit the form to your server the card info doesn’t travel in the request because it’s only used to create the token.
Create a token
Once we created our form, we will set up the send button to create a token using the 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:
And finally let’s catch the click event of the Save button, so instead of submitting the form it creates the token function of the card.
As you can see we are passing as a parameter the name of the form created, this is so the library gets the card information and makes the request to Openpay.
If everything works well, the method
success_callback will be called to set the token id value
token_id and the data will be sent to the server:
If there is a problem in the request, an alert will show the error:
For further reference on the use of the library, see the Openpay.js
Create a customer
When doing the implementation of the /save_customer_card implementation you have to do the following in order to create the customer:
Note: For this example, we create the customer using the requires_account = false flag which means that the account balance will not handle itself.
For more information about the types of clients see the customers tutorial
Create a customer card using the token
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.
Notes: You can simulate different results using the cards Testing