收到 Stripe Webhook 后将项目保存在数据库中
Posted
技术标签:
【中文标题】收到 Stripe Webhook 后将项目保存在数据库中【英文标题】:Saving Items In Database after receiving a Stripe Webhook 【发布时间】:2020-12-22 02:25:06 【问题描述】:当我从 Stripe 收到一个说订阅已创建的 webhook 时,我正在尝试更新我的数据库以让该用户访问我的订阅服务。 webhook 表示订阅已创建,因此我使用 UserID 并使用它在我的数据库中查找用户。然后我更新用户记录,将 SubscriptionStatus 更改为 1,表示它处于活动状态。当我尝试将该信息保存到数据库时,它会引发异常,并且我从 Stripe 收到一条错误消息,指出 webhook 失败并出现错误 400(错误请求)。根据 Stripe 的响应,它说“由于语法错误,服务器无法理解请求。”
这是我从 Stripe 收到的回复:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IIS 10.0 Detailed Error - 400.0 - Bad Request</title>
<style type="text/css">
<!--
bodymargin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;
codemargin:0;color:#006600;font-size:1.1em;font-weight:bold;
.config_source codefont-size:.8em;color:#000000;
premargin:0;font-size:1.4em;word-wrap:break-word;
ul,olmargin:10px 0 10px 5px;
ul.first,ol.firstmargin-top:5px;
fieldsetpadding:0 15px 10px 15px;word-break:break-all;
.summary-container fieldsetpadding-bottom:5px;margin-top:4px;
legend.no-expand-allpadding:2px 15px 4px 10px;margin:0 0 0 -12px;
legendcolor:#333333;;margin:4px 0 8px -12px;_margin-top:0px;
font-weight:bold;font-size:1em;
a:link,a:visitedcolor:#007EFF;font-weight:bold;
a:hovertext-decoration:none;
h1font-size:2.4em;margin:0;color:#FFF;
h2font-size:1.7em;margin:0;color:#CC0000;
h3font-size:1.4em;margin:10px 0 0 0;color:#CC0000;
h4font-size:1.2em;margin:10px 0 5px 0;
#headerwidth:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
#contentmargin:0 0 0 2%;position:relative;
.summary-container,.content-containerbackground:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;
.content-container pmargin:0 0 10px 0;
#details-leftwidth:35%;float:left;margin-right:2%;
#details-rightwidth:63%;float:left;overflow:hidden;
#server_versionwidth:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
#server_version pmargin:5px 0;
tablemargin:4px 0 4px 0;width:100%;border:none;
td,thvertical-align:top;padding:3px 0;text-align:left;font-weight:normal;border:none;
thwidth:30%;text-align:right;padding-right:2%;font-weight:bold;
thead thbackground-color:#ebebeb;width:25%;
#details-right thwidth:20%;
table tr.alt td,table tr.alt th
.highlight-codecolor:#CC0000;font-weight:bold;font-style:italic;
.clearclear:both;
.preferredpadding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;
-->
</style>
</head>
<body>
<div id="content">
<div class="content-container">
<h3>HTTP Error 400.0 - Bad Request</h3>
<h4>Bad Request</h4>
</div>
<div class="content-container">
<fieldset><h4>Most likely causes:</h4>
<ul> <li></li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>Things you can try:</h4>
<ul> <li>Check the failed request tracing logs for additional information about this error. For more information, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>Detailed Error Information:</h4>
<div id="details-left">
<table border="0" cellpadding="0" cellspacing="0">
<tr class="alt"><th>Module</th><td> ManagedPipelineHandler</td></tr>
<tr><th>Notification</th><td> ExecuteRequestHandler</td></tr>
<tr class="alt"><th>Handler</th><td> System.Web.Mvc.MvcHandler</td></tr>
<tr><th>Error Code</th><td> 0x00000000</td></tr>
</table>
</div>
<div id="details-right">
<table border="0" cellpadding="0" cellspacing="0">
<tr class="alt"><th>Requested URL</th><td> https://localhost:44394/Stripe/StripeWebhook</td></tr>
<tr><th>Physical Path</th><td> C:\Users\steve\source\repos\Church Musician Administration App\Church Musician Administration App (Updated)\Stripe\StripeWebhook</td></tr>
<tr class="alt"><th>Logon Method</th><td> Anonymous</td></tr>
<tr><th>Logon User</th><td> Anonymous</td></tr>
</table>
<div class="clear"></div>
</div>
</fieldset>
</div>
<div class="content-container">
<fieldset><h4>More Information:</h4>
The request could not be understood by the server due to malformed syntax.
<p><a href="https://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=400,0,0x00000000,19042">View more information »</a></p>
<p>Microsoft Knowledge Base Articles:</p>
<ul><li></li></ul>
</fieldset>
</div>
</div>
</body>
</html>
这是我应用中的 Webhook 端点:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Database_Access;
using Stripe;
namespace Church_Musician_Administration_App__Updated_.Controllers
public class StripeController : Controller
private churchmusicianEntities db = new churchmusicianEntities();
[AllowAnonymous]
[HttpPost]
public ActionResult StripeWebhook()
try
var json = new StreamReader(HttpContext.Request.InputStream).ReadToEnd();
// validate webhook called by stripe only
var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], "whsec_jLsw8GxNmEKkcyxhjNeDTpJvI5xhggXu");
switch (stripeEvent.Type)
case "customer.created":
var customer = stripeEvent.Data.Object as Customer;
// do work
break;
case "customer.subscription.created":
var subscriptionCreated = stripeEvent.Data.Object as Subscription;
string subscriptionCustID = subscriptionCreated.CustomerId;
var subscriptionCustomers = db.logins.Where(x => x.StripeCustomerID == subscriptionCustID);
foreach (var subscriptionCustomer in subscriptionCustomers)
if (subscriptionCreated.Status == "trialing" || subscriptionCreated.Status == "active")
subscriptionCustomer.SubscriptionStatus = 1;
db.Entry(subscriptionCustomer).State = EntityState.Modified;
db.SaveChanges();
break;
case "customer.subscription.updated":
case "customer.subscription.deleted":
case "customer.subscription.trial_will_end":
var subscription = stripeEvent.Data.Object as Subscription;
// do work
break;
case "invoice.created":
var newinvoice = stripeEvent.Data.Object as Invoice;
// do work
break;
case "invoice.upcoming":
case "invoice.payment_succeeded":
var successPayment = stripeEvent.Data.Object as Invoice;
string customerID = successPayment.CustomerId;
var custs = db.logins.Where(x => x.StripeCustomerID == customerID);
foreach (var cust in custs)
cust.SubscriptionExpiration = successPayment.PeriodEnd.ToString();
db.SaveChanges();
break;
case "invoice.payment_failed":
var changeSubscription = stripeEvent.Data.Object as Invoice;
string customerID2 = changeSubscription.CustomerId;
if(changeSubscription.Status != "active")
var payingCustomers = db.logins.Where(x => x.StripeCustomerID == customerID2);
foreach (var payingCustomer in payingCustomers)
payingCustomer.SubscriptionStatus = 0;
db.SaveChanges();
// do work
break;
case "coupon.created":
case "coupon.updated":
case "coupon.deleted":
var coupon = stripeEvent.Data.Object as Coupon;
// do work
break;
// DO SAME FOR OTHER EVENTS
return new HttpStatusCodeResult(HttpStatusCode.OK);
catch (StripeException ex)
//_logger.LogError(ex, $"StripWebhook: ex.Message");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
catch (Exception ex)
//_logger.LogError(ex, $"StripWebhook: ex.Message");
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
【问题讨论】:
【参考方案1】:问题可能是由于您的数据库逻辑出现问题,导致您的服务器将完整错误返回给 Stripe,而 Stripe 无法读取。相反,您应该提前返回 200 以表明已收到 webhook 事件,然后处理您的业务逻辑:https://stripe.com/docs/webhooks/build#return-a-2xx-status-code-quickly
【讨论】:
以上是关于收到 Stripe Webhook 后将项目保存在数据库中的主要内容,如果未能解决你的问题,请参考以下文章
仅在 Stripe 中的平台余额更新时收到通知 - WebHook
如何在Stripe PHP和webhook中使用好事件,比较收到的付款数量并取消订阅
如何在 firebase 函数中检查 Stripe webhook 签名