Apollo Server:如何为 Stripe webhook 添加自定义端点?

Apollo Server: How can I add a custom endpoint for Stripe webhook?

我有一个 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'));

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