Skip to content

OneClick

Throughout the tutorial for card charge we showed how to do a charge by first creating a token (using Openpay.js) y luego enviarlo dentro de la petición de cargo. Esto es muy útil para cuando un cliente llega a nuestro sitio y solo deseamos realizarle el cargo en ese momento, pero cuando deseamos mantener los datos de la tarjeta, para que el cliente la pueda ocupar en múltiples ocasiones sin necesidad de volverla a introducir los datos, lo tenemos que hacer es guardar la tarjeta para posteriormente poder utilizarla sin necesidad de volverla a pedir al cliente. Los pasos para realizar esto son:
  1. Create a form to request the information
  2. Create a token
  3. Create a customer
  4. Create a customer card using the token
  5. 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).
<form action="/save_customer_card" method="POST" id="customer-form">
        <input type="hidden" name="token_id" id="token_id"/>
        <fieldset>
          <legend>Datos del cliente</legend>
        <p>
          <label>Name</label>
          <input type="text" size="20" autocomplete="on" name="client_name"/>
        </p>
        <p>
          <label>Correo Electrornico</label>
          <input type="text" size="20" autocomplete="on" name="cliente_email"/>
        </p>
        </fieldset>
        <fieldset>
          <legend>Datos de la tarjeta</legend>
        <p>
          <label>Name</label>
          <input type="text" size="20" autocomplete="off"
            data-openpay-card="holder_name" />
        </p>
        <p>
          <label>Número</label>
          <input type="text" size="20" autocomplete="off"
            data-openpay-card="card_number" />
        </p>
        <p>
          <label>CVV2</label>
          <input type="text" size="4" autocomplete="off"
            data-openpay-card="cvv2" />
        </p>
        <p>
          <label>Fecha de expiraciorn (MM/YY)</label>
          <input type="text" size="2" data-openpay-card="expiration_month" /> /
          <input type="text" size="2" data-openpay-card="expiration_year" />
        </p>
        </fieldset>
        <input type="submit" id="save-button" value="Pagar"/>
</form>
It’s very important that the fields used to enter the card information have the data_openpay_card ​ya que esto permitirá a la librería de Openpay encontrar la información. Observa que para los datos de la tarjeta no se está ocupando el atributo 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. Primero agregamos al head and Openpay.js files to the head:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://js.openpay.mx/openpay.v1.min.js"></script>
Now let’s set the merchant-id and thepublic-key):
<script type="text/javascript">
     $(document).ready(function() {
            OpenPay.setId('mzdtln0bmtms6o3kck8f');
            OpenPay.setApiKey('pk_f0660ad5a39f4912872e24a7a660370c');
            OpenPay.setSandboxMode(true);
    });
</script>
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.
$('#save-button').on('click', function(event) {
       event.preventDefault();
       $("#save-button").prop( "disabled", true);
       OpenPay.token.extractFormAndCreate('customer-form', success_callbak, error_callbak);
});
Como puedes ver estamos pasando como parámetro el nombre del formulario creado, esto para que la librería obtengan los datos de la tarjeta y haga la petición a Openpay. Si todo sale bien se llamará el método success_callback will be called to set the token id value token_id and the data will be sent to the server:
var success_callbak = function(response) {
              var token_id = response.data.id;
              $('#token_id').val(token_id);
              $('#customer-form').submit();
};
If there is a problem in the request, an alert will show the error:
var error_callbak = function(response) {
     var desc = response.data.description != undefined ? response.data.description : response.message;
     alert("ERROR [" + response.status + "] " + desc);
     $("#save-button").prop("disabled", false);
};

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:

$openpay = Openpay::getInstance('mzdtln0bmtms6o3kck8f', 'sk_e568c42a6c384b7ab02cd47d2e407cab');

$customerData = array(
    'name' => $_POST["client_name"],
    'email' => $_POST["cliente_email"],
    'requires_account' => false);

$customer = $openpay->customers->add($customerData);
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.

$cardData = array(
  'token_id' => $_POST["token_id"]
  'device_session_id' => $_POST["device_session_id"]
  );

$card = $customer->cards->add($cardData);
El objeto card contiene un id, el cual debes guardar en tu servidor ya con el podrás hacer cargos a esa tarjeta después. Puedes consultar la referencia de Create Card with a Token para mas información. ​ Notes: You can simulate different results using the cards Testing