Conekta Developer's Hub

Bienvenido al Conekta Developer's Hub. Aquí encontrarás la más robusta documentación del API Conekta y todos los tutoriales que te ayudarán a comenzar a recibir pagos de la manera más rápida, sencilla y segura.

Checkout

Utiliza el checkout de conekta e incrustarlo en tu sitio.

📘

Primeros pasos

  • Instalar e incluir alguna de nuestras SDKs en tu proyecto.
  • Utilizar tu propia llave privada. Si no la conoces, puedes obtenerla aquí.

Paso 1 - Crea un "customer"

curl -H "Accept: application/vnd.conekta-v2.0.0+json" \
     -H "Content-type: application/json" \
     -u key_XXXXXXXXXXXX: \
     -X POST -d '{
    "name": "Juan Perez",
    "email": "[email protected]"
}' https://api.conekta.io/customers
<?php 
//Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API.
require_once("/path/to/lib/Conekta.php");
\Conekta\Conekta::setApiKey("key_eYvWV7gSDkNYXsmr");
\Conekta\Conekta::setApiVersion("2.0.0");

$validCustomer = [
  'name' => "Payment Link Name",
  'email' => "Juan Perez"
];
$customer = Customer::create($validCustomer);
# Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API
import conekta
conekta.api_key = "key_eYvWV7gSDkNYXsmr"
conekta.api_version = "2.0.0"

# Para los siguientes pasos en la integración un token_id de prueba se provee. 
# Para tener acceso al token que se generó en el paso 1.0 → es necesario accesarlo en el objeto conektaSuccessResponseHandler["id"] 
# Generación del cliente y la información de pago.
try:
    customer = conekta.Customer.create({
        'name': 'Fulanito Pérez',
        'email': '[email protected]',
        'phone': '5555555555'
    })
except conekta.ConektaError as e:
    print(e.message)
# Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API
require "conekta"
Conekta.api_key = "key_eYvWV7gSDkNYXsmr" # <-- Mock private key, please use YOUR personal private key
Conekta.api_version = "2.0.0"

valid_customer = {
  name: "Payment Link Name",
  email: "[email protected]"
}
customer = Conekta::Customer.create(valid_customer)
//Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API.
var conekta = require('conekta');
conekta.api_key = 'key_eYvWV7gSDkNYXsmr'; //  <-- Mock private key, please use YOUR personal private key
conekta.api_version = '2.0.0';

let customer = conekta.Customer.create({
    name: "Payment Link Name",
    email: "[email protected]"
  }, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });
using Newtonsoft.Json;
using conekta;
conekta.Api.apiKey = "key_eYvWV7gSDkNYXsmr";
conekta.Api.version = "2.0.0";

var validCustomer = new 
  {
    name = "Payment Link Name",
    email = "[email protected]"
  };

var customer = new Customer().create(validCustomer);
import (
    "fmt"
    conekta "github.com/conekta/conekta-go"
    "github.com/conekta/conekta-go/customer"
)

conekta.APIKey = "key_pMcnDF4zFyWKyLG15LuqwA"

customerParams := &conekta.CustomerParams{
    Name: "Payment Link Name",
    Email: "[email protected]",
}

customerResponse, err := customer.Create(customerParams)
//Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API.
Conekta.setApiKey("key_eYvWV7gSDkNYXsmr"); //  <-- Mock private key, please use YOUR personal private key
com.conekta.Conekta.apiVersion = "2.0.0"
  
  Customer customer = Customer.create(
    new JSONObject("{"
      + "'name': 'Fulanito Pérez', "
      + "'email': '[email protected]'"
      + "}"
    )
  );

Esto regresa una respuesta como la siguiente:

{
    "livemode": false,
    "name": "Vicente Mendoza",
    "email": "[email protected]",
    "id": "cus_2neG7CYEdeda9BBGU",
    "object": "customer",
    "created_at": 1588684774,
    "corporate": false,
    "custom_reference": ""
}
<?php

echo $customer->livemode;
echo $customer->name;
echo $customer->email;
echo $customer->id;
echo $customer->object;
print(customer.livemode);
print(customer.name);
print(customer.email);
print(customer.id);
puts customer.livemode
puts customer.name
puts customer.email
puts customer.id
puts customer.object
console.log(customer.livemode);
console.log(customer.name);
console.log(customer.email);
console.log(customer.id);
Console.WriteLine(customer.livemode);
Console.WriteLine(customer.name);
Console.WriteLine(customer.email);
Console.WriteLine(customer.id);
Console.WriteLine(customer._object);
fmt.Println("Livemode: %v\n", customerResponse.Livemode)
fmt.Println("Name: %v\n", customerResponse.Name)
fmt.Println("Email: %v\n", customerResponse.Email)
fmt.Println("ID: %v\n", customerResponse.ID)
System.out.println(customer.livemode);
System.out.println(customer.name);
System.out.println(customer.email);
System.out.println(customer.id);

Paso 2 - Crear una orden vacía con opciones de checkout

El siguiente snippet incorpora todas las partes del paso 1. Copia y pega el siguiente fragmento de código en tu sandbox y corre el código para crear una orden y un checkout object al mismo tiempo.

curl -H "Accept: application/vnd.conekta-v2.0.0+json" \
     -H "Content-type: application/json" \
     -u key_XXXXXXXXXXX: \
     -X POST -d '{
        "currency": "MXN",
        "customer_info": {
           "customer_id": "cus_2nHprwaWFn7QJ21Lj"
        },
       "line_items": [{
           "name": "Box of Cohiba S1s",
           "unit_price": 35000,
           "quantity": 1
       }],
       "shipping_lines": [{
           "amount": 0
       }],
       "checkout": {
           "allowed_payment_methods": ["cash", "card", "bank_transfer"],
           "monthly_installments_enabled": true,
           "monthly_installments_options": [3, 6, 9, 12]
        },
       "shipping_contact": {
          "phone": "+5215555555555",
          "receiver": "Marvin Fuller",
          "address": {
            "street1": "Nuevo Leon 4",
            "country": "MX",
            "postal_code": "06100"
          }
       }
}' https://api.conekta.io/orders
<?php

$validOrderWithCheckout = array(
  'line_items'=> array(
    array(
      'name'=> 'Box of Cohiba S1s',
      'description'=> 'Imported From Mex.',
      'unit_price'=> 120000,
      'quantity'=> 1,
      'sku'=> 'cohbs1',
      'category'=> 'food',
      'tags' => array('food', 'mexican food')
    )
  ),
  'checkout' => array(
    'allowed_payment_methods' => array("cash", "card", "bank_transfer"),
    'monthly_installments_enabled' => true,
    'monthly_installments_options' => array(3, 6, 9, 12)
  ),
  'customer_info' => array(
    'customer_id'   =>  'cus_2nHprwaWFn7QJ21Lj'
  ),
  'currency'    => 'mxn',
  'metadata'    => array('test' => 'extra info')
);
$order = Order::create($validOrderWithCheckout);
valid_order_with_checkout = {
   line_items: [
       {
           name: 'Box of Cohiba S1s',
           description: 'Imported From Mex.',
           unit_price: 120000,
           quantity: 1,
           sku: 'cohbs1',
           category: 'food',
           tags: ['food', 'mexican food']
       }
   ],
   checkout: {
       allowed_payment_methods: ["cash", "card", "bank_transfer"],
       monthly_installments_enabled: true,
       monthly_installments_options: [3, 6, 9, 12]
   },
   customer_info: {
       customer_id: 'cus_2nHprwaWFn7QJ21Lj'
   },
   currency: 'mxn',
   metadata: {test: 'extra info'}
}
order = Conekta::Order.create(valid_order_with_checkout)
puts order.inspect
checkout_order_object = {
       "currency": "MXN",
       "customer_info": {
          "customer_id": "cus_2o3FvMEBiKitVK1vQ"
       },
      "line_items": [{
          "name": "Box of Cohiba S1s",
          "unit_price": 300000,
          "quantity": 1
      }],
      "shipping_lines": [{
          "amount": 0
      }],
      "checkout": {
          "allowed_payment_methods": ["cash", "card", "bank_transfer"],
          "force_3ds_flow": False,
          "monthly_installments_enabled": False,
          "monthly_installments_options": [3,6,9,12,18],
          "expires_at": 1609891200
       },
      "shipping_contact": {
         "phone": "+5215555555555",
         "receiver": "Marvin Fuller",
         "address": {
           "street1": "Nuevo Leon 4",
           "country": "MX",
           "postal_code": "06100"
         }
      }
}
 
order = self.client.Order.create(order)
checkout = order.createCheckout(checkout_order_object)
let checkoutOrderObject = {
       "currency": "MXN",
       "customer_info": {
          "customer_id": "cus_2o3FvMEBiKitVK1vQ"
       },
      "line_items": [{
          "name": "Box of Cohiba S1s",
          "unit_price": 300000,
          "quantity": 1
      }],
      "checkout": {
          "allowed_payment_methods": ["cash", "card", "bank_transfer"],
          "force_3ds_flow": false,
          "monthly_installments_enabled": false,
          "monthly_installments_options": [3,6,9,12,18],
          "expires_at": 1609891200
       },
      "shipping_contact": {
         "phone": "5555555555",
         "receiver": "Marvin Fuller"
      }
};
 
 
conekta.Order.create(checkoutOrderObject, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });
using Newtonsoft.Json;

var validOrderWithCheckout = new
  {
    line_items = new 
      [
        new
        {
          name = "Box of Cohiba S1s",
          description = "Imported From Mex.",
          unit_price = 120000,
          quantity = 1,
          sku = "cohbs1",
          category = "food",
          tags = new string[] 
            { 
                "food", 
                "mexican food"
            }
        }
      ],
    checkout = new
      {
        type = "Integration",
        allowed_payment_methods = new string[] 
          {
            "cash", 
            "card", 
            "bank_transfer"
          },
        monthly_installments_enabled = true,
        monthly_installments_options = new int[]
          {
            3, 
            6, 
            9, 
            12
          }
      },
    customer_info = new 
      {
        customer_id = "cus_2oAokFrKM7CyVxGJm"
      },
    currency: "mxn",
    metadata: new 
      {
        test = "extra info"
      }
  };

var order = new Order()
  .create(JsonConvert.SerializeObject(validOrderWithCheckout));

Console.WriteLine(order.id);
orderParams := &conekta.OrderParams{
    Currency: "MXN",
    CustomerInfo: &CustomerParams{
        ID: customerResponse.ID,
    },
    LineItems: []*LineItemsParams{
        {
            Name:      "Box of Cohiba S1s",
            UnitPrice: 300000,
            Quantity:  1,
        },
    },
    Checkout: &OrderCheckoutParams{
    Force3dsFlow: false,
    MonthlyInstallmentsEnabled: false,
    MonthlyInstallmentsOptions: []int64{3, 6, 9, 12, 18},
        ExpiresAt:             time.Now().Unix() + int64(259200) + int64(rand.Float64()*3600),
        AllowedPaymentMethods: []string{"cash", "card", "bank_transfer"},
    }
}

orderResponse, err := order.Create(orderParams)
try {
  Order order = Order.create(
      new JSONObject("{ 'currency': 'mxn'," +
                        " 'customer_info': {" +
                        "   'customer_id': 'cus_2o3FvMEBiKitVK1vQ'" +
                        "  }," +
                        "  'line_items': [{" +
                        "    'name': 'Box of Cohiba S1s'," +
                        "    'unit_price': 300000," +
                        "    'quantity': 1," +
                        "  }]," +
                        "  'checkout': {" +
                        "    'allowed_payment_methods': ['cash','card','bank_transfer']," +
                        "    'force_3ds_flow': false," +
                        "    'monthly_installments_enabled': false," +
                        "    'monthly_installments_options': [3,6,9,12,18]" +
                        "    'expired_at': " + (System.currentTimeMillis() / 1000L) + 259200 + "," +
                        "  }," +
                        "  'shipping_contact': {" +
                        "    'phone': '5555555555'," +
                        "    'receiver': 'Marvin Fuller'" +
                        "  }" +
                        "}")
    );
} catch (Conekta::Error e) {
   System.out.println(e.details.get(0).message);
}

Esto regresa una respuesta como la siguiente:

{
    "livemode": false,
    "amount": 35000,
    "currency": "MXN",
    "payment_status": "paid",
    "amount_refunded": 0,
    "checkout": {
        "id": "42a4c95e-0db2-4ae8-9bb3-ea681acc8281",
        "object": "checkout",
        "status": "Issued",
        "allowed_payment_methods": ["cash", "card", "bank_transfer"],
        "needs_shipping_contact": true,
        "livemode": true
    },
    "customer_info": {
        "email": "[email protected]",
        "name": "Mario Perez",
        "corporate": false,
        "customer_id": "cus_2nHprwaWFn7QJ21Lj",
        "object": "customer_info"
    },
    "shipping_contact": {
        "receiver": "Marvin Fuller",
        "phone": "+5215555555555",
        "address": {
            "street1": "Nuevo Leon 4",
            "country": "mx",
            "residential": true,
            "object": "shipping_address",
            "postal_code": "06100"
        },
        "id": "ship_cont_2nYNo3xT815RRppom",
        "object": "shipping_contact",
        "created_at": 0
    },
    "object": "order",
    "id": "ord_2nYNo3xT815RRppon",
    "metadata": {},
    "created_at": 1587129536,
    "updated_at": 1587129537,
    "line_items": {
        "object": "list",
        "has_more": false,
        "total": 1,
        "data": [{
            "name": "Box of Cohiba S1s",
            "unit_price": 35000,
            "quantity": 1,
            "object": "line_item",
            "id": "line_item_2nYNo3xT815RRppoi",
            "parent_id": "ord_2nYNo3xT815RRppon",
            "metadata": {},
            "antifraud_info": {}
        }]
    },
    "shipping_lines": {
        "object": "list",
        "has_more": false,
        "total": 1,
        "data": [{
            "amount": 0,
            "object": "shipping_line",
            "id": "ship_lin_2nYNo3xT815RRppoj",
            "parent_id": "ord_2nYNo3xT815RRppon"
        }]
    }
}
<?php

print_r((array) $order->checkout->allowed_payment_methods); // array("cash", "card", "bank_transfer")
print_r($order->checkout->monthly_installments_enabled); // true
print_r((array) $order->checkout->monthly_installments_options); // array(3, 6, 9, 12)
print_r($order->checkout->object); // 'checkout'
print_r($order->checkout->type); // 'Integration'
puts order.checkout.allowed_payment_methods.inspect
puts order.checkout.monthly_installments_enabled
puts order.checkout.monthly_installments_options.inspect
puts order.checkout.object
puts order.checkout.type
print(order.checkout.allowed_payment_methods)
print(order.checkout.monthly_installments_enabled)
print(order.checkout.monthly_installments_options)
print(order.checkout.object)
print(order.checkout.type)
console.log(order.checkout.allowed_payment_methods)
console.log(order.checkout.monthly_installments_enabled)
console.log(order.checkout.monthly_installments_options)
console.log(order.checkout.object)
console.log(order.checkout.type)
Console.WriteLine(order.checkout.allowed_payment_methods.Length);
Console.WriteLine(order.checkout.monthly_installments_enabled);
Console.WriteLine(order.checkout.monthly_installments_options.Length);
Console.WriteLine(order.checkout._object);
Console.WriteLine(order.checkout.type);
fmt.Println("AllowedPaymentMethod: %v\n", orderResponse.Checkout.AllowedPaymentMethods)
fmt.Println("MonthlyInstallmentsEnabled: %v\n", orderResponse.Checkout.MonthlyInstallmentsEnabled)
fmt.Println("MonthlyInstallmentOptions: %v\n", orderResponse.Checkout.MonthlyInstallmentsOptions)
fmt.Println("Type: %v\n", orderResponse.Checkout.Type)
System.out.println(order.checkout.allowed_payment_methods);
System.out.println(order.checkout.monthly_installments_enabled);
System.out.println(order.checkout.monthly_installments_options);
System.out.println(order.checkout.object);
System.out.println(order.checkout.type);

Paso 3 - Inicializar el iframe

Incrustar el iframe en el checkout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Checkout</title>
    <script type="text/javascript" src="https://pay.conekta.com/v1.0/js/conekta-checkout.min.js"></script>
</head>
<body>
   <div id="conektaIframeContainer" style="height: 700px;"></div>
    <script type="text/javascript">
    window.ConektaCheckoutComponents.Integration({
        targetIFrame: "#conektaIframeContainer",
        checkoutRequestId: "42a4c95e-0db2-4ae8-9bb3-ea681acc8281, // checkout request id
        publicKey: "public_api_key_XXXXXXXX",
        options: {},
        styles: {},
        onFinalizePayment: function(event){
            console.log(event);
        }
    })
    </script>
</body>
</html>

Checkout Conekta

Paso 4 - Personalizar estilos

Puedes personalizar el aspecto visual en el Checkout para que mantenga la armonía con tu sitio.

Paso 5 - Meses sin intereses

Puedes configurar el checkout para que pueden funcionar con meses sin intereses si en las peticiones agregas estas dos variables: monthly_installments_enabled para activarlo y monthly_installments_options con los meses habilitados, Ej 3, 6, 9, 12, 18.

Paso 6 - Guardado de tarjetas

Si requiere que el checkout pueda permitir que las tarjetas sean guardadas por el usuario, bastará con habilitar on_demand_enabled al crear la orden en el paso 2. Con esto el usuario en sus posteriores compras no tendrá que volver a introducir su tarjeta.

Siga el siguiente ejemplo

curl -H "Accept: application/vnd.conekta-v2.0.0+json" \
     -H "Content-type: application/json" \
     -u key_XXXXXXXXXXX: \
     -X POST -d '{
        "currency": "MXN",
        "customer_info": {
           "customer_id": "cus_2nHprwaWFn7QJ21Lj"
        },
       "line_items": [{
           "name": "Box of Cohiba S1s",
           "unit_price": 35000,
           "quantity": 1
       }],
       "shipping_lines": [{
           "amount": 0
       }],
       "checkout": {
           "allowed_payment_methods": ["cash", "card", "bank_transfer"],
           "monthly_installments_enabled": true,
           "monthly_installments_options": [3, 6, 9, 12],
           "on_demand_enabled": true
        },
       "shipping_contact": {
          "phone": "+5215555555555",
          "receiver": "Marvin Fuller",
          "address": {
            "street1": "Nuevo Leon 4",
            "country": "MX",
            "postal_code": "06100"
          }
       }
}' https://api.conekta.io/orders
<?php

$validOrderWithCheckout = array(
  'line_items'=> array(
    array(
      'name'=> 'Box of Cohiba S1s',
      'description'=> 'Imported From Mex.',
      'unit_price'=> 120000,
      'quantity'=> 1,
      'sku'=> 'cohbs1',
      'category'=> 'food',
      'tags' => array('food', 'mexican food')
    )
  ),
  'checkout' => array(
    'allowed_payment_methods' => array("cash", "card", "bank_transfer"),
    'monthly_installments_enabled' => true,
    'monthly_installments_options' => array(3, 6, 9, 12)
    'on_demand_enabled' => true
  ),
  'customer_info' => array(
    'name' =>  'Juan Perez',
    'email' => '[email protected]',
    'phone' => '5566982090'
  ),
  'currency'    => 'mxn',
  'metadata'    => array('test' => 'extra info')
);
$order = Order::create($validOrderWithCheckout);
valid_order_with_checkout =
   {
       line_items: [
           {
               name: 'Box of Cohiba S1s',
               description: 'Imported From Mex.',
               unit_price: 120000,
               quantity: 1,
               sku: 'cohbs1',
               category: 'food',
               tags: ['food', 'mexican food']
           }
       ],
       checkout: {
           type: 'Integration',
           allowed_payment_methods: ["cash", "card", "bank_transfer"],
           monthly_installments_enabled: true,
           monthly_installments_options: [3, 6, 9, 12],
           on_demand_enabled: true
       },
       customer_info: {
           name:  'Juan Perez',
           email: '[email protected]',
           phone: '5566982090'
       },
       currency: 'mxn',
       metadata: {'test' => 'extra info'}
   }
order = Conekta::Order.create(valid_order_with_checkout)
validOrderWithCheckout =
   {
       line_items: [
           {
               name: 'Box of Cohiba S1s',
               description: 'Imported From Mex.',
               unit_price: 120000,
               quantity: 1,
               sku: 'cohbs1',
               category: 'food',
               tags: ['food', 'mexican food']
           }
       ],
       checkout: {
           type: 'Integration',
           allowed_payment_methods: ["cash", "card", "bank_transfer"],
           monthly_installments_enabled: true,
           monthly_installments_options: [3, 6, 9, 12],
           on_demand_enabled: true
       },
       customer_info: {
           name:  'Juan Perez',
           email: '[email protected]',
           phone: '5566982090'
       },
       currency: 'mxn',
       metadata: {'test' => 'extra info'}
   }

conekta.Order.create(validOrderWithCheckout, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });
using Newtonsoft.Json;

var validOrderWithCheckout = new
  {
    line_items = new 
      [
        new
        {
          name = "Box of Cohiba S1s",
          description = "Imported From Mex.",
          unit_price = 120000,
          quantity = 1,
          sku = "cohbs1",
          category = "food",
          tags = new string[] 
            { 
                "food", 
                "mexican food"
            }
        }
      ],
    checkout = new
      {
        type = "Integration",
        allowed_payment_methods = new string[] 
          {
            "cash", 
            "card", 
            "bank_transfer"
          },
        monthly_installments_enabled = true,
        monthly_installments_options = new int[]
          {
            3, 
            6, 
            9, 
            12
          }
      },
    customer_info = new 
      {
        customer_id = "cus_2oAokFrKM7CyVxGJm"
      },
    currency: "mxn",
    metadata: new 
      {
        test = "extra info"
      }
  };

var order = new Order()
  .create(JsonConvert.SerializeObject(validOrderWithCheckout));
orderParams := &conekta.OrderParams{
    Currency: "MXN",
    CustomerInfo: &CustomerParams{
        ID: customerResponse.ID,
    },
    LineItems: []*LineItemsParams{
        {
            Name:      "Box of Cohiba S1s",
            UnitPrice: 120000,
            Quantity:  1,
        },
    },
    Checkout: &OrderCheckoutParams{
    Type: "Integration",
    OnDemandEnabled: true,
    MonthlyInstallmentsEnabled: true,
    MonthlyInstallmentsOptions: []int64{3, 6, 9, 12},
        ExpiresAt:             time.Now().Unix() + int64(259200) + int64(rand.Float64()*3600),
        AllowedPaymentMethods: []string{"cash", "card", "bank_transfer"},
    }
}

orderResponse, err := order.Create(orderParams)
try {
  Order order = Order.create(
      new JSONObject("{ 'currency': 'mxn'," +
                        "  'checkout': {" +
                        "    'allowed_payment_methods': ['cash','card','bank_transfer']," +
                        "    'monthly_installments_enabled': false," +
                        "    'monthly_installments_options': [3,6,9,12,18]," +
                        "    'on_demand_enabled': true," +
                        "    'type': 'Integration'" +                                             "  }," +
                        " 'customer_info': {" +
                        "   'name':  'Juan Perez'," +
                        "   'email': '[email protected]'," +
                        "   'phone': '5566982090'" +
                        "  }," +
                        "  'line_items': [{" +
                        "    'name': 'Box of Cohiba S1s'," +
                        "    'unit_price': 300000," +
                        "    'quantity': 1" +
                        "  }]" +
                        "}")
    );
} catch (Conekta::Error e) {
   System.out.println(e.details.get(0).message);
}

En una primer compra el cliente vería una opción para guardar la tarjeta de la siguiente manera

Al realizarse la compra de manera exitosa la tarjeta es guardada y en una segunda compra el cliente podría pagar con la tarjeta guardada.

Paso 7 - Recibir la notificación de pago

Una vez configurado un webhook tu puedes recibir el evento charge.paid y order.paid cada que se reciba un pago exitoso.