【问题标题】:Apollo Server: How can I add a custom endpoint for Stripe webhook?Apollo Server:如何为 Stripe webhook 添加自定义端点?
【发布时间】:2020-07-02 18:30:29
【问题描述】:

我有一个 graphql 服务器,我想为其添加一个自定义端点,以便当客户的订阅状态发生变化时,Stripe 可以与其通信。

目前,我的 index.js 文件看起来像一个典型的 Apollo 服务器设置:

import { ApolloServer } from "apollo-server";
import { connectDb } from "./models";

import schema from "./schema";
import resolvers from "./resolvers";
import contexts from "./contexts";

const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
  context: async ({ req }) => {
    const { getCurrentUser } = contexts;

    const currentUser = await getCurrentUser(req);
    return { models, currentUser };
  },
});

connectDb().then(async () => {
  server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
    console.log(`????  Server ready at ${url}`);
  });
});

所以只有/graphql 暴露了。

如何添加一个自定义的POST /foobar 端点来做类似的事情? (来源:https://stripe.com/docs/webhooks/build#example-code)

// This example uses Express to receive webhooks
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  let event;

  try {
    event = JSON.parse(request.body);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      // Then define and call a method to handle the successful payment intent.
      // handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));

【问题讨论】:

    标签: node.js graphql apollo-server


    【解决方案1】:

    您需要从 apollo-server 迁移到 apollo-server-express。然后您可以添加您需要的任何其他端点。如果您不想使用 Express,也可以使用其他任何 available integrations。

    【讨论】:

    • 太棒了,我会调查的。谢谢!
    • @bigpatato 嗨,你能帮我解决这个问题吗?我想要相同的:/ 我不能添加特定的端点我的阿波罗服务器
    猜你喜欢
    • 2021-06-10
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2013-06-08
    • 2023-03-26
    相关资源
    最近更新 更多