Lets you create, process and manage payments.

See PayPal Developer documentation for more information.

Inheritance: PayPalRelationalObject
        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");
        }
        public static Payment CreatePayment(string baseUrl, string intent)
        {
            // ### 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 = PayPalConfiguration.GetAPIContext();

            // Payment Resource
            var payment = new Payment()
            {
                intent = intent,    // `sale` or `authorize`
                payer = new Payer() { payment_method = "paypal" },
                transactions = GetTransactionsList(),
                redirect_urls = GetReturnUrls(baseUrl, intent)
            };

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

            return createdPayment;
        }
        /// <summary>
        /// https://developer.paypal.com/docs/api/#create-a-payment
        /// </summary>
        /// <param name="payment"></param>
        /// <returns></returns>
        public PayPal<Payment> Create(Payment payment)
        {
            PayPal<Payment> paypal = new PayPal<Payment>();

            try
            {
                PaymentRepository paymentRepository = new PaymentRepository();

                if (System.Diagnostics.Debugger.IsAttached)
                    payment = DEBUG_Create();

                paypal.Object = paymentRepository.Create(payment);

                return paypal;
            }
            catch (PayPal.HttpException he)
            {
                //{"name":"INVALID_RESOURCE_ID","message":"The requested resource ID was not found","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#INVALID_RESOURCE_ID","debug_id":"e035690ac842e"}
                if (he.Response.Contains("INVALID_RESOURCE_ID"))
                {
                    paypal.Validations.Add("paymentCode", "Invalid ID");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return paypal;
        }
Example #4
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");
        }
        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/).
            }
        }
        public void Pay_Pass_With_PayPal_When_Valid_CreditCard()
        {
            var successfulPayment = new Payment {state = "approved"};
            _payPalMocked.Setup(p => p.CreateCreditCardPayment(It.IsAny<Order>(), It.IsAny<CardDetails>())).Returns(successfulPayment);

            _controller.ControllerContext.HttpContext.Session["CreditCard"] = new CardDetails();

            var result = _controller.CompletePayWithCreditCard() as ViewResult;

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.AreEqual("PaymentSuccess", result.ViewName);
        }
        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;
        }
        public void Complete_Pay_With_PayPal_Account_When_Passed()
        {
            var successfulPayment = new Payment { state = "approved" };
            _payPalMocked.Setup(p => p.ExecutePayPalPayment(It.IsAny<string>(), It.IsAny<string>())).Returns(successfulPayment);

            _controller.ControllerContext.HttpContext.Session["PayerID"] = "1";
            _controller.ControllerContext.HttpContext.Session["guid"] = "2";

            var result = _controller.CompletePayWithPayPal() as ViewResult;

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.AreEqual("PaymentSuccess", result.ViewName);
        }
        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;
        }
        public static Payment CreatePayment(string fileName, Currency currency, decimal price, int quantity, string fileId, string userId)
        {
            var apiContext = PaypalConfig.GetAPIContext();

            // Payment Resource
            var payment = new Payment()
            {
                intent = "Order",
                payer = new Payer() { payment_method = "paypal" },
                transactions = GetTransactionsList(fileName, currency, price.ToString(), quantity.ToString(), fileId, userId),
                redirect_urls = GetReturnUrls()
            };

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

            return createdPayment;
        }
Example #12
0
        public static Payment GetCardPaymentDetailsForPaypal(double amount)
        {
            Item cardItem = CreateCardItem(amount);

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

            CreditCard crdtCard = GetPaymentCardDetails();
            Transaction tran = GetCardTransactionDetails(itemList, amount);

            // Now, we have to make a list of trasaction and add the trasactions object
            // to this list. You can create one or more object as per your requirements

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payr;
            payment.transactions = transactions;

            return payment;
        }
        public ActionResult Payment(Models.Payment model)
        {
            //Dictionary<string, string> payPalConfig = new Dictionary<string, string>();
            //payPalConfig.Add("mode", "sandbox");
            //OAuthTokenCredential tokenCredential = new AuthTokenCredential("AXVrBytGm6RdmOYfcUFM-VoOa8TvQhVYN6-TapoUzU2oErEpO0XzbYn8qD26R3iFduECZqOQmB78bZbS", "EGz3u0h-poL7i3MbLUQQXgqiYPEbbdzX95h57JzlnKrjKRV1-MNLPApqgKt30Y7VWmgwb5UxFWja0__2", payPalConfig);
            //string accessToken = tokenCredential.GetAccessToken();
            var apiContext = Configuration.GetAPIContext();
            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    // ###Items
                    // Items within a transaction.
                    var itemList = new PayPal.Api.ItemList()
                    {
                        items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "Mezo Experts",
                            currency = "USD",
                            price = model.Amount.ToString(),
                            quantity = "1",
                            sku = "sku"
                        }
                    }
                    };

                    // ###Payer
                    // A resource representing a Payer that funds a payment
                    // Payment Method
                    // as `paypal`
                    var payer = new PayPal.Api.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 + "/Tutors/AccountSettings?";
                    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 PayPal.Api.Details()
                    {
                        tax = "0",
                        shipping = "0",
                        subtotal = model.Amount.ToString()
                    };

                    // ###Amount
                    // Let's you specify a payment amount.
                    var amount = new PayPal.Api.Amount()
                    {
                        currency = "USD",
                        total = model.Amount.ToString(), // 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<PayPal.Api.Transaction>();

                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(new PayPal.Api.Transaction()
                    {
                        description = "Mezo Experts Services",
                        invoice_number = Common.GetRandomInvoiceNumber(),
                        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,

                    };

                    // Create a payment using a valid APIContext

                    var createdPayment = payment.Create(apiContext);

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    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);
                }
               
                return null;
            }
            catch (Exception ex)
            {
              
                return View("FailureView");
            }
            // return  Json(new { result = createdPayment.links[0].href, redirect = createdPayment.links[1].href, execute = createdPayment.links[2].href });
       
            return null;
        }
Example #14
0
 /// <summary>
 /// Partially update the Payment resource for the given identifier
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <param name="patchRequest">PatchRequest</param>
 public void Update(APIContext apiContext, PatchRequest patchRequest)
 {
     Payment.Update(apiContext, this.id, patchRequest);
 }
Example #15
0
 /// <summary>
 /// Creates (and processes) a new Payment Resource.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <returns>Payment</returns>
 public Payment Create(APIContext apiContext)
 {
     return(Payment.Create(apiContext, this));
 }
Example #16
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));
 }
        private PayPal.Api.Payment CreatePayment(DexCMS.Tickets.Orders.Models.Order order)
        {
            var payer = new Payer { payment_method = "paypal" };
            List<Transaction> transactions = BuildTransactions(order);
            var baseUrl = WebConfigurationManager.AppSettings["ServerUrl"] + "secure/";
            var payment = new PayPal.Api.Payment
            {
                intent = "sale",
                payer = payer,
                transactions = transactions,
                redirect_urls = new RedirectUrls
                {
                    cancel_url = baseUrl + "cancel/" + order.OrderID,
                    return_url = baseUrl + "payment"
                }
            };

            return payment;
        }
        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/).
            }
        }
        public void Pay_Pass_With_PayPal_Account_When_Authorized()
        {
            var successfulPayment = new Payment { links = new List<Links> { new Links { rel = "approval_url", href = "http://paypal.com" } } };
            _payPalMocked.Setup(p => p.CreatePayPalPayment(It.IsAny<Order>(), It.IsAny<string>())).Returns(successfulPayment);

            _controller.ControllerContext.HttpContext.Request.Params["PayerID"] = null;

            var result = _controller.PayWithPayPal() as RedirectResult;
            Assert.IsInstanceOfType(result, typeof(RedirectResult));
            Assert.AreEqual("http://paypal.com", result.Url);
        }
        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/).
            }
        }
        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/).
            }
        }
 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);
 }
        private Payment CreatePayment(APIContext apiContext, string redirectURL)
        {
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            if (Session["cart"] != null)
            {
                List <Models.Home.Item> cart = (List <Models.Home.Item>)(Session["cart"]);

                foreach (var item in cart)
                {
                    itemList.items.Add(new Item()
                    {
                        name     = Convert.ToString(item.Product.ProductName),
                        currency = "USD",
                        price    = Convert.ToString(Convert.ToDecimal(item.Product.Price)),
                        // price = "1",
                        quantity = Convert.ToString(item.Quantity),
                        // quantity = "1",
                        sku = "sku"
                    }
                                       );
                    Console.WriteLine(Convert.ToString(item.Quantity));
                }

                var payer = new Payer()
                {
                    payment_method = "paypal"
                };

                var redirectURLs = new RedirectUrls()
                {
                    cancel_url = redirectURL + "&Cancel=true",
                    return_url = redirectURL
                };

                var details = new Details()
                {
                    tax      = "0.00",
                    shipping = "0.00",
                    subtotal = Convert.ToString(Convert.ToDecimal(Session["SessionTotal"]))
                               // subtotal = "1"
                };

                var amount = new Amount()
                {
                    currency = "USD",
                    total    = Convert.ToString(Convert.ToDecimal(Session["SessionTotal"])),
                    // total = "1",
                    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
                });

                this.payment = new Payment()
                {
                    intent        = "sale",
                    payer         = payer,
                    redirect_urls = redirectURLs,
                    transactions  = transactionList
                };
            }

            return(this.payment.Create(apiContext));
        }
Example #24
0
        public ActionResult PaymentWithCreditCard()
        {
            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object
            Item item = new Item();
            item.name = "Demo Item";
            item.currency = "EUR";
            item.price = "150";
            item.quantity = "1";
            item.sku = "sku";

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List<Item> itms = new List<Item>();
            itms.Add(item);
            ItemList itemList = new ItemList();
            itemList.items = itms;

            //Address for the payment
            Address billingAddress = new Address();
            billingAddress.city = "NewYork";
            billingAddress.country_code = "US";
            billingAddress.line1 = "23rd street kew gardens";
            billingAddress.postal_code = "43210";
            billingAddress.state = "NY";

            //Now Create an object of credit card and add above details to it
            //Please replace your credit card details over here which you got from paypal
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2 = "874";  //card cvv2 number
            crdtCard.expire_month = 1; //card expire date
            crdtCard.expire_year = 2020; //card expire year
            crdtCard.first_name = "Aman";
            crdtCard.last_name = "Thakur";
            crdtCard.number = "1234567890123456"; //enter your credit card number here
            crdtCard.type = "visa"; //credit card type here paypal allows 4 types

            // Specify details of your payment amount.
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = "150";
            details.tax = "27";

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount();
            amnt.currency = "EUR";
            // Total = shipping tax + subtotal.
            amnt.total = "177";
            amnt.details = details;

            // Now make a transaction object and assign the Amount object
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "Description about the payment amount.";
            tran.item_list = itemList;
            tran.invoice_number = "your invoice number which you are generating";

            // Now, we have to make a list of transaction and add the transactions object
            // to this list. You can create one or more object as per your requirements

            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);

            // Now we need to specify the FundingInstrument of the Payer
            // for credit card payments, set the CreditCard which we made above

            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();
            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactions;

            try
            {
                //getting context from the paypal
                //basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment
                //for which we have created the object above.

                //Basically, apiContext object has a accesstoken which is sent by the paypal
                //to authenticate the payment to facilitator account.
                //An access token could be an alphanumeric string

                APIContext apiContext = Configuration.GetAPIContext();

                //Create is a Payment class function which actually sends the payment details
                //to the paypal API for the payment. The function is passed with the ApiContext
                //which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.state is "approved" it means the payment was successful else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return View("FailureView");
                }
            }
            catch (PayPal.PayPalException ex)
            {
                //Logger.Log("Error: " + ex.Message);
                return View("FailureView");
            }

            return View("SuccessView");
        }
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            //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     = "Item Name",
                currency = "USD",
                price    = "5",
                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      = "1",
                shipping = "1",
                subtotal = "5"
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total    = "7", // 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 = "your invoice number",
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
        private TokenTransaction CreatePaypalTransactionEntity(TokenPackage package, Payment payment)
        {
            var transaction = new TokenTransaction();

            transaction.amount = package.token_amount;
            transaction.currency = package.currency;
            transaction.original_currency = ConstantValues.S_CURRENCY_SGD;
            transaction.original_price = package.price;
            transaction.token_package_id = package.id;
            transaction.paypal_payment_id = payment.id;

            return transaction;
        }
 public Payment Create(Payment payment)
 {
     return Payment.Create(context, payment);
 }
        public ActionResult Payment(Models.Payment model)
        {
           
            var apiContext = Configuration.GetAPIContext();
            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    // ###Items
                    // Items within a transaction.
                    var itemList = new PayPal.Api.ItemList()
                    {
                        items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "Mezo Experts",
                            currency = "USD",
                            price = model.Amount.ToString(),
                            quantity = "1",
                            sku = "sku"
                        }
                    }
                    };

                    // ###Payer
                    // A resource representing a Payer that funds a payment
                    // Payment Method
                    // as `paypal`
                    var payer = new PayPal.Api.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 + "/Students/AccountSettings?";
                    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 PayPal.Api.Details()
                    {
                        tax = "0",
                        shipping = "0",
                        subtotal = model.Amount.ToString()
                    };

                    // ###Amount
                    // Let's you specify a payment amount.
                    var amount = new PayPal.Api.Amount()
                    {
                        currency = "USD",
                        total = model.Amount.ToString(), // 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<PayPal.Api.Transaction>();

                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(new PayPal.Api.Transaction()
                    {
                        description = "Mezo Experts Services",
                        invoice_number = Common.GetRandomInvoiceNumber(),
                        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,

                    };

                    // Create a payment using a valid APIContext

                    var createdPayment = payment.Create(apiContext);

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    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);
                    PaypalPayments payments = new PaypalPayments();
                    payments.amount = model.Amount.ToString();
                    payments.ID = Guid.NewGuid();
                    payments.status = Status.Offered;
                    payments.paymentId = createdPayment.id;
                    payments.token = createdPayment.token;
                    payments.guid = guid;
                    payments.UserId = new Guid(User.Identity.GetUserId());
                    db.payments.Add(payments);
                    db.SaveChanges();
                   
                    return Redirect(paypalRedirectUrl);
                }

                return null;
            }
            catch (Exception ex)
            {

                return View("FailureView");
            }
            // return  Json(new { result = createdPayment.links[0].href, redirect = createdPayment.links[1].href, execute = createdPayment.links[2].href });

            return null;
        }
Example #29
0
        /// <summary>
        /// ตัดบัตรเครดิต
        /// </summary>
        /// <param name="payment">ข้อมูลบัตรเครดิตที่ต้องการดำเนินการ</param>
        public PaymentResult ChargeCreditCard(PaymentInformation paymentInfo)
        {
            var tokenCredential = new OAuthTokenCredential(_appConfig.PaypalClientId, _appConfig.PaypalClientSecret, new Dictionary <string, string>());
            var accessToken     = tokenCredential.GetAccessToken();
            var config          = new Dictionary <string, string>();

            config.Add("mode", "sandbox"); // HACK: Paypal mode ('live' or 'sandbox')
            var apiContext = new APIContext
            {
                Config      = config,
                AccessToken = accessToken
            };

            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total    = paymentInfo.TotalPrice.ToString(),
                    details  = new Details()
                    {
                        shipping = "0",
                        subtotal = paymentInfo.TotalPrice.ToString(),
                        tax      = "0"
                    }
                },
                description = $"User { paymentInfo.UserProfileId } pay { paymentInfo.TotalPrice.ToString("C2") } for course { paymentInfo.PurchaseForCourseId }",
            };

            // A resource representing a Payer that funds a payment.
            var payer = new Payer()
            {
                payment_method      = "credit_card",
                funding_instruments = new List <FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card = new CreditCard()
                        {
                            billing_address = new Address()
                            {
                                city         = paymentInfo.City,
                                country_code = paymentInfo.Country,
                                line1        = paymentInfo.Address,
                                postal_code  = paymentInfo.PostalCode,
                                state        = paymentInfo.State
                            },
                            cvv2         = paymentInfo.CVV,
                            expire_month = paymentInfo.ExpiredMonth,
                            expire_year  = paymentInfo.ExpiredYear,
                            first_name   = paymentInfo.FirstName,
                            last_name    = paymentInfo.LastName,
                            number       = paymentInfo.CreditCardNumber,
                            type         = paymentInfo.CardType.ToLower()
                        }
                    }
                },
                payer_info = new PayerInfo {
                    email = paymentInfo.UserProfileId
                }
            };

            // 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 = new List <Transaction>()
                {
                    transaction
                }
            };

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

            return(Enum.TryParse <PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow);
        }
Example #30
0
        /// <summary>
        /// Creates (and processes) a new Payment Resource.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="payment">Payment object to be used in creating the PayPal resource.</param>
        /// <returns>Payment</returns>
        public static Payment Create(APIContext apiContext, Payment payment)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);

            // Configure and send the request
            var resourcePath = "v1/payments/payment";
            var resource = PayPalResource.ConfigureAndExecute<Payment>(apiContext, HttpMethod.POST, resourcePath, payment.ConvertToJson());
            resource.token = resource.GetTokenFromApprovalUrl();
            return resource;
        }
Example #31
0
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            //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 = "Item Name",
                currency = "EUR",
                price = "150",
                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 = "27",
                shipping = "1",
                subtotal = "150"
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "EUR",
                total = "178", // 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 = "your invoice number",
                amount = amount,
                item_list = itemList
            });

            this.payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return this.payment.Create(apiContext);
        }
        public void Pay_Pass_With_PayPal_Account_When_Not_Authorized()
        {
            var failedPayment = new Payment { links = new List<Links>() };
            _payPalMocked.Setup(p => p.CreatePayPalPayment(It.IsAny<Order>(), It.IsAny<string>())).Returns(failedPayment);

            _controller.ControllerContext.HttpContext.Request.Params["PayerID"] = null;

            var result = _controller.PayWithPayPal() as ViewResult;
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            Assert.AreEqual("PaymentFailure", result.ViewName);
        }
        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();

            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it. 
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total = "7",
                    details = new Details()
                    {
                        shipping = "1",
                        subtotal = "5",
                        tax = "1"
                    }
                },
                description = "This is the payment transaction description.",
                item_list = new ItemList()
                {
                    items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "Item Name",
                            currency = "USD",
                            price = "1",
                            quantity = "5",
                            sku = "sku"
                        }
                    },
                    shipping_address = new ShippingAddress
                    {
                        city = "Johnstown",
                        country_code = "US",
                        line1 = "52 N Main ST",
                        postal_code = "43210",
                        state = "OH",
                        recipient_name = "Joe Buyer"
                    }
                },
                invoice_number = Common.GetRandomInvoiceNumber()
            };

            // A resource representing a Payer that funds a payment.
            var payer = new Payer()
            {
                payment_method = "credit_card",
                funding_instruments = new List<FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card = new CreditCard()
                        {
                            billing_address = new Address()
                            {
                                city = "Johnstown",
                                country_code = "US",
                                line1 = "52 N Main ST",
                                postal_code = "43210",
                                state = "OH"
                            },
                            cvv2 = "874",
                            expire_month = 11,
                            expire_year = 2018,
                            first_name = "Joe",
                            last_name = "Shopper",
                            number = "4877274905927862",
                            type = "visa"
                        }
                    }
                },
                payer_info = new PayerInfo
                {
                    email = "*****@*****.**"
                }
            };

            // A Payment resource; create one using the above types and intent as `sale` or `authorize`
            var payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = new List<Transaction>() { transaction }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Create credit card 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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #34
0
        public Payment CreatePayment(GroveCM.Models.Order order, string cancelUrl, string returnUrl)
        {
            var amount = CreateAmount(order);

            var itemList = new ItemList() { items = new List<Item>() };
            itemList.items.Add(new Item()
            {
                name = order.ItemName,
                currency = order.Currency,
                price = order.SubTotal.ToString(),
                quantity = order.Quantity.ToString(),
                sku = order.SKU
            });

            var payment = new Payment
            {
                transactions = new List<Transaction>
                                             {
                                                new Transaction
                                                {
                                                    amount = amount,
                                                    description = "Purchase From Widget Store",
                                                    item_list = itemList
                                                }
                                             },
                intent = "sale",
                payer = new Payer { payment_method = "paypal" },
                redirect_urls = new RedirectUrls
                {
                    cancel_url = cancelUrl,
                    return_url = returnUrl
                }
            };

            payment = payment.Create(Api);

            return payment;
        }
        public ActionResult PaymentWithPaypal(Cart cart)
        {
            ShippingDetails shippingDetails = (ShippingDetails)TempData["shipping_details"];

            //getting the apiContext as earlier
            APIContext apiContext = PaypalConfiguration.GetAPIContext();

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

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist
                    //it is returned by the create function call of the payment class

                    // Creating a payment
                    // baseURL is the url on which paypal sendsback the data.
                    // So we have provided URL of this controller only
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
                                "/Paypal/PaymentWithPayPal?";

                    //guid we are generating for storing the paymentID received in session
                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    var payer = new Payer() { payment_method = "paypal" };

                    var redirUrls = new RedirectUrls()
                    {
                        cancel_url = baseURI + "guid=" + guid,
                        return_url = baseURI + "guid=" + guid
                    };

                    List<Transaction> transactions = GenerateteTransactions(cart);

                    //CreatePayment function gives us the payment approval url
                    //on which payer is redirected for paypal account payment
                    payment = new Payment()
                    {
                        intent = "sale",
                        payer = payer,
                        transactions = transactions,
                        redirect_urls = redirUrls
                    };

                    var createdPayment = payment.Create(apiContext);
                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    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
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

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

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return View("Failure");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return View("Failure");
            }

            orderProcessor.ProcessOrder(cart, shippingDetails);
            cart.Clear();

            return View("Success");
        }
Example #36
0
        protected void Run()
        {
            var apiContext = Configuration.GetAPIContext();

            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            {
                var itemList = new ItemList()
                {
                    items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "Item Name",
                            currency = "USD",
                            price = "15",
                            quantity = "5",
                            sku = "sku"
                        }
                    }
                };

                var payer = new Payer() { payment_method = "paypal" };

                // Redirect URLS
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Default.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
                };

                var details = new Details()
                {
                    tax = "15",
                    shipping = "10",
                    subtotal = "75"
                };

                var amount = new Amount()
                {
                    currency = "USD",
                    total = "100.00",
                    details = details
                };

                var transactionList = new List<Transaction>();
                transactionList.Add(new Transaction()
                {
                    description = "Transaction description.",
                    invoice_number = Common.GetRandomInvoiceNumber(),
                    amount = amount,
                    item_list = itemList
                });

                var payment = new Payment()
                {
                    intent = "sale",
                    payer = payer,
                    transactions = transactionList,
                    redirect_urls = redirUrls
                };

                #region Track Workflow
                this.Flow.AddNewRequest("Create PayPal payment", payment);
                #endregion

                var createdPayment = payment.Create(apiContext);

                #region Track Workflow
                this.Flow.RecordResponse(createdPayment);
                #endregion

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