Cargo único
Genera pagos de una sola ocasión con Pago en Plazos
Flujo
1. Añade tu llave privada y versión del API
Necesitarás tu llave privada de pruebas. Si aún no cuentas con ella, puedes obtenerla en tu Panel Conekta.
2. Crea una orden
Al crear un order se generará el cargo de tu cliente. Si no deseas crear el cargo inmediato, puedes preparar la orden y después generar el cargo mandando la información del arreglo charges.
Los campos mostrados en el ejemplo son los mínimos requeridos, si deseas saber más sobre el objeto order revisa nuestra REST API.
El campo product_type podrá tener estos dos valores aplazo_bnpl y creditea_bnpl
curl --request POST \
--url https://api.conekta.io/orders \
--header 'accept: application/vnd.conekta-v2.2.0+json' \
-u key_eYvWV7gSDkNYXsmr: \
--header 'content-type: application/json' \
--data '{
"line_items": [{
"name": "Tacos",
"unit_price": 1000,
"quantity": 12
}],
"shipping_lines": [{
"amount": 1500,
"carrier": "FEDEX"
}],
"currency": "MXN",
"customer_info": {
"name": "Fulanito Pérez",
"email": "[email protected]",
"phone": "+5218181818181"
},
"shipping_contact":{
"address": {
"street1": "Calle 123, int 2",
"postal_code": "06100",
"country": "MX"
}
},
"charges":[{
"payment_method": {
"type": "bnpl",
"success_url": "https://mystore.com/success",
"failure_url": "https://mystore.com/failure",
"product_type": "aplazo_bnpl"
}
}]
}'
using System.Collections.Generic;
using System.Diagnostics;
using Conekta.net.Api;
using Conekta.net.Client;
using Conekta.net.Model;
namespace Example
{
public class CreateOrderExample
{
public static void Main()
{
Configuration config = new Configuration();
config.AccessToken = "key_DwaOLXoX6YCGGvfNifZ3IPwi";
List<Product> products = new()
{
new(
name: "toshiba",
quantity: 1,
unitPrice: 15555
)
};
PaymentMethodBnplRequest request = new(
type: "bnpl",
productType: PaymentMethodBnplRequest.ProductTypeEnum.AplazoBnpl,
successUrl: "https://www.tu-sitio.com/success",
cancelUrl: "https://www.tu-sitio.com/cancel",
failureUrl: "https://www.tu-sitio.com/failure"
);
List<ChargeRequest> charges = new()
{
new(
paymentMethod: new ChargeRequestPaymentMethod(request)
)
};
OrderRequestCustomerInfo customerInfo = new(new CustomerInfoJustCustomerId("cus_2tKcHxhTz7xU5SymF"));
OrderRequest orderRequest = new(
currency: "MXN",
customerInfo: customerInfo,
lineItems: products,
charges: charges,
preAuthorize: false
);
instance = new OrdersApi(config);
OrderResponse response = instance.CreateOrder(orderRequest, "es");
}
}
}
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Conekta\Api\OrdersApi;
use Conekta\Configuration;
use Conekta\Model\OrderRequest;
$config = Configuration::getDefaultConfiguration()->setAccessToken(getenv("CONEKTA_API_KEY"));
$apiInstance = new OrdersApi(null, $config);
$rq = new OrderRequest([
'line_items' => [
[
'name' => 'Nombre del Producto o Servicio',
'unit_price' => 23000,
'quantity' => 1
]
],
'currency' => 'MXN',
'customer_info' => [
'name' => 'Jorge Martinez',
'email' => '[email protected]',
'phone' => '+5218181818181'
],
'metadata' => [
'datos_extra' => '12334'
],
'charges' => [
[
'payment_method' => [
'type' => 'bnpl',
'product_type' => 'aplazo_bnpl',
'success_url' => 'https://www.tu-sitio.com/success',
'failure_url' => 'https://www.tu-sitio.com/failure',
'cancel_url' => 'https://www.tu-sitio.com/cancel'
]
]
]
]);
try {
$result = $apiInstance->createOrder($rq);
$json_string = json_encode($result, JSON_PRETTY_PRINT);
print_r($json_string);
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->createOrder: ', $e->getMessage(), PHP_EOL;
}
# Load the gem
require 'conekta'
class OneTimeChargeBnpl
Conekta.configure do |config|
config.access_token = ENV['CONEKTA_API_KEY']
end
api_instance = Conekta::OrdersApi.new
order_request = Conekta::OrderRequest.new(
:currency => 'MXN',
:line_items => [
{
:name => 'Box of Cohiba S1s',
:unit_price => 35000,
:quantity => 1
}
],
:customer_info => {
:name => 'Mario Hernandez',
:email => '[email protected]',
:phone => '5555555555'
},
:charges => [
{
:payment_method => Conekta::PaymentMethodBnplRequest.new(
:expires_at => Time.now.advance(days: 30).to_i,
:product_type => 'creditea_bnpl',
:type => 'bnpl',
:success_url => 'https://www.example.com/success',
:failure_url => 'https://www.example.com/failure',
:cancel_url => 'https://www.example.com/cancel'
)
}
]
)
opts = {
accept_language: 'es' # String | Use for knowing which language to use
}
begin
result = api_instance.create_order(order_request, opts)
p result
rescue Conekta::ApiError => e
puts "Exception when calling create order #{e}"
end
end
import time
import os
import conekta
from conekta.rest import ApiException
from pprint import pprint
# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.
# Configure Bearer authorization: bearerAuth
configuration = conekta.Configuration(
access_token = os.environ["CONEKTA_PRIVATE_API_KEY"]
)
# Enter a context with an instance of the API client
with conekta.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = conekta.OrdersApi(api_client)
order = conekta.OrderRequest(
line_items=[
conekta.Product(
name='Test Product',
quantity=1,
unit_price=10000
)
],
customer_info=conekta.OrderRequestCustomerInfo(
conekta.CustomerInfo(
name='John Doe',
email='[email protected]',
phone='555-555-5555'
)
),
currency='MXN',
charges=[
conekta.ChargeRequest(
payment_method=conekta.ChargeRequestPaymentMethod(
oneof_schema_1_validator=conekta.PaymentMethodBnplRequest(
product_type='aplazo_bnpl',
type= 'bnpl',
success_url= 'https://www.example.com/success',
failure_url= 'https://www.example.com/failure',
cancel_url= 'https://www.example.com/cancel',
)
)
)
]
)
accept_language = 'es' # str | Use for knowing which language to use (optional) (default to 'es')
try:
# Create order
api_response = api_instance.create_order(order, accept_language=accept_language)
print("The response of OrdersApi->create_order:\n")
pprint(api_response)
except ApiException as e:
print("Exception when calling OrdersApi->create_order: %s\n" % e)
ApiClient defaultClient = Configuration.getDefaultApiClient();
HttpBearerAuth bearerAuth = (HttpBearerAuth) defaultClient.getAuthentication("bearerAuth");
bearerAuth.setBearerToken(System.getenv("CONEKTA_PRIVATE_KEY"));
final OrdersApi api = new OrdersApi(defaultClient);
OrderRequest orderRequest = new OrderRequest();
ChargeRequest chargeRequest = new ChargeRequest();
PaymentMethodBnplRequest paymentMethodBnplRequest = new PaymentMethodBnplRequest()
.type("bnpl")
.productType(PaymentMethodBnplRequest.ProductTypeEnum.APLAZO_BNPL)
.successUrl("https://www.successurl.com/success")
.cancelUrl("https://www.cancelurl.com/cancel")
.failureUrl("https://www.failureurl.com/failure");
ChargeRequestPaymentMethod chargeRequestPaymentMethod = new ChargeRequestPaymentMethod();
chargeRequestPaymentMethod.setActualInstance(paymentMethodBnplRequest);
chargeRequest.setPaymentMethod(chargeRequestPaymentMethod);
List<ChargeRequest> charges = new ArrayList<>();
charges.add(chargeRequest);
orderRequest.setCharges(charges);
orderRequest.currency("MXN");
List<Product> products = new ArrayList<>();
products.add(new Product()
.name("test")
.tags(new ArrayList<>(List.of("valor1", "valor2", "valor3")))
.quantity(1)
.unitPrice(500000));
orderRequest.lineItems(products);
OrderRequestCustomerInfo customer = new OrderRequestCustomerInfo();
customer.setActualInstance(new CustomerInfo()
.name("test")
.email("[email protected]")
.phone("3143159054"));
orderRequest.setCustomerInfo(customer);
List<ShippingRequest> shippingLines = new ArrayList<>();
shippingLines.add(new ShippingRequest()
.amount(550L)
.method("Standard")
.carrier("Conekta")
.trackingNumber("1234567890"));
orderRequest.shippingLines(shippingLines);
orderRequest.shippingContact(new CustomerShippingContacts()
.phone("3143159054")
.receiver("fran carrero")
.address(new CustomerShippingContactsAddress()
.city("cdmx")
.country("mx")
.postalCode("06100")
.state("cdmx")
.street1("calle 123")));
OrderResponse response = api.createOrder(orderRequest, "es", null);
System.out.println(response);
configuration := openapiclient.NewConfiguration()
ctx := context.WithValue(context.TODO(), openapiclient.ContextAccessToken, os.Getenv("CONEKTA_PRIVATE_KEY"))
apiClient := openapiclient.NewAPIClient(configuration)
phone := "31431590545"
name := "fran carrero"
OrderRequest := openapiclient.OrderRequest{
Charges: []openapiclient.ChargeRequest{
{
PaymentMethod: openapiclient.ChargeRequestPaymentMethod{PaymentMethodBnplRequest: &openapiclient.PaymentMethodBnplRequest{
Type: "bnpl",
CancelUrl: "https://example.com/cancel",
FailureUrl: "https://example.com/failure",
ProductType: "creditea_bnpl",
SuccessUrl: "https://example.com/success",
}},
},
},
Currency: "MXN",
CustomerInfo: openapiclient.OrderRequestCustomerInfo{},
LineItems: []openapiclient.Product{
{
UnitPrice: 5000,
Quantity: 1,
Name: "Test Product",
Tags: []string{"test", "product"},
},
},
ShippingContact: &openapiclient.CustomerShippingContacts{
Phone: &phone,
Receiver: &name,
Address: openapiclient.CustomerShippingContactsAddress{
Street1: openapiclient.PtrString("123 Main St"),
Street2: openapiclient.PtrString("Apt 4B"),
City: openapiclient.PtrString("Mexico City"),
State: openapiclient.PtrString("CDMX"),
PostalCode: openapiclient.PtrString("01234"),
Country: openapiclient.PtrString("MX"),
},
},
ShippingLines: []openapiclient.ShippingRequest{
{
Carrier: openapiclient.PtrString("DHL"),
TrackingNumber: openapiclient.PtrString("123456789"),
Amount: 1000,
},
},
}
resp, _, _ := apiClient.OrdersAPI.CreateOrder(ctx).OrderRequest(OrderRequest).AcceptLanguage("es").Execute()
fmt.Println(resp)
3. Procesar respuesta
Una vez creada la orden y el cargo, deberás procesar la respuesta y compartir el redirect_url
al cliente final .
Recuerda que la respuesta de una orden es formato _JSON_.
Console.WriteLine($"Order ID: {response.Id}");
Console.WriteLine($"redirect url: {response.Charges.Data[0].PaymentMethod.GetPaymentMethodBnplPayment().RedirectUrl}");
Console.WriteLine($"type: {response.Charges.Data[0].PaymentMethod.GetPaymentMethodBnplPayment().Type}");
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
System.out.println(response);
System.out.println("order id " + response.getId());
System.out.println("redirect url " + response.getCharges().getData().get(0).getPaymentMethod().getPaymentMethodBnplPayment().getRedirectUrl());
System.out.println("type " + response.getCharges().getData().get(0).getPaymentMethod().getPaymentMethodBnplPayment().getType());
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
$order = $apiInstance->createOrder($rq);
$json_string = json_encode( $order, JSON_PRETTY_PRINT);
print_r($json_string);
print("order id" . $order->getId());
print("redirect url" . $order->getCharges()->getData()[0]->getPaymentMethod()->getRedirectUrl());
print("type" . $order->getCharges()->getData()[0]->getPaymentMethod()->getType());
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
p result
p result.id
p result.charges.data[0].payment_method.bnpl_payment.redirect_url
p result.charges.data[0].payment_method.bnpl_payment.type
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
pprint("order id", response.id)
pprint("redirect_url", response.charges.data[0].payment_method.actual_instance.redirect_url)
pprint("type", response.charges.data[0].payment_method.actual_instance.type)
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
System.out.println(response);
System.out.println("order id " + response.getId());
System.out.println("redirect url " + response.getCharges().getData().get(0).getPaymentMethod().getPaymentMethodBnplPayment().getRedirectUrl());
System.out.println("type " + response.getCharges().getData().get(0).getPaymentMethod().getPaymentMethodBnplPayment().getType());
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
fmt.Println(resp)
fmt.Println("order id:", resp.Id)
fmt.Println("redirect_url:", resp.Charges.Data[0].PaymentMethod.PaymentMethodBnplPayment.RedirectUrl)
fmt.Println("type:", resp.Charges.Data[0].PaymentMethod.PaymentMethodBnplPayment.Type)
//Response
//ID: ord_2nCsbdLXvdAgDVcKr
//direct_url: https://provider.bnpl.mx/main/3d5ec65b-f33d-4111-9ba2-ce0dd973321e
//type: bnpl
Notificaciones vía webhook
Esta modalidad de pago a través de tarjeta tiene comunicación directa vía API para cada uno de los momentos de la transacción. Lo que significa que a cada request hay un response exitoso o fallido inmediato con el que puedes conciliar automáticamente.
Sin embargo, todos los eventos que ocurran antes, durante y después de una transacción pueden ser notificados a través de webhooks, justo en el momento en que ocurren. Te en listamos todos los eventos que intervienen en esta modalidad, accediendo al siguiente enlace para revisar el detalle del payload correspondiente a cada uno de ellos, y mapearlos para llevar a cabo los procesos internos de tu negocio requeridos.
Te recomendamos capturar los siguientes eventos:
Evento | Descripción |
---|---|
order.paid | Enviado cuando el cliente completa un pago de forma exitosa |
order.pending_payment | Enviado cuando una orden es creada pero está pendiente de pago |
order.canceled | Enviado cuando el pago de una orden es cancelado. |
Updated 1 day ago