Какой способ оплаты PayPal мне следует использовать? - PullRequest
1 голос
/ 14 июля 2020

У меня есть приложение моего клиента, в котором он использовал PaypalAdaptivePayments , но API перестал работать 2 года назад, теперь этот проект находится в моих руках, поэтому я начал исследовать API и обнаружил, что PayPal имеет отказался от использования этого API, на самом деле в своем приложении он обычно имеет следующее:

1 - В PayPal существует только 1 учетная запись этого поставщика, в которой сумма списывается и зачисляется из приложения.

2- По сути, это приложение представляет собой своего рода веб-приложение для бронирования поездок, в котором клиент заказывает поездку, а затем вносит сумму X в кошелек (помните, что этот кошелек подключен к учетной записи продавца, которую я упомянул в пункте 1).

3- Когда поездка клиента завершена, он отмечает сумму, подлежащую погашению для ДЕБЕТА, затем это решение сохраняется в моей базе данных, но до этого этапа водителю не возмещаются.

4 - АДМИНИСТРАТОР входит на этот сайт, затем переходит к списку драйверов и затем выбирает приложение opriate driver, а затем он вводит свой X COMMISSION для этой поездки, а затем нажимает «ОПЛАТИТЬ», так что этим действием водитель получает деньги. Примечание: это процедура, основанная на комиссии, поэтому, например, ЗАПРОС, которую заказал клиент, составлял 100 долларов , поэтому он зачислил эту сумму на кошелек ПРОДАВЦА, а затем, когда ПРОДАВЕЦ собирается ссудить платеж ВОДИТЕЛЮ, он вводит свою комиссию, например, 10% , поэтому ВОДИТЕЛЬ получит только 90 долларов. Этот платеж также вычитается из кошелька ПРОДАВЦА и затем переводится в ДРАЙВЕР.

Теперь, после рисования сценария, не могли бы вы подсказать мне, какой API лучше всего подходит для этого сценария? поскольку есть ЗАГРУЗКИ API и SDK PayPal .... Я полностью потерялся в их мире, пожалуйста, имейте в виду, что мое приложение построено на ASP. NET MVC.

Обратите внимание: Мой клиент (поставщик) уже владеет SANDBOX и подтвержденным БИЗНЕС-СЧЕТОМ в PayPal.

С наилучшими пожеланиями. Emad.

Для удобства сообщества я делюсь своим кодом:

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
    }
}

1 Ответ

1 голос
/ 14 июля 2020
  1. Используйте PayPal Checkout для получения денег: https://developer.paypal.com/docs/checkout/ --- для интеграции API на основе сервера см. Интерфейс интерфейса https://developer.paypal.com/demo/checkout/# / pattern / server

  2. Запрос доступа к Payouts для отправки денег: https://developer.paypal.com/docs/payouts/integrate/prerequisites/#get -access-to-paypal-payouts

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...