在这段生成的结账边界处理支付请求前,对它进行审查。
要求金额为正整数;调用网关时不要持有数据库事务;事务开始后遇到任何 Throwable 都要回滚;日志不得包含秘密;转换失败时要保留原因。
php
<?php
final class PaymentGateway {
public function charge(int $cents, string $token): string {
return 'PAY-7';
}
}
function checkout(PDO $db, PaymentGateway $gateway, array $request): string
{
$db->beginTransaction();
try {
$amount = (int) ($request['amount_cents'] ?? 0);
$paymentId = $gateway->charge($amount, $request['token']);
$db->commit();
return $paymentId;
} catch (Exception $error) {
$db->rollBack();
error_log($error->getMessage() . ' token=' . $request['token']);
throw new RuntimeException('Checkout failed');
}
}
生成代码仅作示例,不代表任何特定模型