简体   繁体   English

如何将 Stripe 支付网关集成到 ASP.NET MVC

[英]How to integrate Stripe payment gateway to ASP.NET MVC

I want to integrate Stripe psp into my ASP.NET MVC application.我想将Stripe psp集成到我的 ASP.NET MVC 应用程序中。

Before you roast me with looking for questions with same issues, I did look for the said questions but they seem to be outdated.在你用寻找相同问题的问题来烤我之前,我确实寻找过上述问题,但它们似乎已经过时了。

I tried to follow the procedures from stripe website, but the javascript couldn't load the payment.我尝试按照 stripe 网站的程序进行操作,但 javascript 无法加载付款。 I know I'm missing something.我知道我错过了一些东西。

If you could help me rather than roast me it would be great:).如果你能帮助我而不是烤我,那就太好了:)。
ps I'm totally new to MVC:/ ps我对 MVC 完全陌生:/

The cshtml view with script带有脚本的 cshtml 视图

@{
    Layout = null;
}


<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ProcessPayment | Merchant Dashboard</title>
    <script src="https://js.stripe.com/v3/"></script>
  <script>
      var stripe = Stripe('pk_test_51H1XOgCuKWbkvTE3V6VYOV0qVBLrEcZMCISGPWJ3nZeDqq3JgWb1GL1c2HRxk4NAve4j7YFkZeAvWoatocuvgzLb00bSZL72k3');
      var elements = stripe.elements();

      // Custom styling can be passed to options when creating an Element.
      var style = {
          base: {
              // Add your base input styles here. For example:
              fontSize: '16px',
              color: '#32325d',
          },
      };

      // Create an instance of the card Element.
      var card = elements.create('card', { style: style });

      // Add an instance of the card Element into the `card-element` <div>.
      card.mount('#card-element');

      // Create a token or display an error when the form is submitted.
      var form = document.getElementById('payment-form');
      form.addEventListener('submit', function (event) {
          event.preventDefault();

          stripe.createToken(card).then(function (result) {
              if (result.error) {
                  // Inform the customer that there was an error.
                  var errorElement = document.getElementById('card-errors');
                  errorElement.textContent = result.error.message;
              } else {
                  // Send the token to your server.
                  stripeTokenHandler(result.token);
              }
          });
      });

      function stripeTokenHandler(token) {
          // Insert the token ID into the form so it gets submitted to the server
          var form = document.getElementById('payment-form');
          var hiddenInput = document.createElement('input');
          hiddenInput.setAttribute('type', 'hidden');
          hiddenInput.setAttribute('name', 'stripeToken');
          hiddenInput.setAttribute('value', token.id);
          form.appendChild(hiddenInput);

          // Submit the form
          form.submit();
      }

      // Set your secret key. Remember to switch to your live secret key in production!
      // See your keys here: https://dashboard.stripe.com/account/apikeys
      StripeConfiguration.ApiKey = "pk_test_51H1XOgCuKWbkvTE3V6VYOV0qVBLrEcZMCISGPWJ3nZeDqq3JgWb1GL1c2HRxk4NAve4j7YFkZeAvWoatocuvgzLb00bSZL72k3";

      // Token is created using Checkout or Elements!
      // Get the payment token submitted by the form:
      var token = model.Token; // Using ASP.NET MVC

      var options = new ChargeCreateOptions
      {
          Amount = 999,
              Currency = "usd",
              Description = "Example charge",
              Source = token,
};

      var service = new ChargeService();
      var charge = service.Create(options);
  </script>
</head>
<body>

    <form action="/charge" method="post" id="payment-form">
        <div class="form-row">
            <label for="card-element">
                Credit or debit card
            </label>
            <div id="card-element">
                <!-- A Stripe Element will be inserted here. -->
            </div>

            <!-- Used to display Element errors. -->
            <div id="card-errors" role="alert"></div>
        </div>

        <button>Submit Payment</button>
    </form>
</body>
</html>

The controller controller

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MerchantCheckout.Models;
using Stripe;

namespace MerchantCheckout.Controllers
{
    public class ProcessPaymentController : Controller
    {
        // GET: ProcessPayment
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ProcessPayment()
        {
            var stripePublishKey = ConfigurationManager.AppSettings["pk_test_51H1XOgCuKWbkvTE3V6VYOV0qVBLrEcZMCISGPWJ3nZeDqq3JgWb1GL1c2HRxk4NAve4j7YFkZeAvWoatocuvgzLb00bSZL72k3"];
            ViewBag.StripePublishKey = stripePublishKey;
            return View();
        }

        public ActionResult Charge(string stripeEmail, string stripeToken)
        {
            Stripe.CustomerCreateOptions customer = new Stripe.CustomerCreateOptions();

            var custService = new Stripe.CustomerService();

            Stripe.Customer stpCustomer = custService.Create(customer);

            return View();
        }
    }
}

Well I managed to make it work:).好吧,我设法使它工作:)。 For any one like me who is stucked, please follow the steps below:对于像我这样被卡住的人,请按照以下步骤操作:

Step 1 : Once you get your key from stripe, add it to your web.config file第 1 步:从条带获取密钥后,将其添加到 web.config 文件中

 <add key="stripePublishableKey" value="YourKeyHere"/>

Note: I've added for testing purposes only.注意:我添加仅用于测试目的。 You can later add your secret key when your app goes live.当您的应用上线时,您可以稍后添加您的密钥。

Step 2: Add the following codes in your controller第 2 步:在您的 controller 中添加以下代码

public ActionResult Index()
{
    ViewBag.StripePublishKey = ConfigurationManager.AppSettings["stripePublishableKey"];
     return View();
}
    
[HttpPost]
public ActionResult Charge(string stripeToken, string stripeEmail)
{
   Stripe.StripeConfiguration.SetApiKey("your Publishable key");
    Stripe.StripeConfiguration.ApiKey = "your Secret key";
    
    var myCharge = new Stripe.ChargeCreateOptions();
    // always set these properties
    myCharge.Amount = 500;
    myCharge.Currency = "USD";
    myCharge.ReceiptEmail = stripeEmail;
    myCharge.Description = "Sample Charge";
    myCharge.Source = stripeToken;
    myCharge.Capture = true;
    var chargeService = new Stripe.ChargeService();
    Charge stripeCharge = chargeService.Create(myCharge);
    return View();
}

Step 3: Verify if your cshtml file contains the following codes, if not, add them:第三步:验证你的cshtml文件是否包含以下代码,如果没有,添加它们:

<form action="/Home/Charge" method="POST">
    <article>
        <label>Amount: $5.00</label>
    </article>
    <script src="//checkout.stripe.com/v2/checkout.js"
            class="stripe-button"
            data-key="@ViewBag.StripePublishKey"
            data-locale="auto"
            data-description="Sample Charge"
            data-amount="500">
    </script>
</form>

Step 4: Test.!第四步:测试! You should however use the stripe test data.但是,您应该使用条带测试数据。

I do not own the above codes, did some research and came across this website where this man explains how its done.我不拥有上述代码,做了一些研究,发现了这个网站,这个人解释了它是如何完成的。 Click here 点击这里

Stripe Integration is very easy.条纹集成非常简单。
Stripe has provided very useful documentation for payment gateway integration. Stripe 为支付网关集成提供了非常有用的文档。 we can follow the same我们可以遵循相同的
For new users it's important to understand how we can integrate payment gateway into our application.对于新用户来说,了解我们如何将支付网关集成到我们的应用程序中很重要。

Note: Before starting any development, First be ready with publishable key and secrete key.注意:在开始任何开发之前,首先要准备好可发布的密钥和秘密密钥。 Register or login to Stripe account and get these keys from there.注册或登录 Stripe 帐户并从那里获取这些密钥。

When I used Stripe first time in my Application, I followed below link当我第一次在我的应用程序中使用 Stripe 时,我点击了下面的链接

  1. Go to https://stripe.com/docs/payments/integration-builder Go 到https://stripe.com/docs/payments/integration-builder
  2. Choose language .NET选择语言 .NET
  3. Choose Prebuild Checkout Page/Custom Payment flow选择预建结帐页面/自定义付款流程

To do a quick test I will suggest to use Prebuild Checkout Page.要进行快速测试,我建议使用 Prebuild Checkout Page。 Once you get confidence then you can move on to Custom payment flow.一旦您获得信心,您就可以继续进行自定义付款流程。

To integrate with .NET CORE MVC application you can refer github project:要与 .NET CORE MVC 应用程序集成,您可以参考 github 项目:
https://github.com/rohitsoftt/stripe-payment-gateway-dot-net-core https://github.com/rohitsoftt/stripe-payment-gateway-dot-net-core
You need to update your keys in appsettings.json file您需要在 appsettings.json 文件中更新您的密钥

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM