审查生成的支付边界

来自 异常
PHP 8.3.33 高级 6分钟 找出 5处问题

在这段生成的结账边界处理支付请求前,对它进行审查。

要求金额为正整数;调用网关时不要持有数据库事务;事务开始后遇到任何 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');
    }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误