| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace HBank; |
| 6 | |
| 7 | /** |
| 8 | * HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only if |
| 9 | * you answer 200 with {"resume": true} as application/json within 10 seconds. |
| 10 | * |
| 11 | * It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback URLs) |
| 12 | * before you approve: fromRequest($secret) does, or verifySignature(). Also check that `id` and `amount` match an order |
| 13 | * you created, and confirm with getPayment() before handing out goods. |
| 14 | * |
| 15 | * // Plain PHP (refuses a callback without a valid signature) |
| 16 | * $cb = \HBank\Callback::fromRequest(getenv('HBANK_CALLBACK_SECRET')); |
| 17 | * \HBank\Callback::respond($orders->matches($cb->id, $cb->amount) ? \HBank\Callback::approve() : \HBank\Callback::refuse('Out of stock')); |
| 18 | * |
| 19 | * // Laravel (exclude the route from CSRF protection) |
| 20 | * Route::post('/hbank/callback', function (Request $request) { |
| 21 | * abort_unless(\HBank\Callback::verifySignature($secret, $request->header('HBank-Signature'), $request->getContent()), 400); |
| 22 | * $cb = \HBank\Callback::parse($request->getContent()); |
| 23 | * return response()->json(Order::matches($cb->id, $cb->amount) ? \HBank\Callback::approve() : \HBank\Callback::refuse('Out of stock')); |
| 24 | * }); |
| 25 | */ |
| 26 | final class Callback |
| 27 | { |
| 28 | /** $amount is the exact decimal text, e.g. "24.90"; compare it with bccomp() or your decimal type. */ |
| 29 | public function __construct( |
| 30 | public readonly string $id, |
| 31 | public readonly string $amount, |
| 32 | public readonly string $currency, |
| 33 | public readonly string $status, |
| 34 | public readonly string $description, |
| 35 | ) { |
| 36 | } |
| 37 | |
| 38 | /** Reads a callback body. Throws HBankException("invalid_callback") if it isn't one. */ |
| 39 | public static function parse(string $body): self |
| 40 | { |
| 41 | // Quote bare numbers first so amounts keep their exact digits. |
| 42 | $exact = preg_replace('/("amount"\s*:\s*)(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/', '$1"$2"', $body); |
| 43 | $d = json_decode((string) $exact, true, 16, JSON_BIGINT_AS_STRING); |
| 44 | if (!is_array($d) || !isset($d['id'], $d['amount'], $d['currency']) || !(is_string($d['id']) || is_int($d['id'])) || $d['id'] === '' || !is_numeric($d['amount'])) { |
| 45 | throw new HBankException('invalid_callback', 0, 'missing or invalid id, amount or currency'); |
| 46 | } |
| 47 | return new self((string) $d['id'], (string) $d['amount'], (string) $d['currency'], |
| 48 | (string) ($d['status'] ?? ''), (string) ($d['description'] ?? '')); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Reads the current request's body (php://input). With $secret, its HBank-Signature must be valid first: otherwise |
| 53 | * it throws HBankException("invalid_callback"). |
| 54 | */ |
| 55 | public static function fromRequest(?string $secret = null): self |
| 56 | { |
| 57 | $body = (string) file_get_contents('php://input'); |
| 58 | if ($secret !== null && !self::verifySignature($secret, $_SERVER['HTTP_HBANK_SIGNATURE'] ?? null, $body)) { |
| 59 | throw new HBankException('invalid_callback', 0, 'bad or missing HBank-Signature'); |
| 60 | } |
| 61 | return self::parse($body); |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Whether $header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs $body (the raw request body, exactly |
| 66 | * as received) with $secret, and was made within $tolerance seconds of $now (default: now). |
| 67 | */ |
| 68 | public static function verifySignature(string $secret, ?string $header, string $body, int $tolerance = 300, ?int $now = null): bool |
| 69 | { |
| 70 | if ($secret === '' || $header === null || $header === '') { |
| 71 | return false; |
| 72 | } |
| 73 | $parts = []; |
| 74 | foreach (explode(',', $header) as $part) { |
| 75 | $kv = explode('=', $part, 2); |
| 76 | if (count($kv) === 2) { |
| 77 | $parts[$kv[0]] ??= $kv[1]; |
| 78 | } |
| 79 | } |
| 80 | $t = $parts['t'] ?? ''; |
| 81 | if (!preg_match('/^\d{1,18}$/', $t) || abs(($now ?? time()) - (int) $t) > $tolerance) { |
| 82 | return false; |
| 83 | } |
| 84 | return hash_equals(hash_hmac('sha256', $t . '.' . $body, $secret), (string) ($parts['v1'] ?? '')); |
| 85 | } |
| 86 | |
| 87 | /** Lets HBank charge the customer. */ |
| 88 | public static function approve(): array |
| 89 | { |
| 90 | return ['resume' => true]; |
| 91 | } |
| 92 | |
| 93 | /** Refuses the payment; the customer sees $error. */ |
| 94 | public static function refuse(?string $error = null): array |
| 95 | { |
| 96 | return $error === null ? ['resume' => false] : ['resume' => false, 'error' => $error]; |
| 97 | } |
| 98 | |
| 99 | /** Sends the answer (status 200, application/json) for plain PHP. */ |
| 100 | public static function respond(array $answer): void |
| 101 | { |
| 102 | http_response_code(200); |
| 103 | header('Content-Type: application/json'); |
| 104 | echo json_encode($answer, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
| 105 | } |
| 106 | } |