PayPal:安全 REST API 支付集成 - Openclaw Skills

作者:互联网

2026-04-06

AI教程

什么是 PayPal?

Openclaw Skills 的 PayPal 集成技能为开发人员实现可靠的支付处理提供了一个稳健的框架。它通过提供 OAuth 令牌管理、环境特定配置和安全结账实施的结构化模式,简化了 PayPal REST API 的复杂性。通过遵循此技能中概述的最佳实践,开发人员可以确保其支付集成既安全又具可扩展性。

该技能通过强制要求服务器端验证和基于 API 的 Webhook 验证来强调安全性。它有助于防止常见陷阱,如客户端篡改、重复的 Webhook 处理和货币小数错误,使其成为构建生产级金融科技应用程序的重要资源。

下载入口:https://github.com/openclaw/skills/tree/main/skills/ivangdavila/paypal

安装与下载

1. ClawHub CLI

从源直接安装技能的最快方式。

npx clawhub@latest install paypal

2. 手动安装

将技能文件夹复制到以下位置之一

全局模式 ~/.openclaw/skills/ 工作区 /skills/

优先级:工作区 > 本地 > 内置

3. 提示词安装

将此提示词复制到 OpenClaw 即可自动安装。

请帮我使用 Clawhub 安装 paypal。如果尚未安装 Clawhub,请先安装(npm i -g clawhub)。

PayPal 应用场景

  • 为电子商务应用程序构建安全的结账流程。
  • 实施定期订阅计费和生命周期管理。
  • 通过安全的 Webhook 通知处理实时订单更新。
  • 管理向供应商或服务提供商的自动付款。
  • 开发争议和退款管理系统。
PayPal 工作原理
  1. 通过在沙盒(Sandbox)和生产(Production)API 端点之间进行选择来初始化环境。
  2. 实施 OAuth 2.0 流程以获取并每 8 小时自动刷新访问令牌。
  3. 将交易意图定义为 CAPTURE(立即付款)或 AUTHORIZE(延迟资金归集)。
  4. 在客户端批准后执行服务器端验证,以核实订单状态、金额和商户 ID。
  5. 配置一个 Webhook 器,使用 PayPal API 验证签名并使用幂等逻辑处理事件。

PayPal 配置指南

要开始在 Openclaw Skills 中进行此 PayPal 集成,请准备您的开发人员凭据并配置您的环境。

# 安装必要的环境依赖项
npm install @paypal/checkout-server-sdk

# 设置环境变量
export PAYPAL_CLIENT_ID='your_client_id'
export PAYPAL_CLIENT_SECRET='your_secret'
export PAYPAL_MODE='sandbox' # 或 'live'

PayPal 数据架构与分类体系

该技能组织支付数据和元数据,以确保整个 API 生命周期的一致性。它使用以下数据结构:

属性 类型 描述
intent 字符串 定义支付操作(CAPTURE 与 AUTHORIZE)
purchase_units 数组 包含金额详情和货币代码(字符串形式)
webhook_event 对象 从 PayPal 通知中收到的原始事件主体
verification_status 字符串 强制性 API 签名检查的结果(例如 SUCCESS)
order_status 枚举 跟踪订单生命周期:CREATED、APPROVED、COMPLETED
name: PayPal
slug: paypal
version: 1.0.0
description: Integrate PayPal payments with proper webhook verification, OAuth handling, and security validation for checkout flows and subscriptions.
metadata: {"clawdbot":{"emoji":"??","requires":{"bins":[]},"os":["linux","darwin","win32"]}}

When to Use

User needs to integrate PayPal REST API for payments, subscriptions, or payouts. Agent handles checkout flows, webhook verification, OAuth token management, and dispute workflows.

Quick Reference

Topic File
Code patterns patterns.md
Webhook events webhooks.md

Core Rules

1. Environment URLs are Different

  • Sandbox: api.sandbox.paypal.com
  • Production: api.paypal.com
  • Ask which environment BEFORE generating code
  • Credentials are environment-specific — never mix

2. OAuth Token Management

// Token expires ~8 hours — handle refresh
const getToken = async () => {
  const res = await fetch('https://api.paypal.com/v1/oauth2/token', {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${Buffer.from(`${clientId}:${secret}`).toString('base64')}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'grant_type=client_credentials'
  });
  return res.json(); // { access_token, expires_in }
};

Never hardcode tokens. Implement refresh logic.

3. Webhook Verification is Mandatory

PayPal webhooks MUST be verified via API call — not simple HMAC:

// POST /v1/notifications/verify-webhook-signature
const verification = await fetch('https://api.paypal.com/v1/notifications/verify-webhook-signature', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    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: WEBHOOK_ID,
    webhook_event: body
  })
});
// verification_status === 'SUCCESS'

4. CAPTURE vs AUTHORIZE — Ask First

Intent Behavior
CAPTURE Charges immediately on approval
AUTHORIZE Reserves funds, capture later (up to 29 days)

Changing intent after integration breaks the entire flow.

5. Server-Side Validation — Never Trust Client

// After client approves, VERIFY on server before fulfillment
const order = await fetch(`https://api.paypal.com/v2/checkout/orders/${orderId}`, {
  headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json());

// Validate ALL of these:
if (order.status !== 'APPROVED') throw new Error('Not approved');
if (order.purchase_units[0].amount.value !== expectedAmount) throw new Error('Amount mismatch');
if (order.purchase_units[0].amount.currency_code !== expectedCurrency) throw new Error('Currency mismatch');
if (order.purchase_units[0].payee.merchant_id !== YOUR_MERCHANT_ID) throw new Error('Wrong merchant');

6. Idempotency in Webhooks

PayPal may send the same webhook multiple times:

const processed = await db.webhooks.findOne({ eventId: body.id });
if (processed) return res.status(200).send('Already processed');
await db.webhooks.insert({ eventId: body.id, processedAt: new Date() });
// Now process the event

7. Currency Decimal Rules

Some currencies have NO decimal places:

Currency Decimals Example
USD, EUR 2 "10.50"
JPY, TWD 0 "1050" (NOT "1050.00")

Sending "10.50" for JPY = API error.

Common Traps

  • IPN vs Webhooks — IPN is legacy. Use Webhooks for new integrations. Never mix.
  • Order states — CREATED → APPROVED → COMPLETED (or VOIDED). Handle ALL states, not just happy path.
  • Decimal confusion — PayPal uses strings for amounts ("10.50"), not floats. Some currencies forbid decimals.
  • Sandbox rate limits — Lower than production. Don't assume prod will fail the same way.
  • Payout vs Payment — Payouts API is separate. Don't confuse sending money (Payouts) with receiving (Orders).

相关推荐