lua-resty-stripe
Stripe API for OpenResty
$ opm get gnois/lua-resty-stripe
lua-resty-stripe
安装
opm add gnois\lua-resty-stripe
概述
local rhttp = require("resty.http")
local stripe = require("resty.stripe")
local ApiKey = "..." -- your stripe api key
local api = stripe(rhttp.new(), ApiKey))
local status, headers_or_err, subs = api.subscriptions.get(subscription_id)
if status < 300 then
-- process subscription...
end
API
API 列表紧密遵循 Stripe 参考文档 中的 REST 端点。
对于创建和修改 API(HTTP POST 端点),我们可以提供一个 Idempotency-Key
HTTP 头作为最后一个参数,如果出现错误并且 Stripe-Should-Retry
头设置为 true,则将启用 3 次重试,如 低级错误处理 文档中所述。
Webhook
Stripe webhook 指南 文档介绍了将 Stripe 通知处理到应用程序中的步骤。
假设我们正在使用 Losty,以下是我们在应用程序中创建 webhook 端点以接收这些通知的方式。
local web = require('losty.web')() -- instantiate once
local body = require('losty.body')
local content = require('losty.content')
local wh = require('stripe_webhook')
local WebhookSecret = "whsec_nM......gu"
local w = web.route()
w.post('/stripe-webhook', content.json, function(q, r)
local raw = body.raw(q)
local event, err = wh.events(raw, q.headers['stripe-signature'], WebhookSecret)
if not event then
ngx.log(ngx.ERR, err)
r.status = 400
else
local obj = event.data.object
if 'customer.created' == event.type then
local uid = obj.metadata['user.id']
if uid then
-- link user id to stripe customer id in database ...
r.status = 200
else
r.status = 400
return {fail = "invalid metadata tenant.id"}
end
end
end
end)
添加更多 API
API 列表目前并不全面,因为我只添加了需要的 API。欢迎随时提交请求。
从 Stripe 参考文档 添加新 API 非常容易,尽管它使用的是 (Luaty)[https://github.com/gnois/luaty]。
例如,查看 SetupIntents 的参考文档,我们可以看到有 Create
、Retrieve
、Update
、Confirm
、Cancel
和 List all
操作。这些操作的端点可以直接转换为代码,如下所示
var SetupIntents = "setup_intents"
K.setup_intents = {
get = \id, opt -> return get(SetupIntents, id, opt)
, create = \... -> return create(SetupIntents, ...)
, update = \id, ... -> return post(SetupIntents, id, ...)
, confirm = \id, ... -> return post(SetupIntents, id .. "/confirm", ...)
, cancel = \id, ... -> return post(SetupIntents, id .. "/cancel", ...)
, list = \opt -> return list(SetupIntents, opt)
}
需要注意一些模式
Stripe REST 端点仅使用 HTTP 动词 GET 和 POST
HTTP GET 通常用于
列出
所有项目或获取
一个项目,这通常需要一个 ID。HTTP POST 用于
创建
新项目或发布
对项目的更改,这通常需要一个 ID,有时还会后跟操作名称,例如confirm
或cancel
,如上所示。create
和post
函数接受可变参数,因为可以传递带有幂等键的 HTTP 头。
尽情享受!
作者
gnois
许可证
mit
版本
-
gnois/lua-resty-stripe 0.1.1Stripe API for OpenResty 2022-08-16 03:16:40
-
Stripe API for OpenResty 2022-08-16 02:50:55