Subscriptions

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:

  1. Create a plan
  2. Create a token of debit or credit card using Openpay.js
  3. Create customer
  4. Card token association with customer
  5. 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

<?
$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:

Agregar plan

Card tokenization

To tokenize a customer card using the library Openpay.js.

First add the 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 the public-key to the Openpay library:

<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);

The parameters for this method are:

  • 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.

Example of creating a token:

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);

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

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);
?>

Response:

{
   "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 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. ​

Response example

{
   "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 plan id (psjubnktzpofhakixfkp), the customer id (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);
?>

Response:

{
   "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"
}

Ready, we have created the subscription, which will be automatically charged each month for $ 99.99 after trial period.

Notes:

  • You can simulate different results using the cards Testing
  • Implement the Notifications to know the status of payments in real time