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.

Cargo por solicitud

Tokenizar (cifrar) la información la tarjeta

Por motivos de seguridad, se requiere tokenizar la información sensible de la tarjeta en el frontend de tu sitio.

📘

Primeros pasos

Paso 1 - Añade la librería de ConektaJS a tu sitio

  • Para fines prácticos usamos jQuery en este tutorial.
  • Nuestra librería de frontend ConektaJS sólo tokeniza las tarjetas.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.conekta.io/js/latest/conekta.js"></script>

📘

Recuerda que...

Si estás construyendo una app, en lugar de ConektaJS usarás los SDKs de Android, iOS o Xamarin.

Objetos que regresa ConektaJS

  • Objeto token: es el objeto que regresamos en caso de éxito.
  • Objeto error: es el objeto que regresamos en caso de que algo haya salido mal.
// Token
{
  "id": "tok_a4Ff0dD2xYZZq82d9",
  "object": "token",
  "used": false,
  "livemode": true
}


// Error
{
  "type": "parameter_validation_error",
  "message": "Something went wrong on Conekta's end",
  "message_to_purchaser": "Your code could not be processed, please try again later",
  "error_code": "invalid_expiry_month",
  "param": "card[exp_month]"
}

Paso 1.1 - Añade tu script de tokenización

Definiciones

  • Conekta.setPublicKey() añade tu llave pública para permitir la tokenización de tarjetas.
  • conektaSuccessResponseHandler regresa un objeto token cuando la petición fue exitosa.
  • conektaErrorResponseHandler regresa un objeto error cuando la petición tuvo algún detalle.
  • Conekta.Token.create() envía la información a nuestro servidor.

El token sólo puede ser utilizado una vez y tiene un tiempo de expiración de una hora.

<script type="text/javascript" >
  Conekta.setPublicKey('key_KJysdbf6PotS2ut2');


  var conektaSuccessResponseHandler = function(token) {
    var $form = $("#card-form");
    //Inserta el token_id en la forma para que se envíe al servidor
     $form.append($('<input type="hidden" name="conektaTokenId" id="conektaTokenId">').val(token.id));
    $form.get(0).submit(); //Hace submit
  };
  var conektaErrorResponseHandler = function(response) {
    var $form = $("#card-form");
    $form.find(".card-errors").text(response.message_to_purchaser);
    $form.find("button").prop("disabled", false);
  };


  //jQuery para que genere el token después de dar click en submit
  $(function () {
    $("#card-form").submit(function(event) {
      var $form = $(this);
      // Previene hacer submit más de una vez
      $form.find("button").prop("disabled", true);
      Conekta.Token.create($form, conektaSuccessResponseHandler, conektaErrorResponseHandler);
      return false;
    });
  });
</script>

Paso 1.2 - Añade el formulario de la tarjeta a tu sitio

ConektaJS recopila la información de la tarjeta usando data-attributes pero si lo deseas puedes crear un objeto token.

<form action="" method="POST" id="card-form">
  <span class="card-errors"></span>
  <div>
    <label>
      <span>Nombre del tarjetahabiente</span>
      <input type="text" size="20" data-conekta="card[name]">
    </label>
  </div>
  <div>
    <label>
      <span>Número de tarjeta de crédito</span>
      <input type="text" size="20" data-conekta="card[number]">
    </label>
  </div>
  <div>
    <label>
      <span>CVC</span>
      <input type="text" size="4" data-conekta="card[cvc]">
    </label>
  </div>
  <div>
    <label>
      <span>Fecha de expiración (MM/AAAA)</span>
      <input type="text" size="2" data-conekta="card[exp_month]">
    </label>
    <span>/</span>
    <input type="text" size="4" data-conekta="card[exp_year]">
  </div>
  <button type="submit">Crear token</button>
</form>

Paso 2 - Integración completa del paso 2, fragmento de código

El siguiente snippet incorpora todas las partes del paso 2. Copia y pega el siguiente fragmento de código en tu sandbox y corre el código para crear a un cliente, agregar información de pago y hacer una orden.

Para más información sobre las diferentes partes del snippet favor de seguir el resto del tutorial.

# Generación del cliente y la información de pago.
curl --request POST \
  --url https://api.conekta.io/customers \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
  "name": "Fulanito Pérez",
  "email": "[email protected]",
  "phone": "+52181818181",
  "metadata": {"reference": "12987324097", "random_key": "random value"},
  "payment_sources": [{
    "type": "card",
    "token_id": "tok_test_visa_4242"
  }]
}'


# Implementación de una orden.
curl --request POST \
  --url https://api.conekta.io/orders \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
      "line_items": [{
          "name": "Tacos",
          "unit_price": 1000,
          "quantity": 120
      }],
      "shipping_lines": [{
          "amount": 1500,
          "carrier": "FEDEX"
      }],
      "currency": "MXN",
      "customer_info": {
          "customer_id": "cus_2fkJPFjQKABcmiZWz"
      },
      "shipping_contact":{
           "address": {
               "street1": "Calle 123, int 2",
               "postal_code": "06100",
               "country": "MX"
           }
       },
     "metadata": {"reference": "12987324097", "more_info": "lalalalala"},
      "charges":[{
          "payment_method": {
              "type": "default"
          }
      }]
  }'


# Si la orden fue exitosa la respuesta debería imprimir lo siguiente:
# Respuesta:
# ID: ord_2fsQdMUmsFNP2WjqS
# $ 1215.0 MXN
# Order
# 120 - Tacos - $10.0
# Payment info
# CODE: 035315
# Card info: 4242 - visa - banco - credit
//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");


//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" => "+52181818181",
      "metadata" => ["reference" => "12987324097", "random_key" => "random value"],
      "payment_sources" => [
        [
          "type" => "card",
          "token_id" => "tok_test_visa_4242"
        ]
      ]//payment_sources
    ]//customer
  );
} catch (\Conekta\ProccessingError $error){
  echo $error->getMesage();
} catch (\Conekta\ParameterValidationError $error){
  echo $error->getMessage();
} catch (\Conekta\Handler $error){
  echo $error->getMessage();
}


//Implementación de una orden.
try{
  $order = \Conekta\Order::create(
    [
      "line_items" => [
        [
          "name" => "Tacos",
          "unit_price" => 1000,
          "quantity" => 120
        ]
      ],
      "shipping_lines" => [
        [
          "amount" => 1500,
           "carrier" => "FEDEX"
        ]
      ], //shipping_lines - physical goods only
      "currency" => "MXN",
      "customer_info" => [
        "customer_id" => "cus_2fkJPFjQKABcmiZWz"
      ],
      "shipping_contact" => [
        "address" => [
          "street1" => "Calle 123, int 2",
          "postal_code" => "06100",
          "country" => "MX"
        ]
      ], //shipping_contact - required only for physical goods
      "metadata" => ["reference" => "12987324097", "more_info" => "lalalalala"],
      "charges" => [
        [
          "payment_method" => [
            "type" => "default"
           ] //payment_method - use customer's default - a card
             //to charge a card, different from the default,
             //you can indicate the card's source_id as shown in the Retry Card Section
        ]
      ]
    ]
  );
} catch (\Conekta\ProcessingError $error){
  echo $error->getMessage();
} catch (\Conekta\ParameterValidationError $error){
  echo $error->getMessage();
} catch (\Conekta\Handler $error){
  echo $error->getMessage();
} echo "ID: ". $order->id;
echo "Status: ". $order->payment_status;
echo "$". $order->amount/100 . $order->currency;
echo "Order";
echo $order->line_items[0]->quantity .
      "-". $order->line_items[0]->name .
      "- $". $order->line_items[0]->unit_price/100;
echo "Payment info";
echo "CODE:". $order->charges[0]->payment_method->auth_code;
echo "Card info:".
      "- ". $order->charges[0]->payment_method->name .
      "- ". $order->charges[0]->payment_method->last4 .
      "- ". $order->charges[0]->payment_method->brand .
      "- ". $order->charges[0]->payment_method->type;


// Si la orden fue exitosa la respuesta debería imprimir lo siguiente:
// Respuesta:
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
# 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"


# 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.
customer = Conekta::Customer.create({
  name: 'Fulanito Pérez',
  email: '[email protected]',
  phone: '+52181818181',
  metadata: {"reference" => "12987324097", "random_key" => "random value"},
  payment_sources: [{
    type: 'card',
    token_id: 'tok_test_visa_4242'
  }]
})


# Implementación de una orden.
begin
  order = Conekta::Order.create({
    line_items: [{
        name: "Tacos",
        unit_price: 1000,
        quantity: 120
    }],
    shipping_lines: [{
        amount: 1500,
        carrier: "FEDEX"
    }], #shipping_lines - physical goods only
    currency: "MXN",
    customer_info: {
        customer_id: "cus_2fkJPFjQKABcmiZWz"
    },
    shipping_contact: {
        address: {
            street1: "Calle 123, int 2",
            postal_code: "06100",
            country: "MX"
        }
    }, #shipping_contact - required only for physical goods
    charges: [{
        payment_method: {
            type: "default"
        } #payment_method - use the customer's default - a card
          #to charge a card, different from the default,
          #you can indicate the card's source_id as shown in the Retry Card Section
    }],
    metadata: {"reference" => "12987324097", "more_info" => "lalalalala"}
  })
rescue Conekta::Error => error
  for error_detail in error.details do
    puts error_detail.message
  end
end


# Si la orden fue exitosa la respuesta debería imprimir lo siguiente:
puts "ID: #{order.id}"
puts "Status: #{order.payment_status}"
puts "$ #{(order.amount/100).to_f} #{order.currency}"
puts "Order"
puts "#{order.line_items[0].quantity}
      - #{order.line_items[0].name}
      - $ #{(order.line_items[0].unit_price/100).to_f}"
puts "Payment info"
puts "CODE: #{order.charges[0].payment_method.auth_code}"
puts "Card info:
      - #{order.charges[0].payment_method.name}
      - #{order.charges[0].payment_method.last4}
      - #{order.charges[0].payment_method.brand}
      - #{order.charges[0].payment_method.type}"


# Respuesta:
# ID: ord_2fsQdMUmsFNP2WjqS
# $ 1215.0 MXN
# Order
# 120 - Tacos - $10.0
# Payment info
# CODE: 035315
# Card info: 4242 - visa - banco - credit
# Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API
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.
    customer = conekta.Customer.create({
        'name': 'Fulanito Pérez',
        'email': '[email protected]',
        'phone': '+52181818181',
        'metadata': {'description': 'Compra de creditos: 300(MXN)', 'reference': '1334523452345'},
        'payment_sources': [{
            'type': 'card',
            'token_id': 'tok_test_visa_4242'
        }]
    })
except conekta.ConektaError as e:
    print(e.message)


# Implementación de una orden.
try:
    order = conekta.Order.create({
        "line_items": [{
            "name": "Tacos",
            "unit_price": 1000,
            "quantity": 120
        }],
        "shipping_lines": [{
            "amount": 1500,
            "carrier": "FEDEX"
        }],  # shipping_lines - physical goods only
        "currency": "MXN",
        "customer_info": {
            "customer_id": "cus_2fkJPFjQKABcmiZWz"
        },
        "shipping_contact": {
            "address": {
                "street1": "Calle 123, int 2",
                "postal_code": "06100",
                "country": "MX"
            }  # shipping_contact - required only for physical goods
        },
        "metadata": {"description": "Compra de creditos: 300(MXN)", "reference": "1334523452345"},
        "charges": [{
            "payment_method": {
                "type": "default"
            }  # payment_method - use the customer's default - a card
            # to charge a card, different from the default,
            # you can indicate the card's source_id as shown in the Retry Card Section
        }]
    })
    print("ID: " + order.id)
    print("Status: " + order.payment_status)
    print("$" + str((order.amount / 100)) + order.currency)
    print("Order")
    print(str(order.line_items[0].quantity) + " - "
          + order.line_items[0].name + " - "
          + str((order.line_items[0].unit_price / 100)))
    print("Payment info");
    print("Code: " + order.charges[0].payment_method.auth_code
    + order.charges[0].payment_method.name + " - "
    + order.charges[0].payment_method.last4 + " - "
    + order.charges[0].payment_method.brand + " - "
    + order.charges[0].payment_method.type)
except conekta.ConektaError as e:
    print(e.message)


# Si la orden fue exitosa la respuesta debería imprimir lo siguiente:
# Response
# ID: ord_2fsQdMUmsFNP2WjqS
# $ 1215.0 MXN
# Order
# 120 - Tacos - $10.0
# Payment info
# CODE: 035315
# Card info: 4242 - visa - banco - credit
//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';


//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.
customer = conekta.Customer.create({
    'name': 'Fulanito Pérez',
    'email': '[email protected]',
    'phone': '+52181818181',
    'metadata': { 'description': 'Compra de creditos: 300(MXN)', 'reference': '1334523452345' },
    'payment_sources': [{
      'type': 'card',
      'token_id': 'tok_test_visa_4242'
    }]
  }, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });


  //Implementación de una orden.
  order = conekta.Order.create({
    "line_items": [{
        "name": "Tacos",
        "unit_price": 1000,
        "quantity": 120
    }],
    "shipping_lines": [{
        "amount": 1500,
        "carrier": "FEDEX"
    }], //shipping_lines - physical goods only
    "currency": "MXN",
    "customer_info": {
     "customer_id": "cus_2fkJPFjQKABcmiZWz"
    },
    "shipping_contact":{
     "address": {
       "street1": "Calle 123, int 2",
       "postal_code": "06100",
       "country": "MX"
     }
   },  //shipping_contact - required only for physical goods
  "metadata": { "description": "Compra de creditos: 300(MXN)", "reference": "1334523452345" },
  "charges":[{
    "payment_method": {
      "type": "default"
    }  //payment_methods - use the customer's default - a card
       //to charge a card, different from the default,
       //you can indicate the card's source_id as shown in the Retry Card Section
  }]
}, function(err, res) {
    if(err){
      console.log(err);
      return;
    }
    // Si la orden fue exitosa la consola debería imprimir lo siguiente respuesta:
    console.log(res.toObject());
    console.log("ID: " + res.toObject().id);
    console.log("Status: " + res.toObject().payment_status);
    console.log("$" + (res.toObject().amount/100) + res.toObject().currency);
    console.log("Order");
    console.log(res.toObject().line_items.data[0].quantity + " - "
        + res.toObject().line_items.data[0].name + " - "
        + (res.toObject().line_items.data[0].unit_price/100));
    console.log("Payment info");
    console.log("Code: " + res.toObject().charges.data[0].payment_method.auth_code);
    console.log("Card info: "
          + res.toObject().charges.data[0].payment_method.name + " - "
          + res.toObject().charges.data[0].payment_method.last4 + " - "
          + res.toObject().charges.data[0].payment_method.brand + " - "
          + res.toObject().charges.data[0].payment_method.type);
});


//Respuesta:
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
//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"


//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 customer = Customer.create(
    new JSONObject("{"
      + "'name': 'Fulanito Pérez', "
      + "'email': '[email protected]',"
      + "'phone': '+52181818181',"
      + "'metadata': {'description': 'Compra de creditos: 300(MXN)' , 'reference' : '1334523452345'},"
      + "'payment_sources':[{"
        + "'type': 'card',"
        + "'token_id': 'tok_test_visa_4242'"
        + "}]"
      + "}"
    )
  );


//Implementación de una orden.
Order order = Order.create(
    new JSONObject("{"
      + "'line_items': [{"
          + "'name': 'Tacos',"
          + "'unit_price': 1000,"
          + "'quantity': 120"
      + "}]," //line_items
      + "'shipping_lines': [{"
          + "'amount': 1500,"
          + "'carrier': 'FEDEX'"
      + "}]," //shipping_lines - physical goods only
      + "'currency': 'MXN',"
      + "'customer_info': {"
        + "'customer_id': 'cus_2fkJPFjQKABcmiZWz'"
      + "}," //customer_info
      + "'shipping_contact':{"
         + "'address': {"
           + "'street1': 'Calle 123, int 2',"
           + "'postal_code': '06100',"
           + "'country': 'MX'"
         + "}"
       + "}," //shipping_contact - required only for physical goods 
       +"'metadata': {'description': 'Compra de creditos: 300(MXN)' , 'reference' : '1334523452345'},"
      + "'charges':[{"
        + "'payment_method': {"
          + "'type': 'default'"
        + "}" //payment_method - use the customer's default - a card
              //to charge a card, different from the default,
              //you can indicate the card's source_id as shown in the Retry Card Section
      + "}]" //charges
    + "}" //order
    )
  );


  LineItems line_item = (LineItems)order.line_items.get(0);
  Charge charge = (Charge) order.charges.get(0);
  PaymentMethod payment_method = (PaymentMethod) charge.payment_method;
  System.out.println("ID: " + order.id);
  System.out.println("Status: " + order.payment_status);
  System.out.println("$" + (order.amount/100) + order.currency);
  System.out.println("Order");
  System.out.println(line_item.quantity + " - "
                    + line_item.name + " - "
                    + (line_item.unit_price/100));
  System.out.println("Payment info");
  System.out.println("Code: " + payment_method.getVal("auth_code"));
  System.out.println("Card info: "
                    + payment_method.getVal("name") + " - "
                    + payment_method.getVal("last4") + " - "
                    + payment_method.getVal("brand") + " - "
                    + payment_method.getVal("type"));
}catch (Conekta::Error e) {
   System.out.println(e.details.get(0).message);
}


// Si la orden fue exitosa la consola debería imprimir lo siguiente respuesta:
// Respuesta:
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
//Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API.
using conekta;
conekta.Api.apiKey = "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 customer = Customer.create(
    new JSONObject("{"
      + "'name': 'Fulanito Pérez', "
      + "'email': '[email protected]',"
      + "'phone': '+52181818181',"
      + "'metadata': {'description': 'Compra de creditos: 300(MXN)' , 'reference' : '1334523452345'},"
      + "'payment_sources':[{"
        + "'type': 'card',"
        + "'token_id': 'tok_test_visa_4242'"
        + "}]"
      + "}"
    )
  );


//Implementación de una orden.
 conekta.Order order = new conekta.Order ().create(@"{
    ""line_items"": [{
        ""name"": ""Tacos"",
        ""unit_price"": 1000,
        ""quantity"": 120
    }],
    ""shipping_lines"": [{
        ""amount"": 1500,
        ""carrier"": ""FEDEX""
    }], //shipping_lines - physical goods only
    ""currency"": ""MXN"",
    ""customer_info"": {
      ""customer_id"": ""cus_2fkJPFjQKABcmiZWz""
    },
    ""shipping_contact"":{
       ""address"": {
         ""street1"": ""Calle 123, int 2"",
         ""postal_code"": ""06100"",
         ""country"": ""MX""
       }
     }, //shipping_contact - required only for physical goods 
    ""metadata"":{""description"" : ""Compra de creditos: 300(MXN)"", ""reference"" : ""1334523452345""},
    ""charges"":[{
      ""payment_method"": {
        ""type"": ""default""
      } //payment_method - use the customer's default - a card
        //to charge a card, different from the default,
        //you can indicate the card's source_id as shown in the Retry Card Section
    }]
  }");


  Console.WriteLine("ID: " + order.id);
  Console.WriteLine("Status: " + order.payment_status);
  Console.WriteLine("Amount: $" + (order.amount / 100) + order.currency);
  Console.WriteLine("Order:");
  LineItem line_item = (LineItem)order.line_items.at(0);
  Console.WriteLine(line_item.quantity + " - "
      + line_item.name + " - "
      + (line_item.unit_price / 100));
  Charge charge = (Charge)order.charges.at(0);
  Console.WriteLine("Code: " + charge.payment_method.auth_code);
  Console.WriteLine("Card info: "
      + charge.payment_method.name + " - "
      + charge.payment_method.last4 + " - "
      + charge.payment_method.brand + " - "
      + charge.payment_method.type);
} catch (ConektaException e) {
  foreach (JObject obj in e.details) {
    System.Console.WriteLine("\n [ERROR]:\n");
    System.Console.WriteLine("message:\t" + obj.GetValue("message"));
    System.Console.WriteLine("debug:\t" + obj.GetValue("debug_message"));
    System.Console.WriteLine("code:\t" + obj.GetValue("code"));
  }
}
// Si la orden fue exitosa la consola debería imprimir lo siguiente respuesta:
// Respuesta:
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
//Inicialización del cliente Conekta a través de la adición de la llave privada y versión del API.
import (
    conekta "github.com/conekta/conekta-go"
    "github.com/conekta/conekta-go/order"
    "github.com/conekta/conekta-go/customer"
    "fmt"
)

//Integración completa del paso 2, fragmento de código
conekta.APIKey = "key_pMcnDF4zFyWKyLG15LuqwA"

//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.
paymentSource := &conekta.PaymentSourceCreateParams{
    TokenID: "tok_test_visa_4242",
    PaymentType: "card",
}

addressParams := &conekta.Address{
    Street1: "Street1",
    Street2: "Street2",
    City: "City",
    State: "State",
    Country: "Country",
    PostalCode: "PostalCode",
}

shippingContact := &conekta.ShippingContactParams{
    Phone: "+5215555555555",
    Receiver: "Marvin Fuller",
    Address: addressParams,
}


customerParams := &conekta.CustomerParams{}
customerParams.Name = "fulanito Perez"
customerParams.Phone = "+5215555555555"
customerParams.Email = "[email protected]"
customerParams.PaymentSources = append(customerParams.PaymentSources, paymentSource)
customerParams.ShippingContacts = append(customerParams.ShippingContacts, shippingContact)

result, err := customer.Create(customerParams)

if err != nil {
    code := err.(conekta.Error).Details[0].Code
    fmt.Println(code)
} else {
    fmt.Println(result)
}


//Implementación de una orden.
Address := &conekta.Address{
    Street1: "Street1",
    Street2: "Street2",
    City: "City",
    State: "State",
    Country: "Country",
    PostalCode: "PostalCode",
}

customerParams := &conekta.CustomerParams{
    ID: "cus_2fkJPFjQKABcmiZWz",
}

lineItemParams := &conekta.LineItemsParams{
    Name: "Naranjas Robadas",
    UnitPrice: 10000,
    Quantity: 2,
}

shippingParams := &conekta.ShippingLinesParams{
    Amount: 200,
    TrackingNumber: "123",
    Carrier: "Test Carrier",
    Method: "method",
}

shippingContactParams := &conekta.ShippingContactParams{
    Phone: "55-5555-5555",
    Receiver: "Miguel",
    BetweenStreets: "BetweenStreets",
    Address: Address,
}


chargeParams := &conekta.ChargeParams{
    PaymentMethod: &conekta.PaymentMethodParams{
        Type: "card",
        TokenID: "tok_test_visa_4242",
    },
}


orderParams := &conekta.OrderParams{}
orderParams.Currency = "MXN"
orderParams.CustomerInfo = customerParams
orderParams.LineItems = append(orderParams.LineItems, lineItemParams)
orderParams.ShippingLines = append(orderParams.ShippingLines, shippingParams)
orderParams.ShippingContact = shippingContactParams
orderParams.Charges = append(orderParams.Charges, chargeParams)

ord, err := order.Create(orderParams)
if err != nil {
    code := err.(conekta.Error).Details[0].Code
    //do something
    fmt.Printf(code)
} else {
    //Check if payment was successful
    if ord.payment_status == "paid" {
        fmt.Println(ord.ID)
        fmt.Println(ord.PaymentStatus)
        fmt.Println(ord.Amount/100, ord.Currency)
        fmt.Println(ord.LineItems.Data[0].Quantity)
        fmt.Println(ord.LineItems.Data[0].Name)
        fmt.Println(ord.LineItems.Data[0].UnitPrice/100)
        fmt.Println("--------Payment info--------")
        fmt.Println("code: ", ord.Charges.Data[0].PaymentMethod.AuthCode)
        fmt.Println("Card Info: ")
        fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Name)
        fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Last4)
        fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Brand)
        fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Type)

        //Si la orden fue exitosa la respuesta deberia imprimir lo siguiente:
        //ord_2nDAbSc2qY23Yk72s
        //paid
        //202 MXN
        //2
        //Naranjas Robadas
        //100
        //--------Payment info--------
        //code:    0
        //Card Info: 
        // -    Jorge Lopez
        // -    4242
        // -    visa
        // -    credit
    } else {
        fmt.Println(" - ", ord.Charges.Data[0].FailureMessage)
        fmt.Println(" - ", ord.Charges.Data[0].FailureCode)
    }
}

Paso 2.1 - Añade tu llave privada y versión del API

# N/A
require_once("/path/to/lib/Conekta.php");
\Conekta\Conekta::setApiKey("key_eYvWV7gSDkNYXsmr");
\Conekta\Conekta::setApiVersion("2.0.0");
require "conekta"
Conekta.api_key = "key_eYvWV7gSDkNYXsmr"
Conekta.api_version = "2.0.0"
import conekta
conekta.api_key = "key_eYvWV7gSDkNYXsmr"
conekta.api_version = "2.0.0"
var conekta = require('conekta');
conekta.api_key = 'key_eYvWV7gSDkNYXsmr';
conekta.api_version = '2.0.0';
import com.conekta;
Conekta.setApiKey("key_eYvWV7gSDkNYXsmr");
com.conekta.Conekta.apiVersion = "2.0.0"
using conekta;
conekta.Api.apiKey = "key_eYvWV7gSDkNYXsmr";
conekta.Api.version = "2.0.0";
import (
    conekta "github.com/conekta/conekta-go"
)

conekta.APIKey = "key_pMcnDF4zFyWKyLG15LuqwA"

Paso 2.2 - Crea un cliente y agrega información de pago

Al crear un customer con la información de tu cliente en conjunto con el token que ConektaJS te proporcionó anteriormente, tendrás la capacidad de reintentar el cargo y hacer cargos recurrentes siempre y cuando el usuario final esté consciente de ello.

Un customer puede tener muchos payment_sources pero sólo uno puede ser el default.

curl --request POST \
  --url https://api.conekta.io/customers \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
  "name": "Fulanito Pérez",
  "email": "[email protected]",
  "phone": "+52181818181",
  "metadata": {"reference": "12987324097", "random_key": "random value"},
  "payment_sources": [{
    "type": "card",
    "token_id": "tok_test_visa_4242"
  }]
}'
try {
  $customer = \Conekta\Customer::create(
    [
      "name" => "Fulanito Pérez",
      "email" => "[email protected]",
      "phone" => "+52181818181",
      "metadata" => ["reference" => "12987324097", "random_key" => "random value"],
      "payment_sources" => [
        [
          "type" => "card",
          "token_id" => "tok_test_visa_4242"
        ]
      ]
    ]
  );
} catch (\Conekta\ProccessingError $error){
  echo $error->getMesage();
} catch (\Conekta\ParameterValidationError $error){
  echo $error->getMessage();
} catch (\Conekta\Handler $error){
  echo $error->getMessage();
}
customer = Conekta::Customer.create({
  name: 'Fulanito Pérez',
  email: '[email protected]',
  phone: '+52181818181',
  metadata: {"reference" => "12987324097", "random_key" => "random value"},
  payment_sources: [{
    type: 'card',
    token_id: 'tok_test_visa_4242'
  }]
})
try:
  customer = conekta.Customer.create({
    'name': 'Fulanito Pérez',
    'email': '[email protected]',
    'phone': '+52181818181',
    'metadata': { 'description': 'Compra de creditos: 300(MXN)', 'reference': '1334523452345' },
    'payment_sources': [{
      'type': 'card',
      'token_id': 'tok_test_visa_4242'
    }]
  })
except conekta.ConektaError as e:
  print e.message
customer = conekta.Customer.create({
    'name': 'Fulanito Pérez',
    'email': '[email protected]',
    'phone': '+52181818181',
    'metadata': { 'description': 'Compra de creditos: 300(MXN)', 'reference': '1334523452345' },
    'payment_sources': [{
      'type': 'card',
      'token_id': 'tok_test_visa_4242'
    }]
  }, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });
try{
  Customer customer = Customer.create(
    new JSONObject("{"
      + "'name': 'Fulanito Pérez', "
      + "'email': '[email protected]',"
      + "'phone': '+52181818181',"
      + "'metadata': {'description': 'Compra de creditos: 300(MXN)' , 'reference' : '1334523452345'},"
      + "'payment_sources':[{"
        + "'type': 'card',"
        + "'token_id: 'tok_test_visa_4242"
        + "}]"
      + "}"
    )
  );
}catch (Conekta::Error e) {
   System.out.println(e.details.get(0).message);
}
try {
  conekta.Customer customer = new conekta.Customer().create(@"{
    ""name"":""Fulanito Pérez"",
    ""email"":""[email protected]"",
    ""phone"":""+52181818181"",
    ""metadata"":{""description"" : ""Compra de creditos: 300(MXN)"", ""reference"" : ""1334523452345""},
    ""payment_sources"":[{
      ""type"": ""card"",
      ""token_id"":""tok_test_visa_4242""
    }]
  }");
} catch (ConektaException e) {
  foreach (JObject obj in e.details) {
    System.Console.WriteLine("\n [ERROR]:\n");
    System.Console.WriteLine("message:\t" + obj.GetValue("message"));
    System.Console.WriteLine("debug:\t" + obj.GetValue("debug_message"));
    System.Console.WriteLine("code:\t" + obj.GetValue("code"));
  }
}
paymentSource := &conekta.PaymentSourceCreateParams{
    PaymentType: "card",
    TokenID: "tok_test_visa_4242",
}


customerParams := &conekta.CustomerParams{}
customerParams.Name = "fulanito Perez"
customerParams.Phone = "+5215555555555"
customerParams.Email = "[email protected]"
customerParams.PaymentSources = append(customerParams.PaymentSources, paymentSource)
customer, err := customer.Create(customerParams)

if err != nil {
    code := err.(conekta.Error).Details[0].Code
    fmt.Printf(code)
} else {
    fmt.Println(customer)
}

Cambia el método de pago default

Los campos mostrados en el ejemplo son los mínimos requeridos, si deseas saber más sobre el objeto customer revisa nuestra REST API.

curl -H "Accept: application/vnd.conekta-v2.0.0+json" \
-H "Content-type: application/json" \
-u key_apiKeyPrivada: \
-X PUT -d '{
"default_payment_source_id": "src_2hfjTmQcu4t3ioSie"
}' https://api.conekta.io/customers/cus_2hfjJgppVMbzpADZf
$customer = \Conekta\Customer::find("cus_2gR7i98PNSdiio6e9");
$source = $customer->payment_sources[0];
$customer->update(
[
"default_payment_source_id" => $source->id,
]
);
customer = Conekta::Customer.find("cus_2g7BJYJ85NJgw7RmE")
source = customer.payment_sources[0]
customer.update({default_payment_source_id: source.id})
customer = conekta.Customer.find('cus_2gR7i98PNSdiio6e9')
source = customer.payment_sources[0]
customer.update({
  'default_payment_source_id': source.id
})
conekta.Customer.find('cus_2gJHRkVXdMeoezZnA', function(err, customer) {
var srcId = customer.toObject().payment_sources.data[0].id;
customer.update({
default_payment_source_id: srcId
}, function(err, customer) {
console.log(customer.toObject());
});
});
Customer customer = Customer.find("cus_2gVz7XNYo8Ad3i8eC");
PaymentSource source = (PaymentSource) customer.payment_sources.get(0);
customer.update(new JSONObject("{"
'default_payment_source_id': ' +  source.id + "'"
}));
conekta.Customer customer = new conekta.Customer().find("cus_2govPxfoxFtxjkwbd");
conekta.PaymentSource source = customer.payment_sources[1];
System.Console.WriteLine(source.id);
customer.update(@"{
""default_payment_source_id"": """ + source.id + @"""
}");
//Cambia el método de pago default
customer := customer.Find("cus_2nD9kZfqRzMuF8czZ")
payment_source := &conekta.CustomerParams{
  DefaultPaymentSourceID: customer.PaymentSources.Data[0].ID,
} 

customer.Update("cus_2nD9kZfqRzMuF8czZ", payment_source)

Paso 2.3 - Crear una orden

Al crear un order se generará el cargo de tu cliente. Si no deseas crear el cargo de inmediato, puedes preparar la orden y después generar el cargo mandando la información del arreglo charges.

La información que debes enviar tiene que ser real ya que nuestro sistema de antifraude la necesita para revisar la veracidad de la transacción.

Los campos mostrados en el ejemplo son los mínimos requeridos, si deseas mejorar la veracidad de tus transacciones necesitas saber más sobre el objeto order, para ello, revisa nuestra REST API.

curl --request POST \
  --url https://api.conekta.io/orders \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
      "line_items": [{
          "name": "Tacos",
          "unit_price": 1000,
          "quantity": 120
      }],
      "shipping_lines": [{
          "amount": 1500,
          "carrier": "FEDEX"
      }],
      "currency": "MXN",
      "customer_info": {
          "customer_id": "cus_2fkJPFjQKABcmiZWz"
      },
      "shipping_contact":{
           "address": {
               "street1": "Calle 123, int 2",
               "postal_code": "06100",
               "country": "MX"
           }
       },
     "metadata": {"reference": "12987324097", "more_info": "lalalalala"},
      "charges":[{
          "payment_method": {
              "type": "default"
          }
      }]
  }'
try{
  $order = \Conekta\Order::create(
    [
      "line_items" => [
        [
          "name" => "Tacos",
          "unit_price" => 1000,
          "quantity" => 120
        ]
      ],
      "shipping_lines" => [
        [
          "amount" => 1500,
           "carrier" => "FEDEX"
        ]
      ], //shipping_lines - physical goods only
      "currency" => "MXN",
      "customer_info" => [
        "customer_id" => "cus_2fkJPFjQKABcmiZWz"
      ],
      "shipping_contact" => [
        "address" => [
          "street1" => "Calle 123, int 2",
          "postal_code" => "06100",
          "country" => "MX"
        ]
      ], //shipping_contact - required only for physical goods
      "metadata" => ["reference" => "12987324097", "more_info" => "lalalalala"],
      "charges" => [
          [
            "payment_method" => [
              "type" => "default"
            ] //payment_method - use customer's default - a card
              //to charge a card, different from the default,
              //you can indicate the card's source_id as shown in the Retry Card Section
          ]
      ]
    ]
  );
} catch (\Conekta\ProcessingError $error){
  echo $error->getMessage();
} catch (\Conekta\ParameterValidationError $error){
  echo $error->getMessage();
} catch (\Conekta\Handler $error){
  echo $error->getMessage();
}
begin
  order = Conekta::Order.create({
    line_items: [{
        name: "Tacos",
        unit_price: 1000,
        quantity: 120
    }],
    shipping_lines: [{
        amount: 1500,
        carrier: "FEDEX"
    }], #shipping_lines - physical goods only
    currency: "MXN",
    customer_info: {
        customer_id: "cus_2fkJPFjQKABcmiZWz"
    },
    shipping_contact: {
        address: {
            street1: "Calle 123, int 2",
            postal_code: "06100",
            country: "MX"
        }
    }, #shipping_contact - required only for physical goods
    charges: [{
        payment_method: {
            type: "default"
        } #payment_method - use the customer's default - a card
          #to charge a card, different from the default,
          #you can indicate the card's source_id as shown in the Retry Card Section
    }],
    metadata: {"reference" => "12987324097", "more_info" => "lalalalala"}
  })
rescue Conekta::Error => error_list
  for error_detail in error.details do
    puts error_detail.message
  end
end
try:
  order = conekta.Order.create({
      "line_items": [{
          "name": "Tacos",
          "unit_price": 1000,
          "quantity": 120
      }],
      "shipping_lines": [{
          "amount": 1500,
          "carrier": "FEDEX"
      }], #shipping_lines - physical goods only
      "currency": "MXN",
      "customer_info": {
       "customer_id": "cus_2fkJPFjQKABcmiZWz"
      },
      "shipping_contact":{
       "address": {
         "street1": "Calle 123, int 2",
         "postal_code": "06100",
         "country": "MX"
       } #shipping_contact - required only for physical goods
     },
    "metadata": { "description": "Compra de creditos: 300(MXN)", "reference": "1334523452345" },
    "charges":[{
      "payment_method": {
        "type": "default"
      }  #payment_method - use the customer's default - a card
         #to charge a card, different from the default,
         #you can indicate the card's source_id as shown in the Retry Card Section
    }]
  })
except conekta.ConektaError as e:
  print e.message
order = conekta.Order.create({
    "line_items": [{
        "name": "Tacos",
        "unit_price": 1000,
        "quantity": 120
    }],
    "shipping_lines": [{
        "amount": 1500,
        "carrier": "FEDEX"
    }], //shipping_lines - physical goods only
    "currency": "MXN",
    "customer_info": {
     "customer_id": "cus_2fkJPFjQKABcmiZWz"
    },
    "shipping_contact":{
     "address": {
       "street1": "Calle 123, int 2",
       "postal_code": "06100",
       "country": "MX"
     }
   },  //shipping_contact - required only for physical goods
  "metadata": { "description": "Compra de creditos: 300(MXN)", "reference": "1334523452345" },
  "charges":[{
    "payment_method": {
      "type": "default"
    }  //payment_methods - use the customer's default - a card
       //to charge a card, different from the default,
       //you can indicate the card's source_id as shown in the Retry Card Section
  }]
}, function(err, res) {
    if(err){
      console.log(err);
      return;
    }
    console.log(res.toObject());
});
try{
  Order order = Order.create(
    new JSONObject("{"
      + "'line_items': [{"
          + "'name': 'Tacos',"
          + "'unit_price': 1000,"
          + "'quantity': 120"
      + "}]," //line_items
      + "'shipping_lines': [{"
          + "'amount': 1500,"
          + "'carrier': 'FEDEX'"
      + "}]," //shipping_lines - physical goods only
      + "'currency': 'MXN',"
      + "'customer_info': {"
        + "'customer_id': 'cus_2fkJPFjQKABcmiZWz'"
      + "}," //customer_info
      + "'shipping_contact':{"
         + "'address': {"
           + "'street1': 'Calle 123, int 2',"
           + "'postal_code': '06100',"
           + "'country': 'MX'"
         + "}"
       + "}," //shipping_contact - required only for physical goods 
       +"'metadata': {'description': 'Compra de creditos: 300(MXN)' , 'reference' : '1334523452345'},"
      + "'charges':[{"
        + "'payment_method': {"
          + "'type': 'default'"
        + "}" //payment_method - use the customer's default - a card
              //to charge a card, different from the default,
              //you can indicate the card's source_id as shown in the Retry Card Section
      + "}]" //charges
    + "}" //order
    )
  );
}catch (Conekta::Error e) {
   System.out.println(e.details.get(0).message);
}
try{
  conekta.Order order = new conekta.Order ().create(@"{
    ""line_items"": [{
        ""name"": ""Tacos"",
        ""unit_price"": 1000,
        ""quantity"": 120
    }],
    ""shipping_lines"": [{
        ""amount"": 1500,
        ""carrier"": ""FEDEX""
    }], //shipping_lines - physical goods only
    ""currency"": ""MXN"",
    ""customer_info"": {
      ""customer_id"": ""cus_2fkJPFjQKABcmiZWz""
    },
    ""shipping_contact"":{
       ""address"": {
         ""street1"": ""Calle 123, int 2"",
         ""postal_code"": ""06100"",
         ""country"": ""MX""
       }
     }, //shipping_contact - required only for physical goods 
    ""metadata"":{""description"" : ""Compra de creditos: 300(MXN)"", ""reference"" : ""1334523452345""},
    ""charges"":[{
      ""payment_method"": {
        ""type"": ""default""
      } //payment_method - use the customer's default - a card
        //to charge a card, different from the default,
        //you can indicate the card's source_id as shown in the Retry Card Section
    }]
  }");
} catch (ConektaException e) {
  foreach (JObject obj in e.details) {
    System.Console.WriteLine("\n [ERROR]:\n");
    System.Console.WriteLine("message:\t" + obj.GetValue("message"));
    System.Console.WriteLine("debug:\t" + obj.GetValue("debug_message"));
    System.Console.WriteLine("code:\t" + obj.GetValue("code"));
  }
}
Address := &conekta.Address{
    Street1: "Street1",
    Street2: "Street2",
    City: "City",
    State: "State",
    Country: "Country",
    PostalCode: "PostalCode",
}

lineItemParams := &conekta.LineItemsParams{
    Name: "Naranjas Robadas",
    UnitPrice: 10000,
    Quantity: 2,
}

shippingLinesParams := &conekta.ShippingLinesParams{
    Amount: 200,
    TrackingNumber: "123",
    Carrier: "Test Carrier",
    Method: "method",
}

customerParams := &conekta.CustomerParams{
    ID: "cus_2nD9kZfqRzMuF8czZ",
}

shippingContactParams := &conekta.ShippingContactParams{
    Phone: "55-5555-5555",
    Receiver: "Miguel",
    BetweenStreets: "BetweenStreets",
    Address: Address,
}

chargeParams := &conekta.ChargeParams{
    PaymentMethod: &conekta.PaymentMethodParams{
        Type: "default",
    },
    //payment_method - use customer's default - a card
    //to charge a card, different from the default,
    //you can indicate the card's source_id as shown in the Retry Card Section
}

orderParams := &conekta.OrderParams{}
orderParams.Currency = "MXN"
orderParams.CustomerInfo = customerParams
orderParams.LineItems = append(orderParams.LineItems, lineItemParams)
orderParams.ShippingLines = append(orderParams.ShippingLines, shippingLinesParams)
orderParams.ShippingContact = shippingContactParams
orderParams.Charges = append(orderParams.Charges, chargeParams)

ord, err := order.Create(orderParams)

if err != nil {
    code := err.(conekta.Error).Details[0].Code
    //do something
    fmt.Printf(code)
} else {
    //Check if payment was successful
    if ord.payment_status == "paid" {
        fmt.Println(ord)
    } else {
        fmt.Println(" - ", ord.Charges.Data[0].FailureMessage)
        fmt.Println(" - ", ord.Charges.Data[0].FailureCode)
    }
}

Paso 2.4 - Procesar respuesta

Recibirás un objeto JSON con mucha información, puedes mostrar los campos que creas necesarios.

Una buena práctica es notificar a tu usuario vía email.

# N/A
echo "ID: ". $order->id;
echo "Status: ". $order->payment_status;
echo "$". $order->amount/100 . $order->currency;
echo "Order";
echo $order->line_items[0]->quantity .
      "-". $order->line_items[0]->name .
      "- $". $order->line_items[0]->unit_price/100;
echo "Payment info";
echo "CODE:". $order->charges[0]->payment_method->auth_code;
echo "Card info:".
      "- ". $order->charges[0]->payment_method->name .
      "- ". $order->charges[0]->payment_method->last4 .
      "- ". $order->charges[0]->payment_method->brand .
      "- ". $order->charges[0]->payment_method->type;


// Response
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
puts "ID: #{order.id}"
puts "Status: #{order.payment_status}"
puts "$ #{(order.amount/100).to_f} #{order.currency}"
puts "Order"
puts "#{order.line_items[0].quantity}
      - #{order.line_items[0].name}
      - $ #{(order.line_items[0].unit_price/100).to_f}"
puts "Payment info"
puts "CODE: #{order.charges[0].payment_method.auth_code}"
puts "Card info:
      - #{order.charges[0].payment_method.name}
      - #{order.charges[0].payment_method.last4}
      - #{order.charges[0].payment_method.brand}
      - #{order.charges[0].payment_method.type}"


# Response
# ID: ord_2fsQdMUmsFNP2WjqS
# $ 1215.0 MXN
# Order
# 120 - Tacos - $10.0
# Payment info
# CODE: 035315
# Card info: 4242 - visa - banco - credit
print("ID: " + order.id)
print("Status: " + order.payment_status)
print("$" + str((order.amount/100)) + order.currency)
print("Order")
print(str(order.line_items[0].quantity) + " - "
            + order.line_items[0].name + " - "
            + str((order.line_items[0].unit_price/100)))
print("Payment info");
print("Code: " + order.charges[0].payment_method.auth_code)
print("Card info: "
              + order.charges[0].payment_method.name + " - "
              + order.charges[0].payment_method.last4 + " - "
              + order.charges[0].payment_method.brand + " - "
              + order.charges[0].payment_method.type)


# Response
# ID: ord_2fsQdMUmsFNP2WjqS
# $ 1215.0 MXN
# Order
# 120 - Tacos - $10.0
# Payment info
# CODE: 035315
# Card info: 4242 - visa - banco - credit
console.log("ID: " + res.toObject().id);
    console.log("Status: " + res.toObject().payment_status);
    console.log("$" + (res.toObject().amount/100) + res.toObject().currency);
    console.log("Order");
    console.log(res.toObject().line_items.data[0].quantity + " - "
            + res.toObject().line_items.data[0].name + " - "
            + (res.toObject().line_items.data[0].unit_price/100));
    console.log("Payment info");
    console.log("Code: " + res.toObject().charges.data[0].payment_method.auth_code);
    console.log("Card info: "
              + res.toObject().charges.data[0].payment_method.name + " - "
              + res.toObject().charges.data[0].payment_method.last4 + " - "
              + res.toObject().charges.data[0].payment_method.brand + " - "
              + res.toObject().charges.data[0].payment_method.type);


// Response
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
LineItems line_item = (LineItems)order.line_items.get(0);
  Charge charge = (Charge) order.charges.get(0);
  PaymentMethod payment_method = (PaymentMethod) charge.payment_method;
  System.out.println("ID: " + order.id);
  System.out.println("Status: " + order.payment_status);
  System.out.println("$" + (order.amount/100) + order.currency);
  System.out.println("Order");
  System.out.println(line_item.quantity + " - "
                    + line_item.name + " - "
                    + (line_item.unit_price/100));
  System.out.println("Payment info");
  System.out.println("Code: " + payment_method.getVal("auth_code"));
  System.out.println("Card info: "
                    + payment_method.getVal("name") + " - "
                    + payment_method.getVal("last4") + " - "
                    + payment_method.getVal("brand") + " - "
                    + payment_method.getVal("type"));


// Response
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
Console.WriteLine("ID: " + order.id);
            Console.WriteLine("Status: " + order.payment_status);
            Console.WriteLine("Amount: $" + (order.amount / 100) + order.currency);
            Console.WriteLine("Order:");
            LineItem line_item = (LineItem)order.line_items.at(0);
            Console.WriteLine(line_item.quantity + " - "
                              + line_item.name + " - "
                              + (line_item.unit_price / 100));
            Charge charge = (Charge)order.charges.at(0);
            Console.WriteLine("Code: " + charge.payment_method.auth_code);
            Console.WriteLine("Card info: "
                          + charge.payment_method.name + " - "
                          + charge.payment_method.last4 + " - "
                          + charge.payment_method.brand + " - "
                          + charge.payment_method.type);


// Response
// ID: ord_2fsQdMUmsFNP2WjqS
// $ 1215.0 MXN
// Order
// 120 - Tacos - $10.0
// Payment info
// CODE: 035315
// Card info: 4242 - visa - banco - credit
//Procesar respuesta
fmt.Println("ID: ", ord.ID)
fmt.Println("Status: ", ord.PaymentStatus)
fmt.Println("$", ord.Amount/100, ord.Currency)
fmt.Println("--------Order--------")
fmt.Println(ord.LineItems.Data[0].Quantity)
fmt.Println(ord.LineItems.Data[0].Name)
fmt.Println(ord.LineItems.Data[0].UnitPrice/100)
fmt.Println("--------Payment info--------")
fmt.Println("code: ", ord.Charges.Data[0].PaymentMethod.AuthCode)
fmt.Println("Card Info: ")
fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Name)
fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Last4)
fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Brand)
fmt.Println(" - ", ord.Charges.Data[0].PaymentMethod.Type)

//Response
//ord_2nDAbSc2qY23Yk72s
//paid
//202 MXN
//2
//Naranjas Robadas
//100
//--------Payment info--------
//code:  0
//Card Info: 
// -  Jorge Lopez
// -  4242
// -  visa
// -  credit

👍

¡Listo!

Recuerda cambiar tus llaves pública y privada después de realizar pruebas.

Existirán casos en los que el cargo no será exitoso, puedes ofrecer a tu cliente utilizar otro método de pago. En estos casos puedes probar alguna de estas opciones:

1. Intentar con otra tarjeta

Para hacer un cargo con un método de pago diferente al default solo necesitas su payment_source_id, el cual podrás obtener dentro del objeto payment source.

curl --request POST \
 --url https://api.conekta.io/orders/ord_2fsQdMUmsFNP2WjqS/charges \
 --header 'accept: application/vnd.conekta-v2.0.0+json' \
 -u key_eYvWV7gSDkNYXsmr: \
 --header 'content-type: application/json' \
 --data '{
     "payment_method": {
         "type": "card",
         "payment_source_id": "src_2fkJPFjQKABcmiZWy"
     }
 }'
$charge = \Conekta\Order::createCharge(
 [
   "payment_method" => [
     "type" => "card",
     "payment_source_id" => "src_2fkJPFjQKABcmiZWy"
   ]
 ]
);
charge = order.create_charge({
   payment_method: {
      type: "card",
      payment_source_id: "src_2fkJPFjQKABcmiZWy"
    }
 })
charge = order.createCharge({
 "payment_method": {
     "type": "card",
     "payment_source_id": "src_2fkJPFjQKABcmiZWy"
 }
})
charge = conekta.Order.create_charge({
   "payment_method": {
       "type": "card",
       "payment_source_id": "src_2fkJPFjQKABcmiZWy"
   }
}, function(err, res) {
     console.log(res.toObject());
});
Charge charge = order.createCharge("{"
 + "'payment_method': {"
     + "'type': 'card',"
     + "'payment_source_id': 'src_2fkJPFjQKABcmiZWy'"
   + "}"
 +"}");
order.createCharge (@"{
  ""type"":""card"",
  ""payment_source_id"":""src_2fkJPFjQKABcmiZWy""
}");
paymentMethodParams := &conekta.PaymentMethodParams{
    Type: "card",
    PaymentSourceID: "src_2fkJPFjQKABcmiZWy",
}
charge := &conekta.ChargeParams{
    PaymentMethod: paymentMethodParams,
}

charge.Create("ord_2nDAbSc2qY23Yk72s", charge)

2. Intentar con otro método de pago

Te recomendamos sugerir otro método de pago como OXXO Pay o SPEI cuando los reintentos fallidos de tarjeta fueron más de 2.

curl --request POST \
  --url https://api.conekta.io/orders/ord_2fsQdMUmsFNP2WjqS/charges \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
      "payment_method": {
          "type": "oxxo_cash"
      }
  }'


curl --request POST \
  --url https://api.conekta.io/orders/ord_2fsQdMUmsFNP2WjqS/charges \
  --header 'accept: application/vnd.conekta-v2.0.0+json' \
  -u key_eYvWV7gSDkNYXsmr: \
  --header 'content-type: application/json' \
  --data '{
      "payment_method": {
          "type": "spei"
      }
  }'
// OxxoPay
$charge = \Conekta\Order::createCharge(
  [
    "payment_method" => [
        "type" => "oxxo_cash"
    ]
  ]
);


// SPEI
$charge = \Conekta\Order::createCharge(
  [
    "payment_method" => [
        "type" => "spei"
    ]
  ]
);
# OxxoPay
charge = order.create_charge({
  payment_method: {
      type: "oxxo_cash"
  }
})


# SPEI
charge = order.create_charge({
  payment_method: {
      type: "spei"
  }
})
# OxxoPay
charge = order.createCharge({
  "payment_method": {
      "type": "oxxo_cash"
  }
})


# SPEI
charge = order.createCharge({
  "payment_method": {
      "type": "spei"
  }
})
// OxxoPay
charge = conekta.Order.create_charge({
    "payment_method": {
        "type": "oxxo_cash"
    }
}, function(err, res) {
      console.log(res.toObject());
});


// SPEI
charge = conekta.Order.create_charge({
    "payment_method": {
        "type": "spei"
    }
}, function(err, res) {
      console.log(res.toObject());
});
// OxxoPay
Charge charge = order.createCharge("{"
  + "'payment_method': {"
      + "'type': 'oxxo_cash'"
    + "}"
  +"}");


// SPEI
Charge charge = order.createCharge("{"
  + "'payment_method': {"
      + "'type': 'spei'"
    + "}"
  +"}");
// OxxoPay
order.createCharge (@"{
   ""type"":""oxxo_cash""
}");


// SPEI
order.createCharge (@"{
   ""type"":""spei""
}");
//OxxoPay
paymentMethodParams := &conekta.PaymentMethodParams{
    Type: "oxxo_cash",
    ExpiresAt: time.Now().AddDate(0, 0, 30).Unix(),
}
charge := &conekta.ChargeParams{
    PaymentMethod: paymentMethodParams,
}

charge.Create("ord_2nDAbSc2qY23Yk72s", charge)

//SPEI
paymentMethodParams := &conekta.PaymentMethodParams{
    Type: "spei",
    ExpiresAt: time.Now().AddDate(0, 0, 90).Unix(),
}
charge := &conekta.ChargeParams{
    PaymentMethod: paymentMethodParams,
}

charge.Create("ord_2nDAbSc2qY23Yk72s", charge)