Actualizar un Payment Intent
Actualiza un Payment Intent para modificar sus datos antes de que se confirme y se pague.
Endpoint
PATCH /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 actualiza (por ejemplo 550e8400-e29b-41d4-a716-446655440000). |
Cuerpo de la petición
Todos los campos son opcionales. Incluye solo los campos que quieras actualizar.
{
"amount": "150.00",
"currency": "usd",
"description": "Updated payment description",
"metadata": {
"order_id": "12345",
"updated_at": "2024-01-01T12:00:00Z"
},
"return_url": "https://merchant.example.com/new-return",
"cancel_url": "https://merchant.example.com/new-cancel",
"withdrawal_addresses": { "evm": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" }
}
Parámetros
| Parámetro | Tipo | Obligatorio | Descripción |
|---|---|---|---|
amount | string | No | Actualiza el importe a cobrar. Debe ser un número positivo. |
currency | string | No | Actualiza el código de moneda. |
description | string | No | Actualiza la descripción. |
metadata | object | No | Actualiza los metadatos. Se combinan con los metadatos existentes. |
return_url | string | No | Actualiza la URL de retorno. |
cancel_url | string | No | Actualiza la URL de cancelación. |
withdrawal_addresses | object | No | Direcciones de retiro por tipo de cadena. Omítelo para usar el valor por defecto de tu cuenta. |
:::warning Nota
Solo puedes actualizar un Payment Intent si su estado es requires_payment_method o requires_confirmation. Cuando un pago está en processing o succeeded, ya no se puede actualizar.
:::
Respuesta
Respuesta correcta
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"amount": "150.00",
"currency": "usd",
"status": "requires_payment_method",
"paymentMethodTypes": ["crypto"],
"returnUrl": "https://merchant.example.com/new-return",
"cancelUrl": "https://merchant.example.com/new-cancel",
"description": "Updated payment description",
"metadata": {
"order_id": "12345",
"updated_at": "2024-01-01T12:00:00Z"
},
"paymentLink": {
"id": 1,
"link": "https://pay.orcarail.com/pay/pl_abc123"
},
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T12:00:00.000Z"
}
Ejemplo
cURL
curl https://api.orcarail.com/api/v1/payment_intents/550e8400-e29b-41d4-a716-446655440000 \
-X PATCH \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": "150.00",
"description": "Updated payment description"
}'
JavaScript (Node.js)
const paymentIntentId = '550e8400-e29b-41d4-a716-446655440000'
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
method: 'PATCH',
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: '150.00',
description: 'Updated payment description',
metadata: {
order_id: '12345',
updated_at: new Date().toISOString(),
},
}),
}
)
const updatedIntent = await response.json()
console.log('Updated Amount:', updatedIntent.amount)
Python
import requests
payment_intent_id = '550e8400-e29b-41d4-a716-446655440000'
response = requests.patch(
f'https://api.orcarail.com/api/v1/payment_intents/{payment_intent_id}',
headers={
'Authorization': f'Bearer {jwt_token}',
'Content-Type': 'application/json',
},
json={
'amount': '150.00',
'description': 'Updated payment description',
'metadata': {
'order_id': '12345',
'updated_at': '2024-01-01T12:00:00Z',
},
},
)
updated_intent = response.json()
print(f"Updated Amount: {updated_intent['amount']}")
PHP (SDK)
$updated = $orcarail->paymentIntents->update('550e8400-e29b-41d4-a716-446655440000', [
'amount' => '150.00',
'description' => 'Updated payment description',
'metadata' => ['order_id' => '12345'],
]);
echo $updated->amount;
Consulta SDK de PHP para configurar el cliente.
Casos de uso
Actualizar el importe tras cambios en el carrito
Si un cliente modifica su carrito antes de pagar, actualiza el importe del Payment Intent:
async function updateCartTotal(paymentIntentId, newAmount) {
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
method: 'PATCH',
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: newAmount.toFixed(2),
}),
}
)
return await response.json()
}
Añadir metadatos tras crear el pedido
Añade información del pedido a los metadatos del Payment Intent:
async function addOrderMetadata(paymentIntentId, orderId) {
const response = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
method: 'PATCH',
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
metadata: {
order_id: orderId,
created_at: new Date().toISOString(),
},
}),
}
)
return await response.json()
}
Gestión de errores
Si intentas actualizar un Payment Intent que ya se ha pagado o se está procesando, recibirás un error:
{
"statusCode": 400,
"message": "Cannot update Payment Intent with status 'succeeded'",
"error": "Bad Request"
}
Comprueba siempre el estado del Payment Intent antes de intentar actualizarlo:
async function safeUpdatePaymentIntent(paymentIntentId, updates) {
// First, retrieve the current Payment Intent
const getResponse = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`,
},
}
)
const currentIntent = await getResponse.json()
// Check if update is allowed
const allowedStatuses = ['requires_payment_method', 'requires_confirmation']
if (!allowedStatuses.includes(currentIntent.status)) {
throw new Error(
`Cannot update Payment Intent with status '${currentIntent.status}'`
)
}
// Proceed with update
const updateResponse = await fetch(
`https://api.orcarail.com/api/v1/payment_intents/${paymentIntentId}`,
{
method: 'PATCH',
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
}
)
return await updateResponse.json()
}
Próximos pasos
- Confirmar el Payment Intent: tras actualizarlo, confírmalo para obtener la URL de redirección
- Obtener el Payment Intent: comprueba los datos actualizados