首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我应该使用哪种PayPal支付方法?

我应该使用哪种PayPal支付方法?
EN

Stack Overflow用户
提问于 2020-07-13 22:27:18
回答 1查看 96关注 0票数 1

我有一个客户端的应用程序,他在其中使用了PaypalAdaptivePayments,但是这个API从2年前就停止工作了,现在这个项目就在我的手中,所以我开始研究这个API,发现PayPal已经拒绝了这个API的使用,实际上在他的应用程序中,他所拥有的是:

1-在PayPal中只有一个卖方账户,其中有从申请中借记和贷记的金额。

2-这个应用程序基本上是一种骑马预订网络应用程序,在这个应用程序中,客户预订一次车,然后将X的金额存入钱包(请记住,这个钱包是连接到我在第1点中提到的供应商帐户)。

3-当客户的行程完成后,他会标记出借方的金额,然后将这一决定保存到我的数据库中,但直到这一阶段,司机才得到偿还。

4-管理员登录到这个网站,然后他进入司机列表,然后选择一个合适的司机,然后他把他的X佣金,然后点击支付,所以这个行动司机得到报酬。注:这是一种基于佣金的程序,因此,例如,客户预订的车程是USD100,因此他将这一金额记入供应商钱包,然后当该供应商即将向司机提供贷款时,他输入自己的佣金,例如10%,因此司机将只获得USD90的报酬。这笔款项也从供应商的钱包中扣除,然后转帐给司机。

现在,在绘制了这个场景之后,您能指导我哪个API最适合这个场景吗?因为有大量的PayPal API和SDK .我完全迷失在他们的世界,请记住我的应用程序是构建在ASP.NET MVC。

请注意:我的客户(供应商)已经在PayPal中拥有一个沙箱和一个经过验证的业务帐户。

亲切的问候。埃马德。

为了方便社区,我分享我的代码:

代码语言:javascript
复制
using Classes;
using EFare.Classes;
using PayPalMvc;
using PayPalMvc.Enums;
using SampleMVC3WebApplication.Models;
using SampleMVC3WebApplication.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;

namespace SampleMVC3WebApplication
{
    public class WebUILogging
    {
        // Add your favourite logger here

        public static void LogMessage(string message)
        {
            DoTrace(message);
        }

        public static void LogLongMessage(string message, string longMessage)
        {
            DoTrace(message);
            DoTrace(longMessage);
        }

        public static void LogException(string message, Exception ex)
        {
            DoTrace(message);
            DoTrace(ex.Message);
            DoTrace(ex.StackTrace);
        }

        private static void DoTrace(string message)
        {
            Trace.WriteLine(DateTime.Now + " - " + message);
        }
    }
}

namespace SampleMVC3WebApplication.Services
{
    public interface ITransactionService
    {
        SetExpressCheckoutResponse SendPayPalSetExpressCheckoutRequest(ApplicationCart cart, string serverURL,
            string userEmail = null);

        GetExpressCheckoutDetailsResponse SendPayPalGetExpressCheckoutDetailsRequest(string token);

        DoExpressCheckoutPaymentResponse SendPayPalDoExpressCheckoutPaymentRequest(ApplicationCart cart, string token,
            string payerId);
    }

    /// <summary>
    ///     The Transaction Service is used to transform a purchase object (eg cart, basket, or single item) into a sale
    ///     request with PayPal (in this case a cart)
    ///     It also allows your app to store the transactions in your database (create a table to match the PayPalTransaction
    ///     model)
    ///     You should copy this file into your project and modify it to accept your purchase object, store PayPal transaction
    ///     responses in your database,
    ///     as well as log events with your favourite logger.
    /// </summary>
    public class TransactionService : ITransactionService
    {
        private readonly ITransactionRegistrar _payPalTransactionRegistrar = new TransactionRegistrar();

        public SetExpressCheckoutResponse SendPayPalSetExpressCheckoutRequest(ApplicationCart cart, string serverURL,
            string userEmail = null)
        {
            try
            {
                WebUILogging.LogMessage("SendPayPalSetExpressCheckoutRequest");

                // Optional handling of cart items: If there is only a single item being sold we don't need a list of expressCheckoutItems
                // However if you're selling a single item as a sale consider also adding it as an ExpressCheckoutItem as it looks better once you get to PayPal's site
                // Note: ExpressCheckoutItems are currently NOT stored by PayPal against the sale in the users order history so you need to keep your own records of what items were in a cart
                List<ExpressCheckoutItem> expressCheckoutItems = null;
                if (cart.Items != null)
                {
                    expressCheckoutItems = new List<ExpressCheckoutItem>();
                    foreach (var item in cart.Items)
                        expressCheckoutItems.Add(new ExpressCheckoutItem(item.Quantity, item.Price, item.Name,
                            item.Description));
                }

                var response = _payPalTransactionRegistrar.SendSetExpressCheckout(cart.Currency, cart.TotalPrice,
                    cart.PurchaseDescription, cart.Id.ToString(), serverURL, expressCheckoutItems, userEmail);

                // Add a PayPal transaction record
                var transaction = new PayPalTransaction
                {
                    RequestId = response.RequestId,
                    TrackingReference = cart.Id.ToString(),
                    RequestTime = DateTime.Now,
                    RequestStatus = response.ResponseStatus.ToString(),
                    TimeStamp = response.TIMESTAMP,
                    RequestError = response.ErrorToString,
                    Token = response.TOKEN
                };

                // Store this transaction in your Database

                return response;
            }
            catch (Exception ex)
            {
                WebUILogging.LogException(ex.Message, ex);
            }

            return null;
        }

        public GetExpressCheckoutDetailsResponse SendPayPalGetExpressCheckoutDetailsRequest(string token)
        {
            try
            {
                WebUILogging.LogMessage("SendPayPalGetExpressCheckoutDetailsRequest");
                var response = _payPalTransactionRegistrar.SendGetExpressCheckoutDetails(token);

                // Add a PayPal transaction record
                var transaction = new PayPalTransaction
                {
                    RequestId = response.RequestId,
                    TrackingReference = response.TrackingReference,
                    RequestTime = DateTime.Now,
                    RequestStatus = response.ResponseStatus.ToString(),
                    TimeStamp = response.TIMESTAMP,
                    RequestError = response.ErrorToString,
                    Token = response.TOKEN,
                    PayerId = response.PAYERID,
                    RequestData = response.ToString
                };

                // Store this transaction in your Database

                return response;
            }
            catch (Exception ex)
            {
                WebUILogging.LogException(ex.Message, ex);
            }

            return null;
        }

        public DoExpressCheckoutPaymentResponse SendPayPalDoExpressCheckoutPaymentRequest(ApplicationCart cart,
            string token, string payerId)
        {
            try
            {
                WebUILogging.LogMessage("SendPayPalDoExpressCheckoutPaymentRequest");
                var response =
                    _payPalTransactionRegistrar.SendDoExpressCheckoutPayment(token, payerId, cart.Currency,
                        cart.TotalPrice);

                // Add a PayPal transaction record
                var transaction = new PayPalTransaction
                {
                    RequestId = response.RequestId,
                    TrackingReference = cart.Id.ToString(),
                    RequestTime = DateTime.Now,
                    RequestStatus = response.ResponseStatus.ToString(),
                    TimeStamp = response.TIMESTAMP,
                    RequestError = response.ErrorToString,
                    Token = response.TOKEN,
                    RequestData = response.ToString,
                    PaymentTransactionId = response.PaymentTransactionId,
                    PaymentError = response.PaymentErrorToString
                };

                // Store this transaction in your Database

                return response;
            }
            catch (Exception ex)
            {
                WebUILogging.LogException(ex.Message, ex);
            }

            return null;
        }
    }
}

namespace SampleMVC3WebApplication.Controllers
{
    public class PurchaseController : Controller
    {
        private readonly TransactionService transactionService = new TransactionService();

        private bool checkcustomerid(string uid)
        {
            var dl = new AccountDataLayer();
            var ds = dl.Inline_Process("select UserId from dbo.Login_Table where UserId='" + uid +
                                       "' and UType='customer'");
            return ds.Tables[0].Rows.Count > 0;
        }

        #region Set Express Checkout and Get Checkout Details

        public ActionResult PayPalExpressCheckout()
        {
            WebUILogging.LogMessage("Express Checkout Initiated");
            // SetExpressCheckout
            var cart = (ApplicationCart)Session["Cart"];
            var serverURL = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) +
                            VirtualPathUtility.ToAbsolute("~/");
            var transactionResponse =
                transactionService.SendPayPalSetExpressCheckoutRequest(cart, serverURL);
            // If Success redirect to PayPal for user to make payment
            if (transactionResponse == null || transactionResponse.ResponseStatus != ResponseType.Success)
            {
                SetUserNotification(
                    "Sorry there was a problem with initiating a PayPal transaction. Please try again and contact an Administrator if this still doesn't work.");
                var errorMessage = transactionResponse == null
                    ? "Null Transaction Response"
                    : transactionResponse.ErrorToString;
                WebUILogging.LogMessage(
                    "Error initiating PayPal SetExpressCheckout transaction. Error: " + errorMessage);
                return RedirectToAction("Error", "Purchase");
            }

            return Redirect(string.Format(PayPalMvc.Configuration.Current.PayPalRedirectUrl,
                transactionResponse.TOKEN));
        }

        public ActionResult
            PayPalExpressCheckoutAuthorisedSuccess(string token,
                string PayerID) // Note "PayerID" is returned with capitalisation as written
        {
            // PayPal redirects back to here
            WebUILogging.LogMessage("Express Checkout Authorised");
            // GetExpressCheckoutDetails
            TempData["token"] = token;
            TempData["payerId"] = PayerID;
            var transactionResponse =
                transactionService.SendPayPalGetExpressCheckoutDetailsRequest(token);
            if (transactionResponse == null || transactionResponse.ResponseStatus != ResponseType.Success)
            {
                SetUserNotification(
                    "Sorry there was a problem with initiating a PayPal transaction. Please try again and contact an Administrator if this still doesn't work.");
                var errorMessage = transactionResponse == null
                    ? "Null Transaction Response"
                    : transactionResponse.ErrorToString;
                WebUILogging.LogMessage("Error initiating PayPal GetExpressCheckoutDetails transaction. Error: " +
                                        errorMessage);
                return RedirectToAction("Error", "Purchase");
            }

            return RedirectToAction("ConfirmPayPalPayment");
        }

        #endregion Set Express Checkout and Get Checkout Details

        #region Confirm Payment

        public ActionResult ConfirmPayPalPayment()
        {
            WebUILogging.LogMessage("Express Checkout Confirmation");
            var cart = (ApplicationCart)Session["Cart"];
            return View(cart);
        }

        [HttpPost]
        public ActionResult ConfirmPayPalPayment(bool confirmed = true)
        {
            WebUILogging.LogMessage("Express Checkout Confirmed");
            var cart = (ApplicationCart)Session["Cart"];
            // DoExpressCheckoutPayment
            var token = TempData["token"].ToString();
            var payerId = TempData["payerId"].ToString();
            var transactionResponse =
                transactionService.SendPayPalDoExpressCheckoutPaymentRequest(cart, token, payerId);

            if (transactionResponse == null || transactionResponse.ResponseStatus != ResponseType.Success)
            {
                if (transactionResponse != null && transactionResponse.L_ERRORCODE0 == "10486")
                {   // Redirect user back to PayPal in case of Error 10486 (bad funding method)
                    // https://www.x.com/developers/paypal/documentation-tools/how-to-guides/how-to-recover-funding-failure-error-code-10486-doexpresscheckout

                    WebUILogging.LogMessage("Redirecting User back to PayPal due to 10486 error (bad funding method - typically an invalid or maxed out credit card)");
                    return Redirect(string.Format(PayPalMvc.Configuration.Current.PayPalRedirectUrl, token));
                }
                else
                {
                    SetUserNotification(
                        "Sorry there was a problem with taking the PayPal payment, so no money has been transferred. Please try again and contact an Administrator if this still doesn't work.");
                    var errorMessage = transactionResponse == null
                        ? "Null Transaction Response"
                        : transactionResponse.ErrorToString;
                    WebUILogging.LogMessage("Error initiating PayPal DoExpressCheckoutPayment transaction. Error: " +
                                            errorMessage);
                    return RedirectToAction("Error", "Purchase");
                }
            }

            if (transactionResponse.PaymentStatus == PaymentStatus.Completed)
                return RedirectToAction("PostPaymentSuccess");

            // Something went wrong or the payment isn't complete
            WebUILogging.LogMessage("Error taking PayPal payment. Error: " + transactionResponse.ErrorToString +
                                    " - Payment Error: " + transactionResponse.PaymentErrorToString);
            TempData["TransactionResult"] = transactionResponse.PAYMENTREQUEST_0_LONGMESSAGE;
            return RedirectToAction("PostPaymentFailure");
        }

        #endregion Confirm Payment

        #region Post Payment and Cancellation

        public ActionResult PostPaymentSuccess()
        {
            WebUILogging.LogMessage("Post Payment Result: Success");
            var cart = (ApplicationCart)Session["Cart"];
            ViewBag.TrackingReference = cart.Id;
            ViewBag.Description = cart.PurchaseDescription;
            ViewBag.TotalCost = cart.TotalPrice;
            ViewBag.Currency = cart.Currency;

            var dl = new Customer();
            var amt = "";
            var date = "";
            ;
            var time = "";
            var EFareloginCookie = Request.Cookies["Efarelogin_Cookies"];
            if (EFareloginCookie != null)
                if (checkcustomerid(EFareloginCookie["UserId"]))
                {
                    amt = cart.TotalPrice.ToString();
                    date = DateTime.Now.ToString("yyyy-MM-dd");
                    time = DateTime.Now.ToString("hh:mm:ss");

                    var i = dl.addMoney(EFareloginCookie["UserId"], amt, date, time);
                    if (i > 0)
                    {
                        TempData["WalletSuccess"] = "Data saved successfully.";
                        //return RedirectToAction("Wallet", "Account");
                        ModelState.Clear();
                    }
                    else
                    {
                        TempData["Walleterror"] = "Opps something is wrong.";
                    }
                }

            return View();
        }

        public ActionResult PostPaymentFailure()
        {
            WebUILogging.LogMessage("Post Payment Result: Failure");
            ViewBag.ErrorMessage = TempData["TransactionResult"];
            return View();
        }

        public ActionResult CancelPayPalTransaction()
        {
            return View();
        }

        #endregion Post Payment and Cancellation

        #region Transaction Error

        private void SetUserNotification(string notification)
        {
            TempData["ErrorMessage"] = notification;
        }

        public ActionResult Error()
        {
            ViewBag.ErrorMessage = TempData["ErrorMessage"];
            return View();
        }

        #endregion Transaction Error
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-13 22:37:14

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62885229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档