1

我正在开发一个 asp.net MVC5 网站,任何用户都可以使用 paypal 发送和接收付款。目前我正在处理沙盒帐户。在我的应用程序中,发件人将首先向应用程序所有者帐户付款,在满足某些条件后,付款将转发给接收者自动记帐。我想实施支付、退款、捕获/保留、争议并希望跟踪付款状态。

这是我的代码。请检查。

这用于获取配置详细信息:-

public static class PaypalConfiguration
{
    //these variables will store the clientID and clientSecret
    //by reading them from the web.config
    public readonly static string ClientId;
    public readonly static string ClientSecret;
    static PaypalConfiguration()
    {
        var config = GetConfig();
        ClientId = config["clientId"];
        ClientSecret = config["clientSecret"];
    }
    // getting properties from the web.config
    public static Dictionary<string, string> GetConfig()
    {
        return ConfigManager.Instance.GetProperties();
    }
    private static string GetAccessToken()
    {
        // getting access token from paypal                
        string accessToken = new OAuthTokenCredential
      (ClientId, ClientSecret, GetConfig()).GetAccessToken();
        return accessToken;
    }
    public static APIContext GetAPIContext()
    {
        // return apicontext object by invoking it with the accesstoken
        APIContext apiContext = new APIContext(GetAccessToken());
        apiContext.Config = GetConfig();
        return apiContext;
    }
}

退款付款代码:-

    public bool RefundCapturedAmount(string captureId, int goodRequestId)
    {
        try
        {
            var Request = _goodRequestService.GetUserRequest(UserId.Value, goodRequestId);
            APIContext apiContext = PaypalConfiguration.GetAPIContext();
            Capture capture = Capture.Get(apiContext, captureId);
            Amount amount = new Amount();

            amount.currency = "USD";
            amount.total = Convert.ToString(Request.Obj.CustomerCost);
            new Details { tax = "0", shipping = "0" };
            Refund refund = new Refund
            {
                amount = amount
            };
            refund = capture.Refund(apiContext, refund);
            string state = refund.state;
            return true;
        }
        catch (Exception ex)
        {

        }
        return false;
    }

捕获付款:-

   private Capture CapturePayment(APIContext apiContext, string payerId, string paymentId, PayPal.Api.Authorization authorization, int UserId = 0, int goodRequestId = 0)
    {
        int tempGoodRequestId = (int)Session["goodRequestId"];
        var getUserRequestResult = _goodRequestService.GetUserRequest(UserId, tempGoodRequestId);

        var capture = new Capture()
        {
            amount = new Amount()
            {
                currency = "USD",
                total = Convert.ToString(getUserRequestResult.Obj.CustomerCost)
            },
            is_final_capture = true
        };

        var responseCapture = authorization.Capture(apiContext, capture);
        return responseCapture;
    }

以及创建付款、执行付款和获取项目详细金额等:-

    [HttpGet]
    public ActionResult Pay(int goodRequestId = 0)
    {
        if (goodRequestId > 0)
        {
            var Request = _goodRequestService.GetUserRequest(UserId.Value, goodRequestId);
            if (Request != null && Request.Obj.StatusId == 5)
            {
                return RedirectToAction("Request", "Booking", new { id = goodRequestId });
            }
        }
        APIContext apiContext = PaypalConfiguration.GetAPIContext();
        PayResult result = new PayResult();

        try
        {
            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                if (goodRequestId > 0)
                {
                    Session["goodRequestId"] = goodRequestId;
                }
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
                            "/Payment/Pay?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid, UserId.Value, goodRequestId);
                var links = createdPayment.links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    Links lnk = links.Current;
                    if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        paypalRedirectUrl = lnk.href;
                    }
                }
                Session.Add(guid, createdPayment.id);
                return Redirect(paypalRedirectUrl);
            }
            else
            {

                var guid = Request.Params["guid"];

                // Using the information from the redirect, setup the payment to execute.
                var paymentId = Session[guid] as string;
                var paymentExecution = new PaymentExecution() { payer_id = payerId };
                var payment = new Payment() { id = paymentId };
                // Execute authorization.
                var executedPayment = payment.Execute(apiContext, paymentExecution);// Execute the payment
                                                                                    // Capture authorization object
                var authorization = executedPayment.transactions[0].related_resources[0].authorization;//get Authorization to get payment
                                                                                                       //capture payment
                var capture = CapturePayment(apiContext, payerId, paymentId, authorization, UserId.Value, goodRequestId);//Capture Payment here
                if (executedPayment.state.ToLower() == "approved")
                {
                    goodRequestId = (int)Session["goodRequestId"];
                    _goodRequestService.SeekerPaidUserRequest(UserId.Value, goodRequestId);
                    var getUserRequestResult = _goodRequestService.GetUserRequest(UserId.Value, goodRequestId);

                    var item = _itemDataService.GetItem(getUserRequestResult.Obj.GoodId);
                    var send = _sendMessageService.SendPaymentEmailTemplate(executedPayment, getUserRequestResult, item.Obj.GoodImageUrl);
                    PaypalPayment paydetail = GetPayDetail(executedPayment, authorization, capture, UserId.Value, item.Obj.User.Id);
                    var data = _paymentService.SaveUpdatePaypalPayment(paydetail);

                    result.IsError = false;
                    result.Message = "Success";
                    result.GoodRequestId = goodRequestId;
                    result.MailSend = send;
                    return View(result);
                }
                else
                {
                    result.IsError = true;
                    result.Message = "Failed";
                    result.GoodRequestId = goodRequestId;
                    result.MailSend = false;
                    return View(result);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private PaypalPayment GetPayDetail(Payment payment, PayPal.Api.Authorization authorization, Capture capture, int payerID, int payeeId)
    {
        PaypalPayment detail = new PaypalPayment();
        detail.PaymentPayId = payment.id;
        detail.GoodRequestId = (int)Session["goodRequestId"];
        detail.PayerId = Convert.ToString(payerID);
        detail.PayeeId = Convert.ToString(payeeId);
        detail.PaymentCart = payment.cart;
        detail.PaymentStatus = payment.state;
        detail.PaymentCreatedDate = Convert.ToDateTime(payment.create_time);
        detail.PaymentIntent = payment.intent;
        detail.PaymentUpdateDate = Convert.ToDateTime(payment.update_time);
        detail.PaymentInvoiceNumber = payment.transactions[0].invoice_number;
        detail.AuthorizationCreatedDate = Convert.ToDateTime(authorization.create_time);
        detail.AuthorizationId = authorization.id;
        detail.AuthorizationCount = 1;
        detail.AuthorizationStatus = authorization.state;
        detail.AuthorizationUpdateDate = Convert.ToDateTime(authorization.update_time);
        detail.AuthorizationValidUntill = Convert.ToDateTime(authorization.valid_until);
        detail.CaptureCreatedDate = Convert.ToDateTime(capture.create_time);
        detail.CaptureId = capture.id;
        detail.CaptureIsFinal = false;
        detail.CaptureStatus = capture.state;
        detail.CaptureUpdateDate = Convert.ToDateTime(capture.update_time);
        detail.CreateDate = DateTime.Now;
        detail.ModDate = DateTime.Now;
        detail.CreateBy = Convert.ToInt32(UserId);
        detail.ModBy = Convert.ToInt32(UserId);
        return detail;
    }
    private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
    {
        var paymentExecution = new PaymentExecution() { payer_id = payerId };
        var payment = new Payment() { id = paymentId };
        return payment.Execute(apiContext, paymentExecution);
    }
    private Payment CreatePayment(APIContext apiContext, string redirectUrl, int userid, int goodrequestid)
    {
        var getUserRequestResult = _goodRequestService.GetUserRequest(userid, goodrequestid);
        //similar to credit card create itemlist and add item objects to it
        var itemList = new ItemList() { items = new List<Item>() };
        itemList.items.Add(new Item()
        {
            name = getUserRequestResult.Obj.GoodName,
            currency = "USD",
            price = Convert.ToString(getUserRequestResult.Obj.CustomerCost),
            quantity = "1",
            sku = "sku"
        });
        var payer = new Payer() { payment_method = "paypal" };
        // Configure Redirect Urls here with RedirectUrls object
        var redirUrls = new RedirectUrls()
        {
            cancel_url = redirectUrl,
            return_url = redirectUrl
        };
        // similar as we did for credit card, do here and create details object
        //var details = new Details()
        //{
        //    tax = "0.20",
        //    shipping = Convert.ToString(getUserRequestResult.Obj.SecurityDeposit),
        //    subtotal = Convert.ToString(getUserRequestResult.Obj.SharerCost),
        //};
        // similar as we did for credit card, do here and create amount object
        var amount = new Amount()
        {
            currency = "USD",
            total = Convert.ToString(getUserRequestResult.Obj.CustomerCost), // Total must be equal to sum of shipping, tax and subtotal.
                                                                             //details = details
        };
        var transactionList = new List<Transaction>();
        transactionList.Add(new Transaction()
        {
            description = "Transaction description.",
            invoice_number = Convert.ToString((new Random()).Next(100000)),
            amount = amount,
            item_list = itemList
        });
        var payment = new Payment()
        {
            intent = "authorize",
            payer = payer,
            transactions = transactionList,
            redirect_urls = redirUrls
        };
        // Create a payment using a APIContext
        return payment.Create(apiContext);

    }
4

0 回答 0