且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net core 3.1在条带HttpPost("webhook")中获取当前身份用户返回NULL

更新时间:2023-02-17 10:34:42

问题是,当您从Stripe收到POST请求时,没有用户会话.身份验证会话可能由Cookie管理,并由客户的浏览器保留.当直接从Stripe收到POST请求时,该请求将不包含与您已通过身份验证的用户相关的任何cookie.

The issue is that there is no user session when you receive the POST request from Stripe. The authentication session is likely managed with cookies and persisted by your customer's browser. When receiving the POST request directly from Stripe, the request will not include any cookies related to your authenticated user.

您需要使用另一种方式将Checkout会话与数据库中的用户相关联,而不是使用以下内容来查找当前用户.

Instead of using the following to lookup the current user, you'll need another way to associate the Checkout Session to a user in your database.

var currentUser = await _userManager.GetUserAsync(HttpContext.User);

有两种解决方法.

  1. 将用户的ID存储在Checkout会话的元数据中.

  1. Store the ID of the user in the metadata for the Checkout Session.

将Checkout会话的ID存储在数据库中,并返回到当前用户.

Store the ID of the Checkout Session in your database with some relation back to the current user.

许多用户在选项1上都取得了成功,创建Checkout会话的外观可能大致类似于以下内容:

Many users have success with option 1 and it might look something roughly like the following for creating the Checkout Session:

var currentUser = await _userManager.GetUserAsync(HttpContext.User);
var options = new SessionCreateOptions
{
    SuccessUrl = "https://example.com/success",
    Metadata = new Dictionary<string, string>
    {
        {"UserId", currentUser.ID},
    }
    //...
};

然后稍后从webhook处理程序中查找用户时:

Then later when looking up the User from the webhook handler:

var currentUser = await _userManager.FindByIdAsync(checkoutSession.Metadata.UserId);