Я пытаюсь внедрить Stripe для сбора платежей на моем сайте. Я могу получать платежи для обработки, но мне нужно получить HTTP POST от Stripe после оплаты, чтобы записать это в мою БД. Я использую Stripe CLI на своем локальном хосте и получаю ошибку 404. Я попытался опубликовать на // localhost: 59400 / api / payment и //localhost:59400/payment.
Вот документация Stripe, за которой я следую. NET https://stripe.com/docs/payments/checkout/fulfillment#webhooks
Вот мой контроллер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Stripe;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Net.Http;
using System.Net;
namespace Stripe.Controllers
{
[Route("api/[controller]")]
public class PaymentController : Controller
{
// You can find your endpoint's secret in your webhook settings
const string secret = "XXX";
private ApplicationDbContext db = new ApplicationDbContext();
[HttpPost]
public async Task<IActionResult> Index()
{
var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
StripeConfiguration.ApiKey = "XXX";
try
{
var stripeEvent = EventUtility.ConstructEvent(json,
Request.Headers["Stripe-Signature"], secret);
// Handle the checkout.session.completed event
if (stripeEvent.Type == Events.CheckoutSessionCompleted)
{
var session = stripeEvent.Data.Object as Stripe.Checkout.Session;
// Fulfill the purchase...
//HandleCheckoutSession(session);
var paid = db.Confirmations.OrderByDescending(z => z.CreatedDate).First();
paid.Paid = true;
db.Entry(paid).State = EntityState.Modified;
await db.SaveChangesAsync();
return Ok();
}
else
{
return Ok();
}
}
catch (StripeException e)
{
return BadRequest();
}
}
}
}
Я знаю, что CLI работает как localhost: 59400 / возвращает 200, но, очевидно, POST не попадает в API оплаты.
Я врезался в стену после нескольких недель попыток проработать это в свободное время. Любая помощь будет принята с благодарностью.
ОБНОВЛЕНИЕ
Ошибка при ударе CURL // localhost: 59400 / api / payment и // localhost: 59400 / payment
[HttpException]: The controller for path '/payment' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->* Connection #0 to host localhost left intact
Ошибка при попадании Stripe CLI // localhost: 59400 / api / payment и // localhost: 59400 / payment
2020-02-04 22:34:05 --> payment_intent.created [evt_1G8eePHmrqaLln8DkjOfEf3D]
2020-02-04 22:34:05 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eePHmrqaLln8DkjOfEf3D]
2020-02-04 22:34:21 --> customer.created [evt_1G8eeeHmrqaLln8DRBvQWiSN]
2020-02-04 22:34:21 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eeeHmrqaLln8DRBvQWiSN]
2020-02-04 22:34:22 --> payment_method.attached [evt_1G8eeeHmrqaLln8DnUkfDErF]
2020-02-04 22:34:22 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eeeHmrqaLln8DnUkfDErF]
2020-02-04 22:34:23 --> charge.succeeded [evt_1G8eeeHmrqaLln8DBuBNkK2e]
2020-02-04 22:34:23 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eeeHmrqaLln8DBuBNkK2e]
2020-02-04 22:34:23 --> payment_intent.succeeded [evt_1G8eeeHmrqaLln8DcYK4KYSE]
2020-02-04 22:34:23 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eeeHmrqaLln8DcYK4KYSE]
2020-02-04 22:34:25 --> checkout.session.completed [evt_1G8eefHmrqaLln8Dx6xgFRml]
2020-02-04 22:34:25 <-- [404] POST http://localhost:59400/api/payment [evt_1G8eefHmrqaLln8Dx6xgFRml]
Вот мои RouteConfig и WebApiConfig соответственно
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}