简体   繁体   中英

Which PayPal Payment method should I use?

I have an application of my client in which he has used PaypalAdaptivePayments but the API stopped working since 2 years back, now this project is within my hands so I started investigating the API and found that PayPal has deprecated the usage of this API, actually in his application what he tends to have is this:

1- There is only 1 account of this Vendor in PayPal in which the amount debits and credits from the application.

2- Basically this application is sort of Ride booking web app, in which the customer books a ride and then deposits X amount into the wallet (remember this wallet is connected to the vendor account I have mentioned in point 1).

3- When the customer ride is completed he marks the amount as to be cleared for DEBIT, then this decision is saved into my database but till this stage the driver is not reimbursed.

4- The ADMIN logs in to this site and then he goes to the drivers list and then select an appropriate driver and then he puts in his X COMMISSION for this ride, and then clicks on PAY so with this action the driver gets paid. Note: This is a commission based procedure so for example the RIDE which an customer has booked was of USD100 so he credited this amount into the VENDORS wallet, then when the VENDOR is about to lend payment to the DRIVER he enters his own commission for eg 10% , so the DRIVER would be paid USD90 only. This payment is also deducted from the VENDORS wallet and then transferred to the DRIVER.

Now after painting the scenario, can you please guide me which API is best suited for this scenario? as there are LOADS of PayPal API and SDK.... I am totally lost in their world, Please keep in mind my application is build in ASP.NET MVC.

Please note: My Client(Vendor) already owns a SANDBOX and a verified BUSINESS ACCOUNT in PayPal.

Warm Regards. Emad.

For community ease I am sharing my code:

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. Use PayPal Checkout for receiving money: https://developer.paypal.com/docs/checkout/ --- for a server-based API integration see the front-end UI at https://developer.paypal.com/demo/checkout/#/pattern/server

  2. Request access to Payouts for sending money: https://developer.paypal.com/docs/payouts/integrate/prerequisites/#get-access-to-paypal-payouts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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