如何在Node.js中验证PayPal Webhooks?旧代码是否已过时?
PayPal Webhook 验证:旧代码状态与最新方案
旧代码是否过时?
是的,你提供的2015年PayPal Node SDK代码已完全过时,原因如下:
- 该SDK仓库已被PayPal官方归档,不再维护,无后续安全更新或功能迭代
- 旧SDK依赖的部分逻辑虽可能暂时可用,但官方已停止技术支持
- 当前PayPal Webhook验证有更规范、安全的实现标准
最新推荐方案
PayPal官方目前推荐两种Webhook签名验证方式:
方式1:使用官方最新Node.js SDK
采用@paypal/checkout-server-sdk(支持Webhook相关操作),示例代码如下:
const paypal = require('@paypal/checkout-server-sdk'); // 初始化环境(沙箱/生产) const environment = new paypal.core.SandboxEnvironment('你的客户端ID', '你的客户端密钥'); const client = new paypal.core.PayPalHttpClient(environment); // Webhook验证逻辑 async function verifyWebhookEvent(headers, requestBody, webhookId) { const verifyRequest = new paypal.notifications.WebhookEventVerifyRequest() .headers(headers) .requestBody({ auth_algo: headers['paypal-auth-algo'], cert_url: headers['paypal-cert-url'], transmission_id: headers['paypal-transmission-id'], transmission_sig: headers['paypal-transmission-sig'], transmission_time: headers['paypal-transmission-time'], webhook_id: webhookId, webhook_event: JSON.parse(requestBody) }); try { const response = await client.execute(verifyRequest); if (response.result.verification_status === 'SUCCESS') { console.log('Webhook签名验证通过'); // 处理合法的Webhook事件 } else { console.log('Webhook签名验证失败'); } } catch (error) { console.error('验证出错:', error); } }
方式2:直接调用REST API验证
不依赖SDK时,可直接调用PayPal REST API端点完成验证:
const axios = require('axios'); async function verifyWebhookViaAPI(headers, requestBody, webhookId, clientId, clientSecret) { // 获取访问令牌 const tokenResponse = await axios.post('https://api.sandbox.paypal.com/v1/oauth2/token', 'grant_type=client_credentials', { auth: { username: clientId, password: clientSecret }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ); const accessToken = tokenResponse.data.access_token; // 发起验证请求 const verifyResponse = await axios.post( 'https://api.sandbox.paypal.com/v1/notifications/verify-webhook-signature', { auth_algo: headers['paypal-auth-algo'], cert_url: headers['paypal-cert-url'], transmission_id: headers['paypal-transmission-id'], transmission_sig: headers['paypal-transmission-sig'], transmission_time: headers['paypal-transmission-time'], webhook_id: webhookId, webhook_event: JSON.parse(requestBody) }, { headers: { 'Authorization': `Bearer ${accessToken}` } } ); if (verifyResponse.data.verification_status === 'SUCCESS') { console.log('验证通过'); } else { console.log('验证失败'); } }
关键注意事项
- 必须使用HTTPS接收Webhook事件,保障传输安全
- 验证时需完整传递PayPal发送的所有相关请求头,不可遗漏
- 生产环境需将沙箱API端点替换为
https://api.paypal.com - 仅在验证通过后处理Webhook事件内容,防范恶意请求
内容的提问来源于stack exchange,提问作者antonwilhelm
相关产品推荐
相关产品推荐

