Integra Buyesia Pay en tu aplicación usando nuestra API REST sin necesidad de SDK.
Para usar la API REST, necesitas autenticarte usando tus credenciales de cliente. Estas credenciales se obtienen al crear una cuenta de comerciante en nuestro sistema.
// Autenticación con la API
$ch = curl_init('http://pay.buyesia.com/merchant/api/verify');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'client_id' => 'tu_client_id', // Obtén esto desde tu panel de comerciante
'client_secret' => 'tu_client_secret' // Obtén esto desde tu panel de comerciante
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
$token = json_decode($response)->data->access_token;
Para crear una nueva transacción, envía una solicitud POST con los detalles del pago.
// Crear una nueva transacción
$ch = curl_init('http://pay.buyesia.com/merchant/api/transaction-info');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'payer' => 'Nombre del Pagador',
'amount' => 100.00,
'currency' => 'USD',
'successUrl' => 'https://tu-sitio-web.com/success',
'cancelUrl' => 'https://tu-sitio-web.com/cancel',
'order_no' => 'ORD-12345',
'item_name' => 'Descripción del Producto'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $token
]);
$response = curl_exec($ch);
$transaction = json_decode($response);
// Redirigir al usuario a la página de pago
header('Location: ' . $transaction->data->approvedUrl);
Después de un pago exitoso, el usuario será redirigido a la URL de éxito con los detalles de la transacción codificados en Base64.
// Ejemplo de URL de redirección exitosa
$successUrl = 'https://tu-sitio-web.com/success';
// Ejemplo de datos decodificados que recibirás
$transactionData = [
'status' => 200,
'transaction_id' => 'TRX123456',
'merchant' => 'Nombre del Comerciante',
'currency' => 'USD',
'fee' => 0.015,
'amount' => 0.985,
'total' => 1,
'order_no' => 'ORD-12345',
'item_name' => 'Descripción del Producto'
];
Aquí hay un ejemplo completo de integración usando PHP.
// Configuración inicial
$apiUrl = 'http://pay.buyesia.com';
$clientId = 'tu_client_id'; // Obtén esto desde tu panel de comerciante
$clientSecret = 'tu_client_secret'; // Obtén esto desde tu panel de comerciante
// 1. Autenticación
$ch = curl_init($apiUrl . '/merchant/api/verify');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'client_id' => $clientId,
'client_secret' => $clientSecret
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
$token = json_decode($response)->data->access_token;
// 2. Crear transacción
$ch = curl_init($apiUrl . '/merchant/api/transaction-info');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'payer' => 'Nombre del Pagador',
'amount' => 100.00,
'currency' => 'USD',
'successUrl' => 'https://tu-sitio-web.com/success',
'cancelUrl' => 'https://tu-sitio-web.com/cancel',
'order_no' => 'ORD-12345',
'item_name' => 'Descripción del Producto'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $token
]);
$response = curl_exec($ch);
$transaction = json_decode($response);
// 3. Redirigir al usuario a la página de pago
header('Location: ' . $transaction->data->approvedUrl);
La API devuelve códigos de estado HTTP estándar.
// Ejemplo de manejo de errores
try {
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
throw new Exception('Error en la solicitud: ' . $httpCode);
}
$data = json_decode($response);
if (!$data || !isset($data->status) || $data->status !== 'success') {
throw new Exception('Error en la respuesta: ' . ($data->message ?? 'Error desconocido'));
}
} catch (Exception $e) {
// Manejar el error apropiadamente
error_log($e->getMessage());
// Mostrar mensaje al usuario
echo 'Ha ocurrido un error: ' . $e->getMessage();
}
Los webhooks te permiten recibir notificaciones en tiempo real sobre eventos importantes en tu cuenta.
// Configuración del webhook
// 1. Configura la URL de tu webhook en el panel de control del merchant
// 2. Recibirás notificaciones con una firma HMAC-SHA256
// Estructura del webhook recibido
{
"event": "payment.success",
"payload": {
"transaction_id": "uuid-de-la-transaccion",
"order_no": "ORD-12345",
"item_name": "Nombre del producto",
"amount": 1.00,
"currency": "USD",
"status": "success",
"timestamp": "2024-03-23T12:34:56Z"
},
"timestamp": 1234567890
}
// Headers del webhook
X-Webhook-Signature: [firma-hmac-sha256]
Content-Type: application/json
// Validación del webhook
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'];
$payload = file_get_contents('php://input');
$expectedSignature = hash_hmac('sha256', $payload, $client_secret);
if (hash_equals($signature, $expectedSignature)) {
$data = json_decode($payload, true);
// Procesar el evento
}
Los siguientes eventos están disponibles para los webhooks:
// Eventos disponibles
[
'payment.success', // Pago completado exitosamente
'payment.failed', // Pago fallido
'payment.refunded' // Pago reembolsado
]
Crea una cuenta de comerciante en nuestro sistema
Obtén tus credenciales (client_id y client_secret) desde el panel de comerciante
Implementa el código de ejemplo en tu aplicación
Para una implementación segura y robusta:
Información importante sobre la codificación y seguridad de los webhooks:
// Detalles de codificación y seguridad
// 1. Codificación JSON
// - El payload se codifica en JSON con soporte Unicode
// - Se usa JSON_UNESCAPED_UNICODE para caracteres especiales
$jsonPayload = json_encode($fullPayload, JSON_UNESCAPED_UNICODE);
// 2. Firma HMAC-SHA256
// - Se genera una firma usando el payload JSON completo
// - Se usa el client_secret como clave de firma
$signature = hash_hmac('sha256', $jsonPayload, $client_secret);
// 3. Headers requeridos
// - X-Webhook-Signature: [firma-hmac-sha256]
// - Content-Type: application/json
// 4. Estructura del payload
{
"event": "payment.success",
"payload": {
// Datos específicos del evento
},
"timestamp": 1234567890
}
// 5. Validación recomendada
if (!isset($_SERVER['HTTP_X_WEBHOOK_SIGNATURE'])) {
http_response_code(400);
exit('Firma no proporcionada');
}
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'];
$payload = file_get_contents('php://input');
$expectedSignature = hash_hmac('sha256', $payload, $client_secret);
if (!hash_equals($signature, $expectedSignature)) {
http_response_code(401);
exit('Firma inválida');
}
Aspectos importantes a considerar en la implementación: