Set of redirect URLs you provide only for PayPal-based payments.

See PayPal Developer documentation for more information.

Inheritance: PayPalSerializableObject
Ejemplo n.º 1
8
        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");
        }
Ejemplo n.º 2
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/).
            }
        }
Ejemplo n.º 3
0
 public static RedirectUrls GetRedirectUrls()
 {
     RedirectUrls urls = new RedirectUrls();
     urls.cancel_url = "http://ebay.com/";
     urls.return_url = "http://paypal.com/";
     return urls;
 }
Ejemplo n.º 4
0
        private Payment CreatePaymentInternal(APIContext apiContext, string redirectUrl, double amountValue)
        {
            var amountStringValue = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", amountValue);
            var invoiceNumber = Convert.ToString((new Random()).Next(100000));
            //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 = "Socialforce credit amount",
                currency = "USD",
                price = amountStringValue,
                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
            //{
            //    subtotal = amountValue.ToString(CultureInfo.InvariantCulture)
            //};

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount
            {
                currency = "USD",
                total = amountStringValue, // Total must be equal to sum of shipping, tax and subtotal.
                //details = details
            };

            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction
            {
                description = "Gigbucket credit amount",
                invoice_number = invoiceNumber,
                amount = amount,
                item_list = itemList
            });

            var payment = new Payment
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            return payment.Create(apiContext);
        }
Ejemplo n.º 5
0
        public Payment CreatePayment(APIContext apiContext, List<Transaction> paypalTransactions, RedirectUrls redirectUrls)
        {

            var payment = Payment.Create(apiContext, new Payment()
            {
                intent = "sale",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = paypalTransactions,
                redirect_urls = redirectUrls
            });
            return payment;
        }
Ejemplo n.º 6
0
        //het aanmaken van een payment voor paypal van een walletorder: de te betalen payment volgens paypal vereisten.
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, WalletOrder order)
        {
            //eff tijdelijk test ding
            var itemList = new ItemList() { items = new List<Item>() };

            itemList.items.Add(new Item()
            {
                name = "Oplading van Wallet",
                currency = "EUR",
                price = order.TotalAmount.ToString(),
                quantity = "1",
                sku = order.OrderId.ToString()


            });

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

            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            var details = new Details()
            {
                tax = "0",
                shipping = "0",
                subtotal = order.TotalAmount.ToString()
            };

            var amount = new Amount()
            {
                currency = "EUR",
                total = order.TotalAmount.ToString(),
                details = details
            };

            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction()
            {
                description = "Betaling van een oplading",
                invoice_number = order.OrderId.ToString(),
                amount = amount,
                item_list = itemList
            });

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

            return this.payment.Create(apiContext);
        }
Ejemplo n.º 7
0
        public bool CreatePayment(string priceStr, string description)
        {
            try
            {
                // Authenticate with PayPal
                var config = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                apiContext = new APIContext(accessToken);

                var itemList = new ItemList()
                {
                    items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "PrintAhead print",
                            currency = "USD",
                            price = priceStr,
                            quantity = "1",
                            sku = "sku"
                        }
                    }
                };

                var payer = new Payer() { payment_method = "paypal" };
                var redirUrls = new RedirectUrls()
                {
                    cancel_url = "http://www.abalonellc.com/hairshop-10-coming-so10.html",
                    return_url = "http://www.abalonellc.com/"
                };

                var details = new Details()
                {
                    tax = "0",
                    shipping = "0",
                    subtotal = priceStr
                };

                var amount = new Amount()
                {
                    currency = "USD",
                    total = priceStr, // Total must be equal to sum of shipping, tax and subtotal.
                    details = details
                };

                var transactionList = new List<Transaction>
                {
                    new Transaction()
                    {
                        description = description, // transaction description
                        invoice_number = GetRandomInvoiceNumber(),
                        amount = amount,
                        item_list = itemList
                    }
                };

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

                createdPayment = payment.Create(apiContext);
                var links = createdPayment.links.GetEnumerator();
                var hasGoodLink = false;
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link != null && link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        chromeBrowser.Load(link.href);
                        hasGoodLink = true;
                        break;
                    }
                }

                if (!hasGoodLink)
                    return false;
            }
            catch (PaymentsException ex)
            {
                // Get the details of this exception with ex.Details.  If you have logging setup for your project, this information will also be automatically logged to your logfile.
                var sb = new StringBuilder();
                sb.AppendLine("Error:    " + ex.Details.name);
                sb.AppendLine("Message:  " + ex.Details.message);
                sb.AppendLine("URI:      " + ex.Details.information_link);
                sb.AppendLine("Debug ID: " + ex.Details.debug_id);
                MessageBox.Show(sb.ToString());
                return false;
            }
            return true;
        }
Ejemplo n.º 8
0
        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;
        }
Ejemplo n.º 9
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);
            };
        }
Ejemplo n.º 10
0
        private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl)
        {
            Payer payer = new Payer()
            {
                payment_method = "paypal"
            };

            var amount = new Amount()
            {
                currency = "USD",
                total = "100",
                details = new Details()
                {
                    tax = "15",
                    shipping = "10",
                    subtotal = "75"
                }
            };

            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            var itemList = new ItemList() { items = new List<Item>() };
            itemList.items.Add(new Item()
            {
                name = "Item Name",
                currency = "USD",
                price = "15",
                quantity = "5",
                sku = "sku"
            });

            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount = amount,
                item_list = itemList
            });

            var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters();
            authorizationCodeParameters.setClientId(Configuration.ClientId);
            authorizationCodeParameters.setClientSecret(Configuration.ClientSecret);
            authorizationCodeParameters.SetCode(authorizationCode);

            var apiContext = Configuration.GetAPIContext();

            var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters);
            var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token);

            var futurePaymentApiContext = Configuration.GetAPIContext(accessToken);

            var futurePayment = new FuturePayment()
            {
                intent = "authorize",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            return futurePayment.Create(futurePaymentApiContext, correlationId);
        }
Ejemplo n.º 11
0
        // #Create Future Payment Using PayPal
        // This sample code demonstrates how you can process a future payment made using a PayPal account.
        /// <summary>
        /// Code example for creating a future payment object.
        /// </summary>
        /// <param name="correlationId"></param>
        /// <param name="authorizationCode"></param>
        private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl)
        {
            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            Payer payer = new Payer()
            {
                payment_method = "paypal"
            };

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

            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Items
            // Items within a transaction.
            var itemList = new ItemList() { items = new List<Item>() };
            itemList.items.Add(new Item()
            {
                name = "Item Name",
                currency = "USD",
                price = "15",
                quantity = "5",
                sku = "sku"
            });

            // ###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,
                item_list = itemList
            });

            var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters();
		    authorizationCodeParameters.setClientId(Configuration.ClientId);
		    authorizationCodeParameters.setClientSecret(Configuration.ClientSecret);
		    authorizationCodeParameters.SetCode(authorizationCode);

            // ### 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();


            var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters);
            var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token);

            var futurePaymentApiContext = Configuration.GetAPIContext(accessToken);

            // ###Payment
            // A FuturePayment Resource
            var futurePayment = new FuturePayment()
            {
                intent = "authorize",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            return futurePayment.Create(futurePaymentApiContext, correlationId);
        }
        private Payment CreatePayment(IOrder order, string paymentType, string redirectUrl, CardDetails cardDetails)
        {
            //Create items for which you are taking payment
            var items = order.OrderDetails.GetList().Select(product => new Item
            {
                name = product.Name,
                currency = "GBP",
                price = product.Price.ToString(CultureInfo.InvariantCulture),
                quantity = product.Quantity.ToString(CultureInfo.InvariantCulture),
                sku = product.Category
            }).ToList();
            // Create ItemList object
            var itemList = new ItemList { items = items };

            // Specify the details of your payment amount.
            var subtotal = order.GetProductCost() - order.GetVat();
            var details = new Details
            {
                shipping = order.DeliveryCharges.ToString(CultureInfo.InvariantCulture),
                subtotal = subtotal.ToString(CultureInfo.InvariantCulture),
                tax = order.GetVat().ToString(CultureInfo.InvariantCulture)
            };

            // Specify your total payment amount and assign the details object
            var totalCost = order.GetProductCost() + order.DeliveryCharges;
            var amount = new Amount
            {
                currency = "GBP",
                total = totalCost.ToString(CultureInfo.InvariantCulture),
                //details = details
            };

            // Now add transactions
            var transactions = new List<Transaction>
            {
                new Transaction
                {
                    amount = amount,
                    description = string.Format("Total amount = £{0}", order.GetProductCost() + order.DeliveryCharges),
                    //item_list = itemList,
                    //invoice_number = order.OrderNumber.ToString(CultureInfo.InvariantCulture)
                }
            };

            Payer payer;
            if (paymentType.Equals("payPal", StringComparison.OrdinalIgnoreCase))
            {
                payer = new Payer { payment_method = "paypal" };
            }
            else
            {
                //Address for the payment
                var billingAddress = new Address
                {
                    country_code = "GB",
                    line1 = cardDetails.Address,
                    postal_code = cardDetails.Postcode,
                    city = cardDetails.City
                };

                //Now Create an object of credit card and add above details to it
                var creditCard = new CreditCard
                {
                    billing_address = billingAddress,
                    cvv2 = cardDetails.CardVerificationCode.GetValueOrDefault().ToString(CultureInfo.InvariantCulture),
                    expire_month = cardDetails.ExpirationMonth.GetValueOrDefault(),
                    expire_year = cardDetails.ExpirationYear.GetValueOrDefault(),
                    first_name = cardDetails.FirstName,
                    last_name = cardDetails.LastName,
                    number = cardDetails.CardNumber.GetValueOrDefault().ToString(CultureInfo.InvariantCulture),
                    type = cardDetails.CardType.ToLower()

                };

                // Now we need to create the FundingInstrument object of the Payer
                // for credit card payments, set the CreditCard which we made above
                var fundInstrument = new FundingInstrument { credit_card = creditCard };

                // The Payment creation API requires a list of FundingIntrument
                var fundingInstrumentList = new List<FundingInstrument> { fundInstrument };

                // Now create Payer object and assign the fundinginstrument list to the object
                payer = new Payer
                {
                    funding_instruments = fundingInstrumentList,
                    payment_method = "credit_card"
                };
            }

            // Finally we need create the payment object and assign the payer object & transaction list to it
            var payment = new Payment
            {
                intent = "sale",
                payer = payer,
                transactions = transactions
            };

            if (!string.IsNullOrEmpty(redirectUrl))
            {
                var redirUrls = new RedirectUrls
                {
                    cancel_url = redirectUrl,
                    return_url = redirectUrl
                };
                payment.redirect_urls = redirUrls;
            }

            return payment;
        }
Ejemplo n.º 13
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);
        }
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, int orderId)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList() { items = new List<Item>() };
            foreach (FunOrderDetail od in dbmeals.FunOrderDetails.Where(x => x.OrderID == orderId))
            {
                itemList.items.Add(new Item()
                {
                    name = od.Description,
                    currency = "USD",
                    price = String.Format("{0:0}", od.Price),//.ToString(),
                    quantity = (od.Quantity).ToString(),
                    sku = od.ID.ToString()
                });
            }

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

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax = "0",
                shipping = "0",
                subtotal = String.Format("{0:0}", dbmeals.FunOrderDetails.Where(x => x.OrderID == orderId).Sum(x => (x.Price * x.Quantity)))
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total = details.subtotal, // 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 = orderId.ToString(),
                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);
        }
Ejemplo n.º 15
0
        private Payment CreatePayment(APIContext apiContext, string returnUrl, string cancelUrl, Models.Transaction t)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList() { items = new List<PayPal.Api.Item>() };
            decimal tax = 0, shipping = 0;
            decimal t_subtotes = 0;
            List<CartItemViewModel> l_civm = (List<CartItemViewModel>)Session["Cart"];

            /*
                Insert Transaction To Database; Set Status to 1 (NotPaid)
                Make sure to create TransactionItems
            */

            foreach (CartItemViewModel civm in l_civm)
            {
                TransactionItem ti = new TransactionItem();
                ti.transaction_id = t.id;
                ti.item_name = civm.name;
                ti.item_price = civm.price;
                ti.quantity = civm.quantity;
                db.TransactionItems.Add(ti);
                itemList.items.Add(new PayPal.Api.Item()
                {
                    name = civm.name,
                    currency = "USD",
                    price = Math.Round(civm.price, 2).ToString(),
                    quantity = civm.quantity.ToString(),
                    sku = civm.id.ToString()
                });

                t_subtotes += civm.price * civm.quantity;
                // similar as we did for credit card, do here and create details object
            }
            var totes = tax + shipping + t_subtotes;

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

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = cancelUrl,
                return_url = returnUrl
            };

            var details = new Details()
            {
                tax = Math.Round(tax, 2).ToString(),
                shipping = Math.Round(shipping, 2).ToString(),
                subtotal = Math.Round(t_subtotes, 2).ToString()
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total = Math.Round(totes, 2).ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            var transactionList = new List<PayPal.Api.Transaction>();

            transactionList.Add(new PayPal.Api.Transaction()
            {
                description = "Transaction description.",
                invoice_number = Session["User"].ToString() + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                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);
        }
Ejemplo n.º 16
0
        public PayPal.Api.Payment GetPayment (Booking booking  )
        {

            // var panier = await GetActivePanier(true);

            //var titres = panier.PanierAlbums.SelectMany(x => x.Titres).Select(x => new Item { name = x.Nom, currency = "EUR", price = x.Prix.ToString(), quantity = "1" });

            //var total = panier.PanierAlbums.Sum(x => x.Total);

            var item = new Item()
            {
                name = string.Format("Reserva de Cancha {0} " , booking.Field.Name),
                currency ="USD",
                quantity ="1",
                price = booking.Price.ToString(),
            };
            //configuracion de paypal
            APIContext api = getPaypalContext();

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

            ItemList itemList = new ItemList();
            itemList.items = items;



            Amount amnt = new Amount();
            amnt.currency = "USD";
            amnt.total = booking.Price.ToString();

            List<Transaction> transactionList = new List<Transaction>();
            Transaction tran = new Transaction();
            //tran.description = "creating a payment";
            tran.amount = amnt;
            tran.item_list = itemList;

            transactionList.Add(tran);

            Payer payr = new Payer();
            payr.payment_method = "paypal";

            RedirectUrls redirUrls = new RedirectUrls();
            redirUrls.cancel_url = cancel_url;
            redirUrls.return_url = return_url;

            PayPal.Api.Payment pymnt = new PayPal.Api.Payment();
            pymnt.intent = "sale";
            pymnt.payer = payr;
            pymnt.transactions = transactionList;
            pymnt.redirect_urls = redirUrls;

            var payment = pymnt.Create(api);
            if (pymnt != null)
            {

                //panier.paymentId = payment.id;
                //await SaveAsync();
            }

            return payment;
        }
Ejemplo n.º 17
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>() };
            SqlConnection sqlConnection1;
            DataSet resultSet;
            gettheTableData(out sqlConnection1, out resultSet);
            sqlConnection1.Close();
            var FaceID = resultSet.Tables[0].Rows[0].ItemArray.ToArray()[13].ToString();
            var itemPaid = db.userPaids.First(u => u.FBID == FaceID);
            itemList.items.Add(new Item()
            {
                name = itemPaid.party.name.ToString(),
                currency = "USD",
                price = itemPaid.ammount.ToString(),
                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
            };
            var tax = itemPaid.ammount * .1m;

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax = tax.ToString("0.00###"),
                shipping = "1.00",
                subtotal = (itemPaid.ammount).ToString()
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total = (itemPaid.ammount +1 + tax).ToString("0.00###"), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction()
            {
                description = "hackargin.",
                invoice_number = "your invoice gfdgnumber",
                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);
        }
Ejemplo n.º 18
0
        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;
        }
Ejemplo n.º 19
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))
            {
                // ###Items
                // Items within a transaction.
                var itemList = new ItemList() 
                {
                    items = new List<Item>() 
                    {
                        new Item()
                        {
                            name = "Item Name",
                            currency = "USD",
                            price = "15",
                            quantity = "5",
                            sku = "sku"
                        }
                    }
                };

                // ###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 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 = "15",
                    shipping = "10",
                    subtotal = "75"
                };

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

        }
Ejemplo n.º 20
0
        //****************
        //TO DO - remove common functions to separate class
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, double pytAmount, string guid)
        {
            var itemList = new ItemList() { items = new List<Item>() };

            itemList.items.Add(new Item()
            {
                name = "Item Name",
                currency = "GBP",
                price = pytAmount.ToString(),
                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
            };

            var details = new Details()
            {
                tax = "0",
                shipping = "0",
                subtotal = pytAmount.ToString()
            };

            var amount = new Amount()
            {
                currency = "GBP",
                total = pytAmount.ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);
            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                invoice_number = guid, // "your invoice number: " + timestamp,
                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 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");
        }
Ejemplo n.º 22
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)
                };
            }
        }