Para esta guía vamos a ver como crear una suscripción para cobrar un servicio a un cliente de manera periódica.
Digamos que tienes un servicio en el cual ofreces 1 mes de prueba y después cobras una renta mensual de $99.99 pesos indefinidamente (o hasta que tu cliente cancele el servicio).
Para ello vamos a hacer lo siguiente:

Now let’s set the
The parameters for this method are:
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.
Response:
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.
Response example
Response:
Ready, we have created the subscription, which will be automatically charged each month for $ 99.99 after trial period.
Notes:
- 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
Un plan es un plantilla para una suscripción que contiene el costo, frecuencia de cobro, número de días de prueba, etc. Para crear un plan tenemos dos opciones: Option 1.- Creation from the API<?
$openpay = Openpay::getInstance('mzdtln0bmtms6o3kck8f', 'sk_e568c42a6c384b7ab02cd47d2e407cab');
$planDataRequest = array(
'amount' => 150.00,
'status_after_retry' => 'cancelled',
'retry_times' => 2,
'name' => 'Plan Curso Verano',
'repeat_unit' => 'month',
'trial_days' => '30',
'repeat_every' => '1',
'currency' => 'MXN');
$plan = $openpay->plans->add($planDataRequest);
?>
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
Response:
{
"name":"Servicio de TV",
"status":"active",
"amount":99.99,
"currency":"MXN",
"id":"psjubnktzpofhakixfkp",
"creation_date":"2014-02-14T13:47:55-06:00",
"repeat_every":1,
"repeat_unit":"month",
"retry_times":2,
"status_after_retry":"cancelled",
"trial_days":30
}
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:
Card tokenization
To tokenize a customer card using the library Openpay.js. Primero agregamos alhead
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>
merchant-id
and thepublic-key
):
<script type="text/javascript">
$(document).ready(function() {
OpenPay.setId('mzdtln0bmtms6o3kck8f');
OpenPay.setApiKey('pk_f0660ad5a39f4912872e24a7a660370c');
OpenPay.setSandboxMode(true);
});
</script>
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.OpenPay.token.create(CREATE_PARAMETERS_OBJECT, SUCCESS_CALLBACK, ERROR_CALLBACK);
- Parameter
CREATE_PARAMETERS_OBJECT
is a Javascript object containing the card information. - Parameter
SUCCESS_CALLBACK
defines the function to be called if the operation was successful. - Parameter
ERROR_CALLBACK
defines the function to be called if the operation failed.
OpenPay.token.create({
"card_number":"4111111111111111",
"holder_name":"Juan Perez Ramirez",
"expiration_year":"20",
"expiration_month":"12",
"cvv2":"110",
"address":{
"city":"Querétaro",
"line3":"Queretaro",
"postal_code":"76900",
"line1":"Av 5 de Febrero",
"line2":"Roble 207",
"state":"Queretaro",
"country_code":"MX"
}
}, onSuccess, onError);
For further reference on the use of the library, see the Openpay.js
Create customer
Now we’ll create the customer we want to subscribe:<?
$openpay = Openpay::getInstance('mzdtln0bmtms6o3kck8f', 'sk_e568c42a6c384b7ab02cd47d2e407cab');
$customerData = array(
'name' => 'Mi cliente uno',
'email' => 'micliente@gmail.com'
)
);
$customer = $openpay->customers->add($customerData);
?>
{
"id":"axapgwwolofnckfui2wx",
"name":"Mi cliente uno",
"last_name":null,
"email":"micliente@gmail.com",
"phone_number":null,
"status":"active",
"balance":0,
"clabe":"646180109400138692",
"address":null,
"creation_date":"2014-02-14T12:30:09-06:00"
}
Asociación del token de tarjeta al cliente
Now this only requires to use thetoken_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);
?>
{
"type":"credit",
"brand":"visa",
"id":"kso4st83wxaibffyt6su",
"card_number":"424242XXXXXX4242",
"holder_name":"Juan Perez Ramirez",
"expiration_year":"15",
"expiration_month":"12",
"allows_charges":true,
"allows_payouts":false,
"creation_date":"2014-02-12T10:57:09-06:00",
"bank_name":"BANCOMER",
"bank_code":"012",
"customer_id":"a2b79p8xmzeyvmolqfja"
}
Notes: You can simulate different results using the cards Testing
Subscribe customer
Finally we create the subscription with the planid
de plan (psjubnktzpofhakixfkp), the customer id
del cliente (axapgwwolofnckfui2wx) and id
de tarjeta (kokzmiiwephcdmq1h2qr), con lo cual la petición quedaría así:
<?
$openpay = Openpay::getInstance('mzdtln0bmtms6o3kck8f', 'sk_e568c42a6c384b7ab02cd47d2e407cab');
$subscriptionDataRequest = array(
"trial_end_date" => "2014-01-01",
'plan_id' => 'psjubnktzpofhakixfkp',
'card_id' => 'kokzmiiwephcdmq1h2qr');
$customer = $openpay->customers->get('axapgwwolofnckfui2wx');
$subscription = $customer->subscriptions->add($subscriptionDataRequest);
?>
{
"status":"trial",
"card":{
"type":"debit",
"brand":"visa",
"address":null,
"id":"kokzmiiwephcdmq1h2qr",
"card_number":"1111",
"holder_name":"Mi cliente uno",
"expiration_year":"20",
"expiration_month":"12",
"allows_charges":true,
"allows_payouts":true,
"creation_date":"2014-02-14T13:42:25-06:00",
"bank_name":"Banamex",
"customer_id":"axapgwwolofnckfui2wx",
"bank_code":"002"
},
"id":"sfquvei5ya0lwdrd5blo",
"cancel_at_period_end":false,
"charge_date":"2014-03-15",
"creation_date":"2014-02-14T13:48:59-06:00",
"current_period_number":0,
"period_end_date":"2014-03-14",
"trial_end_date":"2014-03-14",
"plan_id":"psjubnktzpofhakixfkp",
"customer_id":"axapgwwolofnckfui2wx"
}
- You can simulate different results using the cards Testing
- Implement the Notifications to know the status of payments in real time