Использование Stripe Checkout в приложении .net MVC - PullRequest
0 голосов
/ 18 марта 2019

Я пытаюсь использовать Stripe Checkout для создания моего первого приложения MVC, используя шаги прямо из Stripe, найденные здесь - https://stripe.com/docs/checkout/aspnet

Когда я пытаюсь скомпилировать после выполнения этих шагов, я получаю следующееошибки ...

Startup.cs

Ошибка CS0103 Имя 'StripeConfiguration' не существует в текущем контексте

HomeController.cs

Ошибка CS0246 Не удалось найти имя типа или пространства имен 'ChargeCreateOptions' (отсутствует директива using или ссылка на сборку?)

Ошибка CS0246 Имя типа или пространства именНе удалось найти CustomerCreateOptions (отсутствует директива using или ссылка на сборку?)

Ошибка CS0246 Не удалось найти тип или имя пространства имен 'ChargeService' (отсутствует директива using или сборкассылка?)

Ошибка CS0246 Не удалось найти тип или имя пространства имен 'CustomerService' (отсутствует директива using или сборкаy ссылка?)

Я уже удостоверился, что у меня самый последний пакет Stripe, используя Инструменты> Диспетчер пакетов NuGet> Управление пакетом NuGet для решения.

Код HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StripeCheckoutNPP.Models;

namespace StripeCheckoutNPP.Controllers
{
    public class HomeController : Controller

    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult Charge(string stripeEmail, string stripeToken)
        {
            var customers = new CustomerService();
            var charges = new ChargeService();

            var customer = customers.Create(new CustomerCreateOptions
            {
                Email = stripeEmail,
                SourceToken = stripeToken
            });

            var charge = charges.Create(new ChargeCreateOptions
            {
                Amount = 500,
                Description = "Sample Charge",
                Currency = "usd",
                CustomerId = customer.Id
            });

            return View();
        }
    }
}

Код Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace StripeCheckoutNPP
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            StripeConfiguration.SetApiKey(Configuration.GetSection("Stripe")["SecretKey"]);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 18 марта 2019

В Visual Studio 2017 добавлено .NET Core-> ASP.NET Core веб-приложение с именем StripeCheckoutNPP. Версия ASP.NET Core 2.2. Выбрал веб-приложение (модель-вид-контроллер). Не проверено Настроить для HTTPS. Перестроено проектное решение. Добавлен Stripe.Net. stripe.net https://dashboard.stripe.com/login?redirect=%2Faccount%2Fapikeys добавил мой секретный ключ и ключ публикации в appsettings.json

Шахта работает даже после последнего поста ответа - делаешь по-своему.

Похоже, вы неправильно обрабатываете, так что пространства имен и классы полосы не имеют правильной ссылки.

Я установил бесплатный JustDecompile, и увидел, что все ваши ошибки, для классов StripeConfiguration ChargeCreateOptions CustomerCreateOptions ChargeService Обслуживание клиентов Находятся в Stripe.net.dll

enter image description here

0 голосов
/ 18 марта 2019

Согласно инструкции, ваш способ настройки должен быть

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        StripeConfiguration.SetApiKey(Configuration.GetSection("Stripe")["SecretKey"]); 
        // the rest of the code....
    }

В настоящее время у вас есть StripeConfiguration.SetApiKey() в конструкторе

...