Integrar Checkout

Crea un Checkout Oxxo Pay e intégralo en tu sitio.
Es una solución de cobro práctica y rápida que te permite vender online, ofreciendo pago en efectivo como medio de pago . Siguiendo nuestras herramientas y tutoriales de integración, podrás sumarlo a tu sitio sin ningún inconveniente.

Checkout -> Se muestra en una pestaña distinta al de tu sitio en línea. El cliente paga y continúa el flujo de compra en tu tienda.

📘

Primeros pasos

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

Crear un Customer

curl -H "Accept: application/vnd.app-v2.1.0+json" \
     -H "Content-type: application/json" \
     -u YOUR_ACCESS_TOKEN: \
     -X POST -d '{
    "name": "Juan Perez",
    "email": "[email protected]"
}' https://api.digitalfemsa.io/customers
<?php

$validCustomer = [
  'name' => "Payment Link Name",
  'email' => "[email protected]"
];
$customer = Customer::create($validCustomer);
# Inicialización del cliente DigitalFemsa través de la adición de la llave privada y versión del API
require "digital_femsa"
DigitalFEMSA.api_key = "key_eYvWV7gSDkNYXsmr" # <-- Llave privada de ejemplo, por favor usa TU llave privada personal
DigitalFEMSA.api_version = "2.0.0"

valid_customer = {
  name: "Payment Link Name",
  email: "[email protected]"
}
customer = DigitalFEMSA::Customer.create(valid_customer)

let customer = digital_femsa.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;

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

var customer = new Customer().create(validCustomer);
package main

import (
    "context"
    "fmt"
    "io"
    "net/http"

    "github.com/digitalfemsa/digitalfemsa-go"
)

func main() {
    const acceptLanguage = "es"
    cfg := digitalfemsa.NewConfiguration()
    client := digitalfemsa.NewAPIClient(cfg)
    ctx := context.WithValue(context.TODO(), digitalfemsa.ContextAccessToken, "key_DwaOLXoX6YCGGvfNifZ3IPwi")
    req := digitalfemsa.Customer{
        Name:            "Foo Test",
        Phone:           "+573143159063",
        Email:           "[email protected]",
        Corporate:       digitalfemsa.PtrBool(true),
        PlanId:          digitalfemsa.PtrString("plan_2tXx672QLQ68CkmMn"),
        CustomReference: digitalfemsa.PtrString("go_12345678"),
    }
    customer, response, err := client.CustomersApi.CreateCustomer(ctx).Customer(req).AcceptLanguage(acceptLanguage).Execute()
    if err != nil {
        panic(err)
    }
    if response.StatusCode != http.StatusCreated {
        responseBody, err := io.ReadAll(response.Body)
        if err != nil {
            panic(err)
        }
        panic(fmt.Sprintf("response body: %s", responseBody))
    }
    fmt.Printf("customer: %v", customer)
}
// Inicialización del cliente DigitalFemsa a través de la adición de la llave privada y versión del API.
DigitalFemsa.setApiKey("key_eYvWV7gSDkNYXsmr"); // <-- Llave privada de ejemplo, por favor usa TU llave privada personal
com.digitalfemsa.DigitalFemsa.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": "Juan Perez",
    "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;
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", customer.Livemode)
fmt.Println("Name: %v\n", *customer.Name)
fmt.Println("Email: %v\n", *customer.Email)
fmt.Println("ID: %v\n", customer.Id)
System.out.println(customer.livemode);
System.out.println(customer.name);
System.out.println(customer.email);
System.out.println(customer.id);

Crear una Order 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 Order y un Checkout object al mismo tiempo. Aquí se definen las urls de redirección una vez que se haya completado ya sea exitoso o fallido el pago.

curl -H "Accept: application/vnd.app-v2.1.0+json" \
     -H "Content-type: application/json" \
     -u YOUR_ACCESS_TOKEN: \
     -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"],
           "type": "HostedPayment",
           "success_url": "https://www.mysite.com/payment/confirmation",
           "failure_url": "https://www.mysite.com/payment/failure",
           "redirection_time": 4 //Tiempo de Redirección al Success-Failure URL, umbrales de 4 a 120 seg.
        },
       "shipping_contact": {
          "phone": "+5215555555555",
          "receiver": "Marvin Fuller",
          "address": {
            "street1": "Nuevo Leon 4",
            "country": "MX",
            "postal_code": "06100"
          }
       }
}' https://api.digitalfemsa.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"),
    'type' => 'HostedPayment',
    'success_url' => 'https://www.mysite.com/payment/confirmation',
    'failure_url' => 'https://www.mysite.com/payment/failure',
    "redirection_time": 4 //Tiempo de Redirección al Success/Failure URL, umbrales de 4 a 120 seg.
  ),
  '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"],
       expires_at: Time.now.to_i + 259200,
       failure_url: "testredirect.com",
       force_2fa_flow: true,
       success_url: "testredirect.com",
       type: "HostedPayment",
       redirection_time: 4 # Tiempo de Redirección al Success/Failure URL, umbrales de 4 a 120 seg.
   },
   customer_info: {
       customer_id: customer.id
   },
   currency: 'mxn',
   metadata: {test: 'extra info'}
}
order = DigitalFemsa::Order.create(valid_order_with_checkout)
puts order.inspect
order = self.client.Order.create(order)
checkout = order.createCheckout({
       "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": {
          "type":"HostedPayment",
          "success_url": "testredirect.com",
          "failure_url": "testredirect.com",
          "allowed_payment_methods": ["cash"],
          "multifactor_authentication": False,
          "expires_at": 1609891200,
          "redirection_time": 4 //Tiempo de Redirección al Success/Failure URL, umbrales de 4 a 120 seg.
      
       },
      "shipping_contact": {
         "phone": "+5215555555555",
         "receiver": "Marvin Fuller",
         "address": {
           "street1": "Nuevo Leon 4",
           "country": "MX",
           "postal_code": "06100"
         }
      }
   })
digital_femsa.Order.create({
       "currency": "MXN",
       "customer_info": {
          "customer_id": customer.id
       },
      "line_items": [{
          "name": "Box of Cohiba S1s",
          "unit_price": 300000,
          "quantity": 1
      }],
      "shipping_lines": [{
          "amount": 0
      }],
      "checkout": {
          "type":"HostedPayment",
          "success_url": "testredirect.com",
          "failure_url": "testredirect.com",
          "allowed_payment_methods": ["cash"],
          "multifactor_authentication": False,
          "expires_at": 1609891200,
          "redirection_time": 4 //Tiempo de Redirección al Success/Failure URL, umbrales de 4 a 120 seg.
       },
      "shipping_contact": {
         "phone": "+5215555555555",
         "receiver": "Marvin Fuller",
         "address": {
           "street1": "Nuevo Leon 4",
           "country": "MX",
           "postal_code": "06100"
         }
      }
   }, function(err, res) {
      if(err){
        console.log(err);
        return;
      }
      console.log(res.toObject());
  });
using Newtonsoft.Json;

var validOrderWithCheckout = new
  {
    currency: "MXN",
    customer_info = new 
      {
        customer_id = "cus_2o3FvMEBiKitVK1vQ"
      },
    line_items = new 
      [
        new
        {
          name = "Box of Cohiba S1s",
          unit_price = 300000,
          quantity = 1
        }
      ],
    shipping_lines = new 
      [
        new
          {
            "amount" = 0
          }
      ],
    checkout = new
      {
        type = "HostedPayment",
        success_url = "testredirect.com",
        failure_url = "testredirect.com",
        allowed_payment_methods = new string[] 
          {
            "cash",
          },
        multifactor_authentication = false,
        expires_at = 1609891200,
        redirection_time= 4 //Tiempo de Redirección al Success/Failure URL, umbrales de 4 a 120 seg.
      },
     shipping_contact = new
       {
         phone = "+5215555555555",
         receiver = "Marvin Fuller",
         address = new 
           {
             street1 = "Nuevo Leon 4",
             country = "MX",
             postal_code = "06100"
           }
      }
  };

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

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"github.com/digitalfemsa/digitalfemsa-go"
)

func main() {
	const acceptLanguage = "es"
	cfg := digitalfemsa.NewConfiguration()
	client := digitalfemsa.NewAPIClient(cfg)
	ctx := context.WithValue(context.TODO(), digitalfemsa.ContextAccessToken, "key_DwaOLXoX6YCGGvfNifZ3IPwi")
	rq := digitalfemsa.OrderRequest{
		Checkout: &digitalfemsa.CheckoutRequest{
			AllowedPaymentMethods: []string{"cash"},
			FailureUrl:            digitalfemsa.PtrString("https://www.mysite.com/payment/failure"),
			SuccessUrl:            digitalfemsa.PtrString("https://www.mysite.com/payment/confirmation"),
			Type:                  digitalfemsa.PtrString("HostedPayment"),
		},
		Currency: "MXN",
		CustomerInfo: digitalfemsa.OrderRequestCustomerInfo{
			CustomerInfoJustCustomerId: digitalfemsa.NewCustomerInfoJustCustomerId("cus_2nHprwaWFn7QJ21Lj"),
		},
		LineItems: []digitalfemsa.Product{
			{
				Name:      "Box of Cohiba S1s",
				UnitPrice: 35000,
				Quantity:  1,
			},
		},
		ShippingContact: &digitalfemsa.CustomerShippingContacts{
			Phone:    digitalfemsa.PtrString("+5215555555555"),
			Receiver: digitalfemsa.PtrString("Marvin Fuller"),
			Address: digitalfemsa.CustomerShippingContactsAddress{
				Street1:    digitalfemsa.PtrString("Nuevo Leon 4"),
				PostalCode: digitalfemsa.PtrString("06100"),
				Country:    digitalfemsa.PtrString("MX"),
			},
		},
		ShippingLines: []digitalfemsa.ShippingRequest{{Amount: 0}},
	}
	order, response, err := client.OrdersApi.CreateOrder(ctx).
		OrderRequest(rq).
		AcceptLanguage(acceptLanguage).
		Execute()
	if err != nil {
		panic(err)
	}
	if response.StatusCode != http.StatusCreated {
		responseBody, err := io.ReadAll(response.Body)
		if err != nil {
			panic(err)
		}
		panic(fmt.Sprintf("response body: %s", responseBody))
	}
	fmt.Printf("order: %v", order)
}

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']," +
                        "    'expired_at': " + (System.currentTimeMillis() / 1000L) + 259200 + "," +
                        "    'failure_url': 'testredirect.com'," +
                        "    'success_url': 'testredirect.com'," +
                        "    'type': 'HostedPayment'" +
                        "    'redirection_time': 4," +
                        "  }," +
                        "  'shipping_contact': {" +
                        "    'phone': '5555555555'," +
                        "    'receiver': 'Marvin Fuller'" +
                        "  }" +
                        "}")
    );
} catch (DigitalFemsa::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",
        "type": "HostedPayment",
        "status": "Issued",
        "url": "https://pay.digitalfemsa.io/link/964b5bdfe557467d9e02469e89b48e19",
        "allowed_payment_methods": ["cash"],
        "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": {}
        }]
    },
    "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")
print_r($order->checkout->object); // 'checkout'
print_r($order->checkout->url); // 'https://pay.digitalfemsa.io/link/964b5bdfe557467d9e02469e89b48e19
print_r($order->checkout->type); // 'HostedPayment'
puts order.checkout.allowed_payment_methods.inspect
puts order.checkout.object
puts order.checkout.url
puts order.checkout.type
console.log(stringify(order.checkout.allowed_payment_methods)); // [cash]
console.log(stringify(order.checkout.url)); // 'https://pay.digitalfemsa.io/link/964b5bdfe557467d9e02469e89b48e19
console.log(strinfiy(order.checkout.type)); // 'HostedPayment'
Console.WriteLine(order.checkout._object); // 'checkout'
Console.WriteLine(order.checkout.url); // 'https://pay.digitalfemsa.io/link/964b5bdfe557467d9e02469e89b48e19
Console.WriteLine(order.checkout.type); // 'HostedPayment'
	fmt.Println("AllowedPaymentMethod: %v\n", order.Checkout.AllowedPaymentMethods)
	fmt.Println("Url: %v\n", order.Checkout.Url)
	fmt.Println("Type: %v\n", order.Checkout.Type)
System.out.println(order.checkout.allowed_payment_methods);
System.out.println(order.checkout.object);
System.out.println(order.checkout.type);

Redireccionar el Checkout

En tu sitio tienes que hacer redirección a la url regresada en el paso anterior, donde el usuario podrá efectuar su pago en el Checkout:

Open a web browser and goto checkout url.
redirect_to order.checkout.url
<?php

header("Location: {$order->checkout->url}");
res.redirect(order.checkout.url);
header($"Location: {order.checkout.url}");
http.HandleFunc("/", http.RedirectHandler(order.checkout.url, 301))
response.sendRedirect(order.checkout.url);

Regresar al sitio posterior al pago

Una vez que tu Cliente procese el pago, ya sea que haya sido Exitoso o Fallido se realizará el redirect a las urls success_url y failure_url definidas en el paso 2, dada la configuración expresada en segundos del redirection_time, definidas en el paso 2.

Se agregaran los siguientes parámetros a la url de redirección devuelta al sitio.

ParámetroDescripciónEjemplos
checkout_idIdentificador de la petición del checkout7e531c1e-7ac7-4c46-8ee1-44d45913449c
order_idIdentificador de la orden.ord_2oCQQtCxJ5UnQyXSq
payment_statusEstatus del pagopaid, pending_payment, error

Redirección a tu sitio, dadas las URLs de Success o Failure, considera configurar una Thank you page para presentar los datos mencionados arriba, datos adicionales de tu negocio así como la identidad de tu marca.

Una vez recibas estos parámetros tienes que validar el estatus de la Order haciendo una petición a Direct API.

curl --request GET \
  --url https://api.digitalfemsa.io/orders/{Order_Id} \
  --header 'accept: application/vnd.app-v2.1.0+json' \
  -u YOUR_ACCESS_TOKEN: \
  --header 'content-type: application/json'
order = DigitalFemsa::Order.find("ord_2oEhsRCcpaxW66Y2x")
var order = new Order().find("ord_2oEhsRCcpaxW66Y2x");

Console.WriteLine(order.payment_status);
<?php

$order = Order::find('ord_2oEhsRCcpaxW66Y2x');
print_r($order->payment_status);
digital_femsa.Order.find("ord_2oEhsRCcpaxW66Y2x", (err, ord) => {
  console.log(stringify(ord.payment_status));
});
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"github.com/digitalfemsa/digitalfemsa-go"
)

func main() {
	const acceptLanguage = "es"
	cfg := digitalfemsa.NewConfiguration()
	client := digitalfemsa.NewAPIClient(cfg)
	ctx := context.WithValue(context.TODO(), digitalfemsa.ContextAccessToken, "key_DwaOLXoX6YCGGvfNifZ3IPwi")
	order, response, err := client.OrdersApi.GetOrderById(ctx, "ord_2oEhsRCcpaxW66Y2x").
		AcceptLanguage(acceptLanguage).
		Execute()
	if err != nil {
		panic(err)
	}
	if response.StatusCode != http.StatusCreated {
		responseBody, err := io.ReadAll(response.Body)
		if err != nil {
			panic(err)
		}
		panic(fmt.Sprintf("response body: %s", responseBody))
	}
	fmt.Println("Payment Status: %v", order.PaymentStatus)
}
Order order = Order.find("ord_2oEhsRCcpaxW66Y2x");

Recibir la notificación del pago

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

👍

¡Listo!

Recuerda cambiar tus API Keys pública y privada de sandbox por tus API Keys de producción después de realizar pruebas.