将 Stripe webhooks 与 graphql-yoga 和 Prisma 结合使用

Mar*_*iel 2 webhooks express stripe-payments graphql prisma

我在寻找如何拦截应用程序中的 Stripe webhook 调用时遇到了一些困难。我使用 graphql-yoga (express) 和 prisma。

我必须监听来自 Stripe 的付款失败呼叫,以便我可以编辑相应的用户配置文件。

谢谢您的帮助!

Stripe webhook 调用如下所示:

{
  "created": 1326853478,
  "id": "charge.expired_00000000000000",
  "type": "charge.expired",
  "object": "event",
  "request": null,
  "pending_webhooks": 1,
  "data": {
    "object": {
      "id": "ch_00000000000000",
      "object": "charge",
      "amount": 100,
      "captured": false,
      "created": 1537153592,
      "currency": "usd",
      "customer": null,
      "description": "My First Test Charge (created for API docs)",
      "invoice": null,
      "livemode": false,
      "on_behalf_of": null,
      "order": null,
      "outcome": null,
      "paid": true,
      "receipt_email": null,
      "receipt_number": null,
      "refunded": false,
      "review": null,
      "shipping": null,
      "source": {
        "id": "card_00000000000000",
        "object": "card",
        "address_city": null,
        "address_country": null,
        "address_line1": null,
        "address_line1_check": null,
        "address_line2": null,
        "address_state": null,
        "address_zip": "12919",
        "address_zip_check": "pass",
        "brand": "Visa",
        "country": "US",
        "customer": "cus_00000000000000",
        "cvc_check": null,
        "name": null,
        "tokenization_method": null
      },
      "statement_descriptor": null,
      "status": "succeeded",
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

wsw*_*wsw 6

POST由于 Stripe Webhook 返回带有负载的通用 http JSON,因此它不会event根据Graphql语言查询格式化数据。

目前,您可以做的是使用 的 [0] 公开普通的APIREST端点Graphql-Yogaexpress

我编写了一个工作示例代码,您可以尝试一下

const { GraphQLServer } = require('graphql-yoga')
const typeDefs = `
  type Query {
    hello(name: String): String!
  }
`
const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}`,
  },
}

const server = new GraphQLServer({ typeDefs, resolvers, skipValidation: true })
server.express.use('/api/stripe/webhooks', (req, res) => {
    // Handle your callback here !!!!
    res.status(200).send();
})

server.start(() => console.log('Server is running on localhost:4000'))
Run Code Online (Sandbox Code Playgroud)

如果以上内容有帮助,请告诉我。

[0] https://github.com/prisma/graphql-yoga#how-to-eject-from-the-standard-express-setup

  • 实际上,Stripe webhook 有一个重试机制,以防您的服务器出现故障。如果您的服务器宕机,它将重试长达 72 小时 (https://stripe.com/docs/webhooks#responding-to-a-webhook)(希望您的服务器不会宕机那么久:))。但你绝对可以使用“无服务器”方法,解析响应并将“webhook”代理到与架构匹配的“Graphql”端点 (2认同)
  • 这很棒,但是如何访问 Express 服务器内的“ctx”变量呢? (2认同)