如何在Docker配置中运行Revin要求的stripe webhook创建命令?
解决Docker环境下Stripe Webhook创建问题
一、stripe webhook_endpoints create在Dockerfile中执行失败的原因
直接在Dockerfile里添加该命令会踩几个坑:
- 镜像构建阶段可能未安装Stripe CLI,或未配置
STRIPE_API_KEY等必要环境变量 - 构建过程中容器通常没有网络访问权限,无法调用Stripe的远程API
- 该命令属于一次性配置操作,不需要嵌入到镜像构建流程中
二、Docker环境下的正确执行方式
1. 先在镜像中安装Stripe CLI
在Dockerfile.studio中添加安装步骤(以Debian/Ubuntu基础镜像为例):
RUN apt-get update && apt-get install -y curl RUN curl -s https://packages.stripe.dev/api/security/keypair/stripe-cli-gpg/public | gpg --dearmor | tee /usr/share/keyrings/stripe.gpg RUN echo "deb [signed-by=/usr/share/keyrings/stripe.gpg] https://packages.stripe.dev/stripe-cli-debian-local stable main" | tee /etc/apt/sources.list.d/stripe.list RUN apt-get update && apt-get install -y stripe
2. 选择合适的执行时机
方式一:容器启动时自动执行(带幂等校验)
创建启动脚本start.sh,避免重复创建Webhook:
#!/bin/bash # 检查目标Webhook是否已存在 WEBHOOK_TARGET="你的Webhook接收地址" WEBHOOK_EXISTS=$(stripe webhook_endpoints list --limit 1 --url "$WEBHOOK_TARGET" --api-key "$STRIPE_API_KEY" | grep -q "$WEBHOOK_TARGET" && echo "exists" || echo "not exists") if [ "$WEBHOOK_EXISTS" = "not exists" ]; then stripe webhook_endpoints create \ --url "$WEBHOOK_TARGET" \ --api-key "$STRIPE_API_KEY" \ --enabled-events "charge.succeeded" "customer.created" # 替换为你需要监听的事件 fi # 启动应用服务 exec "你的应用启动命令"
然后在Dockerfile.studio中配置脚本作为启动命令:
COPY start.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/start.sh CMD ["start.sh"]
方式二:手动进入容器执行(适合调试)
启动容器后,通过以下命令进入容器并执行:
docker exec -it <你的容器名称> bash # 容器内执行创建命令 stripe webhook_endpoints create \ --url "你的Webhook接收地址" \ --api-key <你的Stripe API密钥> \ --enabled-events "需要的事件列表"
三、关于localhost与ngrok的选择
- 如果你的服务运行在本地Docker环境:必须用ngrok或类似内网穿透工具。因为localhost仅能在本地访问,Stripe的服务器无法直接连接到你本地的Docker容器。启动ngrok后会生成一个公网地址(如
https://xxxx-xx-xx-xx-xx.ngrok.io),将其作为Webhook的--url参数即可。 - 如果服务已部署到公网:直接使用公网地址,无需ngrok。
四、关键配置注意事项
- 确保容器内已配置
STRIPE_API_KEY环境变量,可在docker-compose.yml中添加:services: studio: build: context: . dockerfile: Dockerfile.studio environment: - STRIPE_API_KEY=sk_xxxxxxxxxxxxxx - 执行
stripe webhook_endpoints create后,会返回Webhook签名密钥,需将该密钥配置到你的应用中,用于验证Stripe Webhook请求的合法性。
内容的提问来源于stack exchange,提问作者deadcoder0904
相关产品推荐
相关产品推荐

