<?php
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Payments\CapturesRefundRequest;
use PayPalCheckoutSdk\Payments\RefundsGetRequest;
$environment = new SandboxEnvironment(
getenv('PAYPAL_CLIENT_ID'),
getenv('PAYPAL_CLIENT_SECRET')
);
$client = new PayPalHttpClient($environment);
// Process refund
$app->post('/api/captures/{captureID}/refund', function ($request, $response, $args) use ($client) {
$captureID = $args['captureID'];
$body = $request->getParsedBody();
$refundRequest = new CapturesRefundRequest($captureID);
// Set refund amount if provided
if (isset($body['amount'])) {
$refundRequest->body = [
"amount" => [
"value" => $body['amount'],
"currency_code" => "USD"
],
"note_to_payer" => $body['note'] ?? "Refund processed"
];
}
try {
$refundResponse = $client->execute($refundRequest);
$refund = $refundResponse->result;
$response->getBody()->write(json_encode([
"id" => $refund->id,
"status" => $refund->status,
"amount" => $refund->amount->value
]));
return $response->withHeader('Content-Type', 'application/json');
} catch (HttpException $e) {
$statusCode = $e->statusCode;
$errorData = json_decode($e->getMessage(), true);
if ($statusCode === 422) {
$issue = $errorData['details'][0]['issue'] ?? '';
if ($issue === 'CAPTURE_FULLY_REFUNDED') {
$response->getBody()->write(json_encode([
"error" => "Cannot refund - already refunded"
]));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
} else if ($issue === 'REFUND_AMOUNT_EXCEEDED') {
$response->getBody()->write(json_encode([
"error" => "Refund amount exceeds available balance"
]));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
}
$response->getBody()->write(json_encode([
"error" => $e->getMessage()
]));
return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
}
});
// Get refund status
$app->get('/api/refunds/{refundID}', function ($request, $response, $args) use ($client) {
$refundID = $args['refundID'];
try {
$refundRequest = new RefundsGetRequest($refundID);
$refundResponse = $client->execute($refundRequest);
$refund = $refundResponse->result;
$response->getBody()->write(json_encode([
"id" => $refund->id,
"status" => $refund->status,
"amount" => $refund->amount->value
]));
return $response->withHeader('Content-Type', 'application/json');
} catch (Exception $e) {
$response->getBody()->write(json_encode([
"error" => "Refund not found"
]));
return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
}
});