Throughout the tutorial for card charge we showed how to do a charge by first creating a token (using Openpay.js) and then send it in the charge request.
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.
First create the form to request information from your customer (name and email) and card details (number, expiration date, etc).
It is very important that the fields where they will enter the card information have the data_openpay_card attribute as this will allow 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 library.
First add the head and Openpay.js files to the head:
Now let’s set the code>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 the name of the form created as a parameter, 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 and the data will be send to the server:
If there is a problem in the request, an alert will show the error:
For more reference about the library please go to the Openpay.js section.
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
Save the card to the customer 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:
The full HTML code is here. (The page does not work completely, you must download and make the save_customer_card page implementation on your server ).
You can simulate different results using the test cards