Obtener un Payment Intent
Obtén los detalles de un Payment Intent para comprobar su estado y conseguir información actualizada.
Endpoint
GET /api/v1/payment_intents/:id
Autenticación
Este endpoint admite ambos métodos de autenticación:
- Token Bearer (JWT):
Authorization: Bearer YOUR_JWT_TOKEN - Clave de API (Basic Auth):
Authorization: Basic base64(key:secret)
Petición
Parámetros de ruta
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
id | string | Sí | El ID del Payment Intent que se obtiene (por ejemplo 550e8400-e29b-41d4-a716-446655440000). |
Respuesta
Respuesta correcta
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"amount": "100.00",
"currency": "usd",
"status": "succeeded",
"paymentMethodTypes": ["crypto"],
"returnUrl": "https://merchant.example.com/return",
"cancelUrl": "https://merchant.example.com/cancel",
"description": "Payment for services",
"metadata": {
"order_id": "12345",
"customer_id": "67890"
},
"paymentLink": {
"id": 1,
"link": "https://pay.orcarail.com/pay/pl_abc123"
},
"latestTransaction": {
"id": "txn_1234567890",
"status": "completed",
"amount": "100.00",
"currency": "usd",
"hash": "0x1234567890abcdef...",
"createdAt": "2024-01-01T00:00:00.000Z"
},
"expiresAt": null,
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
Campos de la respuesta
| Campo | Tipo | Descripción |
|---|---|---|
id | string | Identificador único del Payment Intent. |
amount | string | El importe cobrado. |
currency | string | El código de moneda. |
status | string | Estado actual del Payment Intent. Consulta Valores de estado más abajo. |
paymentMethodTypes | array | Array de tipos de método de pago usados. |
returnUrl | string | La URL de retorno indicada. |
cancelUrl | string | La URL de cancelación (si se indicó). |
description | string | La descripción (si se proporcionó). |
metadata | object | Los metadatos (si se proporcionaron). |
paymentLink | object | El objeto del enlace de pago con la URL de pago. |
latestTransaction | object | La transacción más reciente asociada a este Payment Intent. |
latestTransaction.id | string | ID de la transacción. |
latestTransaction.status | string | Estado de la transacción. |
latestTransaction.amount | string | Importe de la transacción. |
latestTransaction.currency | string | Moneda de la transacción. |
latestTransaction.hash | string | Hash de la transacción en la blockchain (si se ha completado). |
expiresAt | string | null | Cuándo caduca el Payment Intent (si se indicó). |
createdAt | string | Cuándo se creó el Payment Intent. |
updatedAt | string | Cuándo se actualizó por última vez el Payment Intent. |
Valores de estado
| Estado | Descripción |
|---|---|
requires_payment_method | El PaymentIntent se ha creado, pero aún no tiene un método de pago asociado. |
requires_confirmation | El PaymentIntent tiene un método de pago asociado, pero hay que confirmarlo. |
processing | El PaymentIntent se está procesando en la blockchain. |
succeeded | El PaymentIntent se ha completado y el pago se ha procesado. |
canceled | El PaymentIntent se ha cancelado. |
Ejemplo
cURL
curl https://api.orcarail.com/api/v1/payment_intents/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
JavaScript (Node.js)
const paymentIntentId = '550e8400-e29b-41d4-a716-446655440000'
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
)
const paymentIntent = await response.json()
console.log('Status:', paymentIntent.status)
console.log('Amount:', paymentIntent.amount)
if (paymentIntent.status === 'succeeded') {
console.log('Transaction Hash:', paymentIntent.latestTransaction?.hash)
}
Python
import requests
payment_intent_id = '550e8400-e29b-41d4-a716-446655440000'
response = requests.get(
f'https://api.orcarail.com/api/v1/payment_intents/{payment_intent_id}',
headers={
'Authorization': f'Bearer {jwt_token}',
},
)
payment_intent = response.json()
print(f"Status: {payment_intent['status']}")
print(f"Amount: {payment_intent['amount']}")
if payment_intent['status'] == 'succeeded':
print(f"Transaction Hash: {payment_intent['latestTransaction']['hash']}")
PHP (SDK)
$intent = $orcarail->paymentIntents->retrieve('550e8400-e29b-41d4-a716-446655440000');
echo $intent->status;
echo $intent->amount;
echo $intent->latest_transaction?->hash;
Consulta SDK de PHP para configurar el cliente.
Casos de uso
Comprobar el estado del pago tras la redirección
Cuando el cliente vuelva a tu return_url, obtén el Payment Intent para comprobar si el pago se ha completado:
// Extract from URL query params
const urlParams = new URLSearchParams(window.location.search)
const paymentIntentId = urlParams.get('payment_intent')
if (paymentIntentId) {
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
)
const paymentIntent = await response.json()
switch (paymentIntent.status) {
case 'succeeded':
// Payment completed successfully
showSuccessMessage()
fulfillOrder(paymentIntent.metadata.order_id)
break
case 'processing':
// Payment is being processed
showProcessingMessage()
break
case 'canceled':
// Payment was canceled
showCanceledMessage()
break
default:
// Handle other statuses
showErrorMessage()
}
}
Consultar periódicamente el estado
Si no usas webhooks, puedes consultar periódicamente el endpoint del Payment Intent para ver los cambios de estado:
async function pollPaymentStatus(paymentIntentId, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
)
const paymentIntent = await response.json()
if (paymentIntent.status === 'succeeded') {
return { success: true, paymentIntent }
}
if (paymentIntent.status === 'canceled') {
return { success: false, paymentIntent }
}
// Wait 2 seconds before next poll
await new Promise((resolve) => setTimeout(resolve, 2000))
}
return { success: false, error: 'Timeout' }
}
Próximos pasos
- Actualizar un Payment Intent: modifica los datos del pago antes de confirmarlo
- Configurar webhooks: recibe actualizaciones de estado en tiempo real en lugar de consultar