<?php
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Payments\AuthorizationsVoidRequest;
$environment = new SandboxEnvironment(
getenv('PAYPAL_CLIENT_ID'),
getenv('PAYPAL_CLIENT_SECRET')
);
$client = new PayPalHttpClient($environment);
// Void an authorization
$app->post('/api/authorizations/{authID}/void', function ($request, $response, $args) use ($client) {
$authID = $args['authID'];
$voidRequest = new AuthorizationsVoidRequest($authID);
try {
$voidResponse = $client->execute($voidRequest);
$authorization = $voidResponse->result;
$response->getBody()->write(json_encode([
"id" => $authorization->id,
"status" => $authorization->status
]));
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 === 'AUTHORIZATION_ALREADY_CAPTURED') {
$response->getBody()->write(json_encode([
"error" => "Cannot void - already captured. Use refund instead."
]));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
} else if ($issue === 'AUTHORIZATION_VOIDED') {
$response->getBody()->write(json_encode([
"error" => "Authorization already voided"
]));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
} else {
$response->getBody()->write(json_encode([
"error" => "Invalid authorization state"
]));
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');
}
});