Stripe webhook 在调用 Vercel 无服务器函数时返回 308 错误。

huangapple go评论88阅读模式
英文:

Stripe webhook returning 308 error when calling Vercel serverless function

问题

我已经使用Stripe设置了一个Webhook,当触发时调用一个无服务器函数。

该函数旨在在调用时更新我的数据库中的条目,表示用户已注册了高级帐户。

当我在本地运行时,Webhook工作得很完美。它触发API,更新用户并处理付款。

然而,当在线上运行时,我不断收到308错误,显示:

重定向到my-app-url.com

以下是我的函数代码:

import { buffer } from "micro";
import { createClient } from "@supabase/supabase-js";

require("dotenv").config();

const stripe = require("stripe")(process.env.STRIPE_LIVE_KEY);

const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;

const supabaseUrl = process.env.REACT_APP_SUPABASE_URL;
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY;

const supabase = createClient(supabaseUrl, supabaseAnonKey);

module.exports = async (req, res) => {

   const signature = req.headers["stripe-signature"];
   const reqBuffer = await buffer(req);

   let event 

   try {
    event = stripe.webhooks.constructEvent(reqBuffer, signature, endpointSecret);
   } catch (err) {
    console.log(err);
    return res.status(400).send(`Webhook error: ${err.message}`);
   }

   if (event.type === "checkout.session.completed") {
    console.log("Checkout completed!");
    const userId = String(event.data.object.client_reference_id);

    console.log(userId);

    const { error } = await supabase.from('profiles').update({ premium: 'true' }).eq('id', userId); 
    
    if (error) {
      console.log(error);
    }
   }

   res.send({ received: true });
}

当我检查我的函数日志时,似乎它甚至没有触发/达到我的API - 没有日志记录。

是否有人有任何建议?

英文:

I've set up a webhook with Stripe, which calls a serverless function when it's triggered.

The function is intended to update an entry in my database when it's called, suggesting that a user has signed up for a premium account.

When I run this locally, the webhook works perfectly. It triggers the API, updates the user and processes the payment.

However, when it gets run on live, I continually get a 308 error saying:

> Redirecting to my-app-url.com

Here's the code for my function:

import { buffer } from "micro"
import { createClient } from "@supabase/supabase-js";

require("dotenv").config();

const stripe = require("stripe")(process.env.STRIPE_LIVE_KEY)

const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET

const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY

const supabase = createClient(supabaseUrl, supabaseAnonKey)

module.exports = async (req, res) => {

   const signature = req.headers["stripe-signature"]
   const reqBuffer = await buffer(req)

   let event 

   try {
    event = stripe.webhooks.constructEvent(reqBuffer, signature, endpointSecret)
   } catch (err) {
    console.log(err)
    return res.status(400).send(`Webhook error: ${err.message}`)
   }

   if (event.type === "checkout.session.completed") {
    console.log("Checkout completed!")
    const userId = String(event.data.object.client_reference_id)

    console.log(userId)

    const { error } = await supabase.from('profiles').update({ premium: 'true' }).eq('id', userId) 
    
    if (error) {
      console.log(error)
    }
   }

   res.send({ received: true })
}

When I check my function logs, it just seems like it's not even firing / reaching my API at all - there's no logs.

Does anyone have any suggestions?

答案1

得分: 5

问题是Vercel中的默认域名重定向。

推荐的方法是重定向到www,所以你应该使用以下格式:

错误:https://[YOUR_DOMAIN].com/api/endpoint

正确:https://www.[YOUR_DOMAIN].com/api/endpoint

祝好!

英文:

The problem is the default domain redirect in Vercel.

The recommended way is to redirect to www, so this is the format you should use:

Wrong: https://[YOUR_DOMAIN].com/api/endpoint

Right: https://www.[YOUR_DOMAIN].com/api/endpoint

Cheers

答案2

得分: 2

对于我的情况,结果是我忘记了末尾的斜杠。

所以,我不是像这样调用Stripe监听器:

stripe listen --forward-to localhost:4242/webhook/

而是像这样调用:

stripe listen --forward-to localhost:4242/webhook

没有末尾的斜杠,导致服务器重定向请求到正确的路径,从而出现了308状态代码。

英文:

For my case, it turns out I forgot the trailing slash.

So instead of calling the stripe listener like this:

stripe listen --forward-to localhost:4242/webhook/

I was calling it like this:

stripe listen --forward-to localhost:4242/webhook

Without the / at the end, causing the server to redirect the request to the correct path, and thus the 308 status code.

答案3

得分: 1

根据308错误显示,似乎您的服务器已收到了Webhook请求,但试图将其重定向到另一个URL。可能甚至是相同的URL,但使用HTTPS。Stripe无法跟随重定向,因此这是您服务器端的配置错误。您必须提供服务器期望接收Webhook的确切URL。

英文:

As the 308 error indicates, it looks like your server is receiving the webhook, but attempting to redirect it to another URL. It's possible that it's even the same URL, but over HTTPS.

Stripe can't follow redirects so this is a misconfiguration on your server's end. You have to give the exact URL for where your server expects to receive webhooks.

huangapple
  • 本文由 发表于 2023年1月10日 03:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75062050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定