php 实现applepay
实现 Apple Pay 的 PHP 后端流程
Apple Pay 的后端实现主要涉及验证支付令牌、处理支付请求以及与支付网关交互。以下是关键步骤:
验证 Apple Pay 支付令牌
支付令牌由前端传递到后端,需要通过 Apple 的证书进行验证。使用 openssl 解密令牌:

$paymentData = json_decode($applePayToken, true);
$header = $paymentData['header'];
$signature = base64_decode($paymentData['signature']);
$data = $paymentData['data'];
$certificate = openssl_x509_read(file_get_contents('ApplePay证书路径'));
$publicKey = openssl_pkey_get_public($certificate);
$isValid = openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA256);
处理支付请求
验证通过后,提取支付信息并传递给支付网关(如 Stripe、Braintree):
$decryptedData = json_decode(base64_decode($data), true);
$cardNumber = $decryptedData['applicationPrimaryAccountNumber'];
$expiry = $decryptedData['applicationExpirationDate'];
$amount = $_POST['amount'];
与支付网关集成
以 Stripe 为例,使用其 PHP SDK 完成支付:

\Stripe\Stripe::setApiKey('STRIPE_SECRET_KEY');
$charge = \Stripe\Charge::create([
'amount' => $amount * 100,
'currency' => 'usd',
'source' => $applePayToken,
]);
处理支付结果
根据网关返回的结果更新订单状态:
if ($charge->status === 'succeeded') {
// 更新订单为支付成功
$order->updateStatus('paid');
} else {
// 处理失败情况
log_error("Payment failed: " . $charge->failure_message);
}
生成 merchant session
若需 Apple Pay 直接认证,调用 Apple 的 API 生成 merchant session:
$merchantId = 'MERCHANT_ID';
$domain = 'YOUR_DOMAIN';
$sessionUrl = "https://apple-pay-gateway.apple.com/paymentservices/startSession";
$requestData = [
'merchantIdentifier' => $merchantId,
'domainName' => $domain,
'displayName' => 'Your Store Name'
];
$ch = curl_init($sessionUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
$response = curl_exec($ch);
$merchantSession = json_decode($response, true);
注意事项
- 确保证书(.pem 文件)从 Apple Developer 后台正确下载并配置。
- 支付网关需支持 Apple Pay(如 Stripe、Braintree、Adyen)。
- 前端需通过
ApplePaySession完成用户交互,后端仅处理验证和支付请求。 - 生产环境需使用 HTTPS 并配置 CSP 以符合 Apple Pay 安全要求。






