gpt4 book ai didi

node.js - Apollo 服务器 : How can I add a custom endpoint for Stripe webhook?

转载 作者:行者123 更新时间:2023-12-02 19:37:46 25 4
gpt4 key购买 nike

我有一个 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 .

关于node.js - Apollo 服务器 : How can I add a custom endpoint for Stripe webhook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60794161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com