paypal

package
v0.29.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package paypal 实现 ploykit billing 的 PayPal 支付渠道 (billing/app.PaymentChannel),走 PayPal Subscriptions + Catalog Products REST API(目录型渠道家族,与 waffo 同类;BC-8 = 框架成色的试金石, 零内核改动接入):

POST /v1/oauth2/token                                 OAuth2 取 token(Basic auth,缓存到 expiry-60s)
POST /v1/catalogs/products                            建 product(PROD-xxx,RegisterProduct 第一步)
POST /v1/billing/plans                                建 plan(P-xxx,RegisterProduct 第二步;status=ACTIVE 直接可用)
POST /v1/billing/plans/{id}/update-pricing-schemes   改价(SyncPrice;204 空响应)
POST /v1/billing/subscriptions                        创建订阅结账(APPROVAL_PENDING + rel=approve 链接)
POST /v1/billing/subscriptions/{id}/cancel            取消订阅(reason 必填,1-128 字符)
POST /v1/notifications/verify-webhook-signature       webhook 验签(七字段,五头一 ID 一原始事件)
POST /webhooks/billing/paypal(产品仓路由)           接收 PayPal 事件推送

环境:mode=test → api-m.sandbox.paypal.com,mode=prod → api-m.paypal.com (PAYPAL_API_BASE 可覆盖,测试指向 httptest server)。沙箱与生产是两套 完全独立的 App(client id/secret/webhook id 各一套),PayPal 事件载荷不携带 mode 标记 —— 五律 5 的跨环境隔离由凭据天然分离保证(沙箱回调打到生产配置 的 webhook id 上,验签必败),渠道自身配置的 mode 记入事件 Payload 供审计。

订阅标识:checkout 会话的 SessionRef = 订阅 id(SUB-xxx),随 SetOrderChannelRefAndExpiry 落 order.channel_ref;custom_id = ploykit 订单号, BILLING.SUBSCRIPTION.* 事件原样回传(订单反查键);PAYMENT.SALE.* 事件的 billing_agreement_id = 订阅 id(订阅家族事件与销售家族事件的汇合点)。

价格(目录型渠道的第二家族特征,与 waffo 的差异点):PayPal 订阅**没有会话级 改价** —— 收款价就是 plan 的 pricing_scheme.fixed_price,DB 改价后必须 SyncPrice 推到 PayPal plan,否则用户按旧价付款、amountMismatch 拒发权益 (SALE 事件金额 != 订单金额)。CreateCheckout 只带 plan_id,不带任何价格。

事件映射(→ ploykit domain.PaymentEvent,五律执行):

BILLING.SUBSCRIPTION.ACTIVATED → checkout.completed(OrderID=custom_id,
  SubscriptionRef=订阅 id,AmountCents=0:订阅对象不携带金额,amountMismatch
  对 0 走忽略路径,首期金额对账交给同拍的 SALE 事件)
PAYMENT.SALE.COMPLETED         → subscription.renewed(SubscriptionRef=
  billing_agreement_id,AmountCents=resource.amount(total/value 双形态),
  PaymentIntentRef=sale id 供退款反查)
BILLING.SUBSCRIPTION.CANCELLED → subscription.canceled(SubscriptionRef=订阅 id)
PAYMENT.SALE.REFUNDED          → refund.created(AmountCents=resource.amount
  或 total_refunded_amount 兜底,PaymentIntentRef=resource.sale_id)
其余(SUSPENDED/EXPIRED/UPDATED/CREATED/DISPUTE.*/PAYMENT.FAILED…) → ignored

Index

Constants

View Source
const (
	EnvClientID     = "PAYPAL_CLIENT_ID"
	EnvClientSecret = "PAYPAL_CLIENT_SECRET"
	EnvWebhookID    = "PAYPAL_WEBHOOK_ID"
	EnvMode         = "PAYPAL_MODE"
	EnvAPIBase      = "PAYPAL_API_BASE" // 测试覆盖(指向 httptest server);生产留空按 mode 选
)

环境变量名(密钥一律走 env 或 BC-5 后台落库,绝不入日志)。

View Source
const (
	FieldClientID     = "client_id"
	FieldClientSecret = "client_secret"
	FieldWebhookID    = "webhook_id"
	FieldMode         = "mode"
)

ConfigSchema 字段键(BC-5/BC-6:后台渠道卡的表单字段名,同时是 billing_channel.paypal.<field> 设置键与 NewFromFields 的 fields 键)。

View Source
const (
	ModeTest = "test"
	ModeProd = "prod"
)

渠道模式常量(BC-4 五律 5;waffo 同款词汇表:test/prod)。

View Source
const (
	SandboxAPIBase = "https://api-m.sandbox.paypal.com"
	LiveAPIBase    = "https://api-m.paypal.com"
)

API 主机(https://developer.paypal.com/api/rest/authentication/): 沙箱 api-m.sandbox.paypal.com,生产 api-m.paypal.com。

Variables

This section is empty.

Functions

func Caps added in v0.14.0

func Caps() app.ChannelCaps

Caps 是包级能力声明单一真源:实例方法与 DisabledChannel 桩共用(未配置 paypal 的后台卡片排序/币种声明与真渠道一致)。

func FromEnv

func FromEnv(getenv func(string) string, log *slog.Logger, production bool) (app.PaymentChannel, error)

FromEnv 从环境装配渠道,纪律照抄 waffo.FromEnv:四个必填变量 (client_id+client_secret+webhook_id+mode)全缺 = 未配置,返回 *app.DisabledChannel 桩(后台渠道页可见可贴密钥,活动渠道集 /config 不含它);缺任何一个 = 配置事故 —— production 直接报错拒启 (收银台半残等于丢钱),dev 打 warn 降级为桩,不挡本地开发。 返回类型是 app.PaymentChannel 接口直返:typed-nil 陷阱(nil *Channel 包成非 nil 接口)从签名上消失,调用方无需再判 nil 重包装。

func NewFromFields

func NewFromFields(fields map[string]string, getenv func(string) string, log *slog.Logger, production bool) (app.PaymentChannel, error)

NewFromFields 按 BC-5 装配:字段值(fields,键=ConfigSchema 字段名,来自 billing_channel.paypal.* 设置行)优先,缺失回退进程 env(env-only 老接法 不断)。与 FromEnv 的纪律差异:webhook_id/mode 不再必填 —— DB 渐进配置期 允许先通收银台后贴 webhook id(半残态由 ChannelConfig().WebhookConfigured 如实暴露),mode 缺省 test(沙箱安全方向:配错只炸收银台,不会拿沙箱 密钥打到生产 API);client_id+client_secret 仍全缺=未配置(返回 DisabledChannel 桩,后台渠道页可见可贴密钥)、缺一报错(production 拒启/dev 降级为桩),与 waffo.NewFromFields 同哲学。返回类型是 app.PaymentChannel 接口直返 —— typed-nil 陷阱从签名上消失。

func Schema added in v0.14.0

func Schema() []app.FieldSpec

Schema 是包级 ConfigSchema 单一真源(BC-6):实例方法、DisabledChannel 桩 (FromEnv/NewFromFields 未配置分支)、后台渠道卡的表单渲染共用此描述符, 字段键同时是 billing_channel.paypal.<field> 设置键与 NewFromFields 的 fields 键 —— 三处一份真源。

Types

type Channel

type Channel struct {
	// contains filtered or unexported fields
}

Channel 实现 app.PaymentChannel。不实现 CheckoutCanceller —— PayPal 没有作废 APPROVAL_PENDING 订阅的公开端点,放任过期即可(ploykit 的 CancelPendingOrder 对未实现该接口的渠道直接跳过,弃单由 OrderExpiryWorker 按 CheckoutSession.ExpiresAt 清扫)。

func New

func New(cfg Config) (*Channel, error)

New 校验并构造渠道。client 凭据缺失立刻报错 —— 半配置不能等到第一笔 收款才发现。webhook_id 可空(验签必败的半残态在 ChannelConfig 可见)。

func (*Channel) CancelSubscription

func (c *Channel) CancelSubscription(ctx context.Context, providerSubID string) error

CancelSubscription 实现 app.SubscriptionCanceller。providerSubID 就是我们 落的 SubscriptionRef = PayPal 订阅 id(SUB-xxx,billing_agreement_id 与之 同值)。成功 = 204 空响应。

func (*Channel) Capabilities

func (c *Channel) Capabilities() app.ChannelCaps

func (*Channel) ChannelConfig

func (c *Channel) ChannelConfig() app.ChannelConfigInfo

ChannelConfig 进 billing 配置面:webhook id 未配时如实标未配置 —— 收银台能开但回调验签必败,运营必须看得见这个半残态。

func (*Channel) ConfigSchema

func (c *Channel) ConfigSchema() []app.FieldSpec

func (*Channel) CreateCheckout

func (c *Channel) CreateCheckout(ctx context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)

func (*Channel) EnvProvidedKeys

func (c *Channel) EnvProvidedKeys() []string

EnvProvidedKeys 返回进程 env 当前已提供(os.Getenv 非空)的本渠道配置键, 键名与 ConfigSchema 的 Key 一致(client_id/client_secret/webhook_id/ mode;env 变量名映射见 paypal.go 的 envOfField)。billing/app 的 ChannelEnvViewer 接口按鸭子类型断言本方法,配置面据此实现「env 已提供 即豁免 Required 校验」—— 环境注入过的字段不在后台表单标红。输出按 ConfigSchema 字段序(map 遍历无序,别让下游断言抖动)。

func (*Channel) Name

func (c *Channel) Name() string

func (*Channel) ParseWebhook

func (c *Channel) ParseWebhook(ctx context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)

ParseWebhook 先调 PayPal 验签 API(五头一 ID 一原始事件),SUCCESS 才进入 事件映射;网络错误或非 SUCCESS 一律算验签失败(ploykit 回 401,不落库)。 五律 4:ChannelEventID = event_type + ":" + id —— 幂等键 (channel, channel_event_id) 无事件类型维度,而 PayPal 资源 id(SUB-xxx/sale id) 会在同一对象的不同事件间复用,不拼类型会把后到的合法事件当重复吞掉。

func (*Channel) RegisterProduct

func (c *Channel) RegisterProduct(ctx context.Context, plan domain.Plan, interval domain.BillingInterval) (string, error)

RegisterProduct 实现 app.ProductRegistrar:两步链 —— 取 product(先列 目录按 name+type 查重复用,未命中才建 PROD-xxx,SERVICE)→ 建 plan (P-xxx,status=ACTIVE,固定价=当前 DB 价),返回 **plan id**(对 paypal 而言渠道商品 = plan,CreateCheckout 的 ChannelProductID 就是它)。

product 层幂等:服务层 GetChannelProduct 先查映射是第一道闸,但映射行 丢失(库换过/手滑删)或首注册半途失败(建完 product、建 plan 报错, 映射未落)后重试时,无查重的 POST 会在 PayPal 目录堆孤儿 product —— 建前先 GET /v1/catalogs/products 按名查重,命中即复用其 id 再建 plan。 plan 层每次新建(PayPal plan 没有业务幂等键;映射由服务层在两步都 成功后落,失败的孤儿 plan 不进映射即不可见)。

func (*Channel) SyncPrice

func (c *Channel) SyncPrice(ctx context.Context, channelProductID string, plan domain.Plan, interval domain.BillingInterval) error

SyncPrice 实现 app.ProductRegistrar:把 plan 当前 DB 价推给已注册 plan (BC-7 改价联动)。**对 paypal 这是刚性依赖**:订阅无会话级改价,不同步 就是按旧价收款 → amountMismatch 拒付。

func (*Channel) TestConnection

func (c *Channel) TestConnection(ctx context.Context) error

TestConnection 取一次 OAuth token 即探活:2xx = client id/secret 正确、 网络通、API 主机选对(mode);401 = 凭据错(INVALID_CLIENT)。没有更便宜的 无副作用读 —— PayPal 的 hello 端点也要 Bearer。

type Client

type Client struct {
	ClientID     string
	ClientSecret string
	BaseURL      string
	HTTP         *http.Client
	// contains filtered or unexported fields
}

Client 是带 OAuth2 token 缓存的 PayPal REST 客户端 (https://developer.paypal.com/api/rest/):

POST /v1/oauth2/token
  Authorization: Basic base64(client_id:client_secret)
  Content-Type: application/x-www-form-urlencoded
  body: grant_type=client_credentials
  → {"access_token":"...","token_type":"Bearer","expires_in":32400,...}

之后每个 API 请求带 Authorization: Bearer <token>。token 进程内缓存 (锁保护,并发取一次),到期前 margin 即刷新。

type Config

type Config struct {
	ClientID     string // 开发者后台 App 的 Client ID(sandbox/live 两套)
	ClientSecret string // 与 Client ID 配对的 secret
	WebhookID    string // 开发者后台 App 的 Webhook ID;为空则 webhook 验签必败(半残态:收银台能开、回调进不来)
	Mode         string // 空 = test(沙箱安全缺省);"test"/"prod"
	APIBase      string // 空 = 按 Mode 选;测试指向 httptest server
}

Config 组装渠道所需的全部外部输入。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL