Let's you execute a PayPal Account based Payment resource with the payer_id obtained from web approval url.

See PayPal Developer documentation for more information.

상속: PayPalSerializableObject
        public ActionResult PaymentWithPayPal(string donationAmt)
        {          
            //OAuthTokenCredential tokenCredential = new OAuthTokenCredential("AeJs4Inwk1Pn8ZNhkWiSLwerx4K64E1PD5TtL4FF7XImtEZ29aAWBTxYOVIBWxEXlW6FycnBz3U7J8jQ", "ENerw7v3F1YT1w5YRYHRPCbjfVSpAbvHVTJFfqc0jWPyeq8hcgmvaZn-1T1WzklDVqw7Pd7MGp3KEQXO");
            //string accessToken = tokenCredential.GetAccessToken();

            // Get a reference to the config
            var config = ConfigManager.Instance.GetProperties();

            // Use OAuthTokenCredential to request an access token from PayPal
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);

            try
            {
                string payerId = Request.Params["PayerID"];
                Payment payment = null;

                if (string.IsNullOrEmpty(payerId))
                {

                    // ###Items
                    // Items within a transaction.
                    Item item = new Item();
                    item.name = "Item Name";
                    item.currency = "USD";
                    item.price = donationAmt;
                    item.quantity = "1";
                    item.sku = "sku";

                    List<Item> itms = new List<Item>();
                    itms.Add(item);
                    ItemList itemList = new ItemList();
                    itemList.items = itms;

                    // ###Payer
                    // A resource representing a Payer that funds a payment
                    // Payment Method
                    // as `paypal`
                    Payer payr = new Payer();
                    payr.payment_method = "paypal";
                    Random rndm = new Random();
                    var guid = Convert.ToString(rndm.Next(100000));

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Donations/DonationSuccessView?";

                    // # Redirect URLS
                    RedirectUrls redirUrls = new RedirectUrls();
                    redirUrls.cancel_url = baseURI + "guid=" + guid;
                    redirUrls.return_url = baseURI + "guid=" + guid;

                    // ###Details
                    // Let's you specify details of a payment amount.
                    Details details = new Details();
                    details.tax = "0";
                    details.shipping = "0";
                    details.subtotal = donationAmt;

                    // ###Amount
                    // Let's you specify a payment amount.
                    Amount amnt = new Amount();
                    amnt.currency = "USD";
                    // Total must be equal to sum of shipping, tax and subtotal.
                    amnt.total = donationAmt + ".00";
                    amnt.details = details;

                    // ###Transaction
                    // A transaction defines the contract of a
                    // payment - what is the payment for and who
                    // is fulfilling it. 
                    List<Transaction> transactionList = new List<Transaction>();
                    Transaction tran = new Transaction();
                    tran.description = "Donation";
                    tran.amount = amnt;
                    tran.item_list = itemList;
                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(tran);

                    // ###Payment
                    // A Payment Resource; create one using
                    // the above types and intent as `sale` or `authorize`
                    payment = new Payment();
                    payment.intent = "sale";
                    payment.payer = payr;
                    payment.transactions = transactionList;
                    payment.redirect_urls = redirUrls;

                    var createdPayment = payment.Create(apiContext);
                    string paypalRedirectUrl = null;
                    var links = createdPayment.links.GetEnumerator();
                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    var guid = Request.Params["guid"];
                    var paymentId = Session[guid] as string;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var pymnt = new Payment() { id = paymentId };
                    var executedPayment = pymnt.Execute(apiContext, paymentExecution);
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return View("DonationFailureView");
            }
            return View("DonationSuccessView");
        }
예제 #2
1
        //Execute payment
        public Payment ConfirmPayment(string payerId, string paymentId)
        {
            var paymentExecution = new PaymentExecution
            {
                payer_id = payerId
            };

            var payment = new Payment { id = paymentId };

            return payment.Execute(Api, paymentExecution);
        }
        public async Task<ActionResult> PaypalReturn()
        {
            string payerId = Request.Params["PayerID"];
            var guid = Request.Params["guid"];
            var success = Request.Params["Success"];

            if (guid != null && success != null)
            {
                var isSuccess = Convert.ToBoolean(Request.QueryString["Success"]);
                var transactionID = Session[guid] as string;

                //If client buy succesful, process here
                if (isSuccess)
                {
                    var helper = new PaypalHelper();
                    APIContext apiContext = helper.GetGetAPIContext();

                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var payment = new Payment() { id = transactionID };

                    //We need to execute to submit paypal about client's transaction
                    //If we don't execute paypal, the transaction will be cancel, the buyer don't charge money
                    //--------------------------------------------------------------
                    try
                    {
                        var executedPayment = payment.Execute(apiContext, paymentExecution);
                        if (executedPayment.state.ToLower() != "approved")
                        {
                            //Save information of transaction into Database
                            //when executedPayment is not approved
                            //---------------------------------------------
                            var transactionId = Session["transactionId"];
                            var goEatApi = GoEatApi.Instance;
                            // goEatApi.UpdateMainTransactionStatus(Int32.Parse(transactionId.ToString()), ConstantValues.S_CANCELLED);
                            return View("PaypalFailure");
                        }
                        else
                        {
                            //Save information of transaction into Database
                            //State of transaction is approved
                            //---------------------------------------------
                            var goEatApi = GoEatApi.Instance;
                            var transactionId = Session["transactionId"];

                            var confirmTransactionResult = goEatApi.GetConfirmTokenTransactionById(Int32.Parse(transactionId.ToString()));
                            if (confirmTransactionResult.Succeeded)
                            {
                                if (confirmTransactionResult.Succeeded)
                                {
                                    goEatApi.FinishPaypalFinalTransaction(
                                        confirmTransactionResult.Data.paypal_payment_id,
                                        confirmTransactionResult.Data.id,
                                        confirmTransactionResult.Data.customer_id,
                                        confirmTransactionResult.Data.token_amount);

                                    var model = new PaypalSuccess() { amount = confirmTransactionResult.Data.token_amount };

                                    var customer = goEatApi.GetUserById(confirmTransactionResult.Data.customer_id);

                                    //create api recording
                                    await goEatApi.RecordTokenTransaction(new GRecordTokenTransaction
                                    {
                                        username = customer.Data.Profile.account,
                                        order_id = confirmTransactionResult.Data.paypal_payment_id,
                                        gtoken_transaction_id = string.Empty,
                                        token_type = ConstantValues.S_SUGAR_TOKEN,
                                        transaction_type = ConstantValues.S_TRANSACTION_TYPE_CONSUMPTION,
                                        amount = confirmTransactionResult.Data.token_amount,
                                        description = ConstantValues.S_DESCRIPTION_TOPUP_TOKEN
                                    });

                                    return View("PaypalSuccess", model);
                                }
                            }
                        }
                    }
                    catch
                    {
                        return View("PaypalFailure");
                    }

                }
                //If client cancel, process here
                else
                {
                    //Save information of transaction into Database
                    //When client cancel, Use transactionID to trace
                    //---------------------------------------------
                    var transactionId = Session["transactionId"];
                    var goEatApi = GoEatApi.Instance;
                    //goEatApi.UpdateMainTransactionStatus(Int32.Parse(transactionId.ToString()), ConstantValues.S_CANCELLED);

                    return RedirectToAction("buytoken");
                }
            }
            //All params is not valid, return valid view here
            return View("PaypalFailure");
        }
예제 #4
1
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                var payer = new Payer() { payment_method = "paypal" };

                // # Redirect URLS
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/OrderSample.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;
                var redirUrls = new RedirectUrls()
                {
                    cancel_url = redirectUrl + "&cancel=true",
                    return_url = redirectUrl
                };

                // ###Amount
                // Lets you specify a payment amount.
                var amount = new Amount()
                {
                    currency = "USD",
                    total = "5.00"
                };

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                var transactionList = new List<Transaction>();

                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(new Transaction()
                {
                    description = "Transaction description.",
                    amount = amount
                });

                // ###Payment
                // Create a payment with the intent set to 'order'
                var payment = new Payment()
                {
                    intent = "order",
                    payer = payer,
                    transactions = transactionList,
                    redirect_urls = redirUrls
                };

                // ^ Ignore workflow code segment
                #region Track Workflow
                flow.AddNewRequest("Create payment order", payment);
                #endregion

                // Create the payment resource.
                var createdPayment = payment.Create(apiContext);

                // ^ Ignore workflow code segment
                #region Track Workflow
                flow.RecordResponse(createdPayment);
                #endregion

                // Use the `approval_url` link provided by the returned object to approve the order payment.
                var links = createdPayment.links.GetEnumerator();
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        this.flow.RecordRedirectUrl("Redirect to PayPal to approve the order...", link.href);
                    }
                }
                Session.Add("flow-" + guid, this.flow);
                Session.Add(guid, createdPayment.id);
            }
            else
            {
                var guid = Request.Params["guid"];
                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("Order payment approved successfully.");
                #endregion

                // Execute the order
                var paymentId = Session[guid] as string;
                var paymentExecution = new PaymentExecution() { payer_id = payerId };
                var payment = new Payment() { id = paymentId };

                // ^ Ignore workflow code segment
                #region Track Workflow
                flow.AddNewRequest("Execute payment", payment);
                #endregion

                // Execute the order payment.
                var executedPayment = payment.Execute(apiContext, paymentExecution);

                // ^ Ignore workflow code segment
                #region Track Workflow
                flow.RecordResponse(executedPayment);
                #endregion

                // Get the information about the executed order from the returned payment object.
                this.order = executedPayment.transactions[0].related_resources[0].order;
                this.amount = executedPayment.transactions[0].amount;

                // Once the order has been executed, an order ID is returned that can be used
                // to do one of the following:
                // this.AuthorizeOrder();
                // this.CaptureOrder();
                // this.VoidOrder();
                // this.RefundOrder();

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
예제 #5
0
 public static PaymentExecution GetPaymentExecution()
 {
     var transactions = new List<Transaction>();
     transactions.Add(TransactionTest.GetTransaction());
     PaymentExecution execution = new PaymentExecution();
     execution.payer_id = PayerInfoTest.GetPayerInfo().payer_id;
     execution.transactions = transactions;
     return execution;
 }
        public Payment ConfirmarPagamento(Guid siteId, string token, string idPagamento, string idPagador)
        {
            var apiContext = _configuradorPayPal.GetApiContext();

            var paymentExecution = new PaymentExecution { payer_id = idPagador };
            var payment = new Payment { id = idPagamento };

            var executedPayment = payment.Execute(apiContext, paymentExecution);

            return executedPayment;
        }
예제 #7
0
        /// <summary>
        /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="paymentId">ID of the payment to execute.</param>
        /// <param name="paymentExecution">PaymentExecution</param>
        /// <returns>Payment</returns>
        public static Payment Execute(APIContext apiContext, string paymentId, PaymentExecution paymentExecution)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(paymentId, "paymentId");
            ArgumentValidator.Validate(paymentExecution, "paymentExecution");

            // Configure and send the request
            var pattern      = "v1/payments/payment/{0}/execute";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { paymentId });

            return(PayPalResource.ConfigureAndExecute <Payment>(apiContext, HttpMethod.POST, resourcePath, paymentExecution.ConvertToJson()));
        }
        public static Payment ExecutePayment(string paymentId, string payerId)
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            var apiContext = PaypalConfig.GetAPIContext();

            var paymentExecution = new PaymentExecution() { payer_id = payerId };
            var payment = new Payment() { id = paymentId };

            // Execute the payment.
            var executedPayment = payment.Execute(apiContext, paymentExecution);

            return executedPayment;
        }
예제 #9
0
 /// <summary>
 /// Executes, or completes, a PayPal payment that the payer has approved. You can optionally update selective payment information when you execute a payment.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <param name="paymentExecution">PaymentExecution</param>
 /// <returns>Payment</returns>
 public Payment Execute(APIContext apiContext, PaymentExecution paymentExecution)
 {
     return Payment.Execute(apiContext, this.id, paymentExecution);
 }
예제 #10
0
        /// <summary>
        /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="paymentId">ID of the payment to execute.</param>
        /// <param name="paymentExecution">PaymentExecution</param>
        /// <returns>Payment</returns>
        public static Payment Execute(APIContext apiContext, string paymentId, PaymentExecution paymentExecution)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(paymentId, "paymentId");
            ArgumentValidator.Validate(paymentExecution, "paymentExecution");

            // Configure and send the request
            var pattern = "v1/payments/payment/{0}/execute";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { paymentId });
            return PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, paymentExecution.ConvertToJson());
        }
예제 #11
0
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                // ###Redirect URLS
                // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/SaleRefund.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                var payment = new Payment
                {
                    intent = "sale",
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List<Transaction>
                    {
                        new Transaction
                        {
                            description = "Transaction description.",
                            invoice_number = Common.GetRandomInvoiceNumber(),
                            amount = new Amount
                            {
                                currency = "USD",
                                total = "100.00",
                                details = new Details
                                {
                                    tax = "15",
                                    shipping = "10",
                                    subtotal = "75"
                                }
                            },
                            item_list = new ItemList
                            {
                                items = new List<Item>
                                {
                                    new Item
                                    {
                                        name = "Item Name",
                                        currency = "USD",
                                        price = "15",
                                        quantity = "5",
                                        sku = "sku"
                                    }
                                }
                            }
                        }
                    },
                    redirect_urls = new RedirectUrls
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    }
                };

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                // Create a payment using a valid APIContext
                var createdPayment = payment.Create(apiContext);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdPayment);
                #endregion

                // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                var links = createdPayment.links.GetEnumerator();
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
                    }
                }
                Session.Add(guid, createdPayment.id);
                Session.Add("flow-" + guid, this.flow);
            }
            else
            {
                var guid = Request.Params["guid"];

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("PayPal payment approved successfully.");
                #endregion

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

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Execute PayPal payment", payment);
                #endregion

                // Execute the payment.
                var executedPayment = payment.Execute(apiContext, paymentExecution);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(executedPayment);
                #endregion

                // A refund transaction. Use the amount to create a refund object
                var refund = new Refund()
                {
                    amount = new Amount()
                    {
                        currency = "USD",
                        total = "100.00"
                    }
                };

                // Get the sale resource from the executed payment's list of related resources.
                var sale = executedPayment.transactions[0].related_resources[0].sale;

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Refund sale", refund, string.Format("URI: /v1/payments/sale/{0}/refund", sale.id));
                #endregion
            
                // Refund by posting Refund object using a valid APIContext
                var response = sale.Refund(apiContext, refund);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(response);
                #endregion

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Get the details of the payment", description: "ID: " + executedPayment.id);
                #endregion

                var retrievedPayment = Payment.Get(apiContext, executedPayment.id);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(retrievedPayment);
                #endregion

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                // Create the web experience profile
                var profile = new WebProfile
                {
                    name = Guid.NewGuid().ToString(),
                    presentation = new Presentation
                    {
                        brand_name = "PayPal .NET SDK",
                        locale_code = "US",
                        logo_image = "https://raw.githubusercontent.com/wiki/paypal/PayPal-NET-SDK/images/homepage.jpg"
                    },
                    input_fields = new InputFields
                    {
                        no_shipping = 1
                    }
                };


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create new web experience profile (NOTE: This only needs to be done once)", profile);
                #endregion

                var createdProfile = profile.Create(apiContext);


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdProfile);
                #endregion

                // Setup the redirect URI to use. The guid value is used to keep the flow information.
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                baseURI += "guid=" + guid + "&webProfileId=" + createdProfile.id;

                // Create the payment
                var payment = new Payment
                {
                    intent = "sale",
                    experience_profile_id = createdProfile.id,
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List<Transaction>
                {
                    new Transaction
                    {
                        description = "Ticket information.",
                        item_list = new ItemList
                        {
                            items = new List<Item>
                            {
                                new Item
                                {
                                    name = "Concert ticket",
                                    currency = "USD",
                                    price = "20.00",
                                    quantity = "2",
                                    sku = "ticket_sku"
                                }
                            }
                        },
                        amount = new Amount
                        {
                            currency = "USD",
                            total = "45.00",
                            details = new Details
                            {
                                tax = "5.00",
                                subtotal = "40.00"
                            }
                        }
                    }
                },
                    redirect_urls = new RedirectUrls
                    {
                        return_url = baseURI + "&return=true",
                        cancel_url = baseURI + "&cancel=true"
                    }
                };


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                var createdPayment = payment.Create(apiContext);


                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdPayment);
                #endregion

                // Use the returned payment's approval URL to redirect the buyer to PayPal and approve the payment.
                var approvalUrl = createdPayment.GetApprovalUrl();

                this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", approvalUrl);
                Session.Add(guid, createdPayment.id);
                Session.Add("flow-" + guid, this.flow);
            }
            else
            {
                var guid = Request.Params["guid"];
                var webProfileId = Request.Params["webProfileId"];
                var isReturnSet = Request.Params["return"];

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("PayPal payment approved successfully.");
                #endregion

                if (string.IsNullOrEmpty(isReturnSet))
                {
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordApproval("PayPal payment canceled by buyer.");
                    #endregion
                }
                else
                {
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordApproval("PayPal payment approved successfully.");
                    #endregion

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

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.AddNewRequest("Execute PayPal payment", payment);
                    #endregion

                    // Execute the payment.
                    var executedPayment = payment.Execute(apiContext, paymentExecution);
                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    this.flow.RecordResponse(executedPayment);
                    #endregion
                }

                // Cleanup - Because there's a limit to the number of experience profile IDs you can create,
                // we'll delete the one that was created for this sample.
                WebProfile.Delete(apiContext, webProfileId);

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
 public Payment ExecutePayPalPayment( string payerId, string paymentId)
 {
     var paymentExecution = new PaymentExecution { payer_id = payerId };
     var payment = new Payment() { id = paymentId };
     return payment.Execute(PayPalConfiguration.GetApiContext(), paymentExecution);
 }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPalWithDiscount.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                var payment = new Payment
                {
                    intent = "sale",
                    // ###Payer
                    // A resource representing a Payer that funds a payment
                    // Payment Method as `paypal`
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List<Transaction>
                    {
                        // ###Transaction
                        // A transaction defines the contract of a
                        // payment - what is the payment for and who
                        // is fulfilling it. 
                        new Transaction
                        {
                            description = "Transaction description.",
                            invoice_number = Common.GetRandomInvoiceNumber(),
                            // ###Amount
                            // Let's you specify a payment amount.
                            amount = new Amount
                            {
                                currency = "USD",
                                // Total must be equal to sum of shipping, tax and subtotal.
                                total = "92.50",
                                // ###Details
                                // Let's you specify details of a payment amount.
                                details = new Details
                                {
                                    tax = "15",
                                    shipping = "10",
                                    subtotal = "67.50"
                                }
                            },
                            // ###Items
                            // Items within a transaction.
                            item_list = new ItemList
                            {
                                items = new List<Item>
                                {
                                    new Item
                                    {
                                        name = "Item Name",
                                        currency = "USD",
                                        price = "15.00",
                                        quantity = "5",
                                        sku = "sku"
                                    },
                                    new Item
                                    {
                                        name = "Special 10% Discount",
                                        currency = "USD",
                                        price = "-7.50",
                                        quantity = "1",
                                        sku = "sku_discount"
                                    }
                                }
                            }
                        }
                    },
                    // ###Redirect URLS
                    // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                    redirect_urls = new RedirectUrls
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    }
                };

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                // Create a payment using a valid APIContext
                var createdPayment = payment.Create(apiContext);

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(createdPayment);
                #endregion

                // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                var links = createdPayment.links.GetEnumerator();
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
                    }
                }
                Session.Add(guid, createdPayment.id);
                Session.Add("flow-" + guid, this.flow);
            }
            else
            {
                var guid = Request.Params["guid"];

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow = Session["flow-" + guid] as RequestFlow;
                this.RegisterSampleRequestFlow();
                this.flow.RecordApproval("PayPal payment approved successfully.");
                #endregion

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

                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.AddNewRequest("Execute PayPal payment", payment);
                #endregion

                // Execute the payment.
                var executedPayment = payment.Execute(apiContext, paymentExecution);
                // ^ Ignore workflow code segment
                #region Track Workflow
                this.flow.RecordResponse(executedPayment);
                #endregion

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
예제 #15
0
        public IHttpActionResult GetPaymentApproved(string paymentId, string token, string PayerId,string userId)
        {
            var config = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);

            apiContext.Config = config;

            Payment payment = Payment.Get(apiContext, paymentId);

            PaymentExecution paymentExecution = new PaymentExecution();
            paymentExecution.payer_id = PayerId;

            try
            {
                Payment executedPayment = payment.Execute(apiContext, paymentExecution); //this PAYLEMT (EXECUTE) CAN FAIL
                if(executedPayment.state != "approved")
                {
                    return BadRequest("PayPal payment has failed. Please try again!");
                }
            }
            catch
            {
                return BadRequest("PayPal payment failed!");
            }

            
            //Set unpaid rooms to paid

            List<RoomAvailability> listOfUnpaidRooms = new List<RoomAvailability>();
            List<ReservationsPaymentAPI> listOfUnpaidRoomsFullDetails = new List<ReservationsPaymentAPI>();
            if (userId != null)
            {
                listOfUnpaidRooms = db.RoomAvailabilities.Where(x => x.UserId == userId && x.IsPaid == false).ToList();
            }
            if (listOfUnpaidRooms.Count > 0)
            {
                foreach (var room in listOfUnpaidRooms)
                {
                    room.IsPaid = true;
                    room.PayPalPaymentId = paymentId;
                    db.Entry(room).State = System.Data.Entity.EntityState.Modified;
                }
            }
            db.SaveChanges();

            string returnUrl = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/#/paymentConfirmation");

            return Redirect(returnUrl);
        }
예제 #16
0
 public Payment ExecutePayment(string payerId, string paymentId)
 {
     var paymentExecution = new PaymentExecution { payer_id = payerId };
     var payment = new Payment { id = paymentId };
     return payment.Execute(_apiContext, paymentExecution);
 }
예제 #17
0
        private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
        {
            var paymentExecution = new PaymentExecution() { payer_id = payerId };
            this.payment = new Payment() { id = paymentId };

            Session["Cart"] = new List<CartItemViewModel>();
            return this.payment.Execute(apiContext, paymentExecution);
        }
예제 #18
0
        public bool ConfirmPayment(string paymentId, string token, string PayerID)
        {
           // var panier = await Context.Panier.FirstOrDefaultAsync(u => u.owner == UserId && u.Status == PanierStatus.Active && u.paymentId == paymentId);

            if (  !string.IsNullOrEmpty(paymentId) && !string.IsNullOrEmpty(PayerID))
            {
                //configuracion de paypal
                APIContext api = getPaypalContext();

                PayPal.Api.Payment payment = PayPal.Api.Payment.Get(api, paymentId);
                PaymentExecution pymntExecution = new PaymentExecution();
                pymntExecution.payer_id = (PayerID);
                PayPal.Api.Payment executedPayment = payment.Execute(api, pymntExecution);
                if (executedPayment != null && executedPayment.state == "approved")
                {
                    ///crear la factura
                    var total = payment.transactions.Sum(t => Convert.ToDecimal(t.amount.total));
                    
                    //.Status = PanierStatus.Confirmed;
                    //panier.PayerID = PayerID;
                    //await SaveAsync();
                    return true;
                }

            }

            return false;
        }
예제 #19
0
        public override PaymentResponse MakePayment()
        {
            try
            {
                #region Create Payment
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.DefaultConnectionLimit = 9999;

                var config = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();

                var apiContext = new APIContext(accessToken);
                apiContext.Config = ConfigManager.Instance.GetProperties();
                apiContext.Config["connectionTimeout"] = "30000";
                if (apiContext.HTTPHeaders == null)
                {
                    apiContext.HTTPHeaders = new Dictionary<string, string>();
                }
                //apiContext.HTTPHeaders["some-header-name"] = "some-value";

                string payerId = this.PayerId;
                if (string.IsNullOrEmpty(payerId))
                {
                    // ###Items
                    // Items within a transaction.
                    var itemList = new ItemList()
                    {
                        items = new List<Item>()
                    {
                        new Item()
                        {
                            name = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value
                            : "Credits",
                            currency = "USD",
                            price = this.Amount.ToString(),
                            quantity = "1",
                            sku = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:TransactionTitle"])).Value
                            : "Credits"
                        }
                    }
                    };

                    // ###Payer
                    // A resource representing a Payer that funds a payment
                    // Payment Method
                    // as `paypal`
                    var payer = new Payer() { payment_method = "paypal" };

                    // ###Redirect URLS
                    // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                    //var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
                    var baseURI = CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value != null
                            ? CompanyConfigurationSettings.CompanyConfigList.Find(cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_PayPal:ReturnUrl"])).Value
                            : "http://www.thedesignheroes.com/PaymentWithPayPal.aspx?";
                    var guid = Convert.ToString((new Random()).Next(100000));
                    var redirectUrl = baseURI + "guid=" + guid;
                    var redirUrls = new RedirectUrls()
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    };

                    // ###Details
                    // Let's you specify details of a payment amount.
                    var details = new Details()
                    {
                        tax = this.TaxAmount.ToString(),
                        shipping = "0",
                        subtotal = this.Amount.ToString()
                    };

                    // ###Amount
                    // Let's you specify a payment amount.
                    var amount = new Amount()
                    {
                        currency = "USD",
                        total = this.Amount.ToString(),//"100.00", // Total must be equal to sum of shipping, tax and subtotal.
                        details = details
                    };

                    // ###Transaction
                    // A transaction defines the contract of a
                    // payment - what is the payment for and who
                    // is fulfilling it. 
                    var transactionList = new List<Transaction>();

                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(new Transaction()
                    {
                        description = "Transaction description.",
                        invoice_number = String.Format(String.Format("{0}:{1}", this.CompanyId.ToString(), guid)),
                        amount = amount,
                        item_list = itemList
                    });

                    // ###Payment
                    // A Payment Resource; create one using
                    // the above types and intent as `sale` or `authorize`
                    var payment = new PayPal.Api.Payment()
                    {
                        intent = "sale",
                        payer = payer,
                        transactions = transactionList,
                        redirect_urls = redirUrls
                    };

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.AddNewRequest("Create PayPal payment", payment);
                    #endregion

                    // Create a payment using a valid APIContext
                    var createdPayment = payment.Create(apiContext);

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.RecordResponse(createdPayment);
                    #endregion

                    // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                    var links = createdPayment.links.GetEnumerator();
                    string responseLink = "";
                    while (links.MoveNext())
                    {
                        var link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            responseLink = link.href;
                            //this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
                        }
                    }
                    //Session.Add(guid, createdPayment.id);
                    //Session.Add("flow-" + guid, this.flow);
                    #endregion

                    return new PaymentResponse()
                    {
                        AuthCode = createdPayment.state,// executePayment.token,
                        Message = createdPayment.token, // executePayment.state,
                        MessageCode = createdPayment.intent,
                        ResponseCode = responseLink,
                        TransactionId = guid,
                        TransactionResult = createdPayment.state
                    };
                }
                else
                {
                    #region Execute Payment
                    //var guid = Request.Params["guid"];

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow = Session["flow-" + guid] as RequestFlow;
                    //this.RegisterSampleRequestFlow();
                    //this.flow.RecordApproval("PayPal payment approved successfully.");
                    #endregion

                    // Using the information from the redirect, setup the payment to execute.
                    var paymentId = this.PaymentGuid;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var payment = new PayPal.Api.Payment() { id = this.PaymentId };

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.AddNewRequest("Execute PayPal payment", payment);
                    #endregion

                    // Execute the payment.
                    var executedPayment = payment.Execute(apiContext, paymentExecution);

                    // ^ Ignore workflow code segment
                    #region Track Workflow
                    //this.flow.RecordResponse(executedPayment);
                    #endregion
                    #endregion

                    return new PaymentResponse()
                    {
                        AuthCode = executedPayment.cart,
                        Message = executedPayment.payer.status,
                        MessageCode = executedPayment.intent,
                        ResponseCode = executedPayment.links[0].href,
                        TransactionId = executedPayment.id,
                        TransactionResult = executedPayment.state,
                    };
                }
            }
            catch (System.Exception exc)
            {
                return new PaymentResponse()
                {
                    ErrorMessage = exc.Message,
                    Message = exc.StackTrace,
                    TransactionResult = String.Format("Paypal Error:{0}--{1}", exc.Message, exc.StackTrace)
                };
            }
        }
예제 #20
0
        // GET: api/PayPal
        public IHttpActionResult PaymentApproved(string userId, string paymentId, string token, string PayerID)
        {
            var apiContext = GetApiContext();
            if (apiContext == null)
                return StatusCode(HttpStatusCode.NotAcceptable);

            Payment exePayment = null;
            try
            {
                Payment payment = Payment.Get(apiContext, paymentId);
                PaymentExecution exe = new PaymentExecution();
                exe.payer_id = PayerID;
                exePayment = payment.Execute(apiContext, exe);  //execute payment
            }
            catch
            {
                return StatusCode(HttpStatusCode.NotAcceptable);
            }

            if (exePayment.state == "approved")  //if payment is approved set cart purchased to true
            {                                    //and all items set to purchased true 
                var cart = EditCart(userId, paymentId);

                Mail mail = db.Mails.Where(x => x.Subject == "Payment").First();

                MailBulider(userId, cart.Id, mail, exePayment.state, paymentId);
                return Redirect(String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/#/profile"));
            }

            return Redirect(String.Format("http://{0}", HttpContext.Current.Request.Url.Authority));
        }
 private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
 {
     var paymentExecution = new PaymentExecution() { payer_id = payerId };
     payment = new Payment() { id = paymentId };
     return payment.Execute(apiContext, paymentExecution);
 }
예제 #22
0
 /// <summary>
 /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <param name="paymentExecution">PaymentExecution</param>
 /// <returns>Payment</returns>
 public Payment Execute(APIContext apiContext, PaymentExecution paymentExecution)
 {
     return(Payment.Execute(apiContext, this.id, paymentExecution));
 }