Additional details of the payment amount.

See PayPal Developer documentation for more information.

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

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

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

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

                if (string.IsNullOrEmpty(payerId))
                {

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

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

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

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

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

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

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

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

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

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

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

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    var guid = Request.Params["guid"];
                    var paymentId = Session[guid] as string;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var pymnt = new Payment() { id = paymentId };
                    var executedPayment = pymnt.Execute(apiContext, paymentExecution);
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return View("DonationFailureView");
            }
            return View("DonationSuccessView");
        }
        private static Transaction GetCardTransactionDetails(ItemList itemList, double amount)
        {
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = amount.ToString();
            details.tax = "0";

            Amount amnt = new Amount();
            amnt.currency = "GBP";
            // Total = shipping tax + subtotal.
            amnt.total = amount.ToString();
            amnt.details = details;

            string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

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

            Guid uniqueGuid = Guid.NewGuid();

            // Now make a trasaction object and assign the Amount object
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "Money due";
            tran.item_list = itemList;
            tran.invoice_number = "PAYPAL-" + guid.ToString(); // uniqueGuid.ToString().ToUpper(); // "Invoice # " + timestamp;

            return tran;
        }
Exemple #3
0
        public static Details CreatePayPalDetails(double amount)
        {
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = amount.ToString();
            details.tax = "0";

            return details;
        }
Exemple #4
0
 public static Amount CreatePayPalAmount(double pytAmount, Details details)
 {
     Amount amount = new Amount()
     {
         currency = "GBP",
         total = pytAmount.ToString(), // Total must be equal to sum of shipping, tax and subtotal.
         details = details
     };
     return amount;
 }
        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);
        }
        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;
        }
        private List<Transaction> BuildTransactions(DexCMS.Tickets.Orders.Models.Order order)
        {
            var details = new Details { shipping = "0.00", tax = "0.00", subtotal = order.OrderTotal.ToString() };
            var amount = new Amount { currency = "USD", details = details, total = order.OrderTotal.ToString() };
            var itemList = new ItemList() { items = new List<Item>() };

            foreach (var ticket in order.Tickets)
            {
                itemList.items.Add(new Item
                {
                    name = GetTicketName(ticket),
                    currency = "USD",
                    price = ticket.TicketTotalPrice.ToString(),
                    quantity = "1",
                    sku = ticket.TicketID.ToString()
                });
            }

            var transaction = new Transaction
            {
                amount = amount,
                description = string.Format("Order #{0} purchased from {1}", order.OrderID, SiteSettings.Resolve.GetSetting("SiteTitle")),
                item_list = itemList,
                invoice_number = order.OrderID.ToString()
            };



            var transactions = new List<Transaction>
            {
                transaction
            };
            return transactions;
        }
Exemple #8
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)
                };
            }
        }
Exemple #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);
            };
        }
        /// <summary>
        /// Create and return new Payment
        /// </summary>
        /// <param name="cart">user Cart</param>
        /// <param name="baseUrl">base uri of Requst</param>
        /// <returns>created Payment</returns>
        public string GetPayment(Cart cart, string baseUrl)
        {
            if (cart == null)
            {
                throw new ArgumentNullException(Resources.NullOrEmptyValue, nameof(cart));
            }

            if (cart.ContentCartDtoCollection == null || (cart.ContentCartDtoCollection.Count() <= 0))
            {
                throw new EmptyCartException(Resources.CountContentInCartIsNull);
            }

            if (cart.PriceAllItemsCollection != cart.ContentCartDtoCollection.Sum <ContentCartDto>(x => x.PriceItem) || cart.PriceAllItemsCollection <= 0)
            {
                throw new ContentCartPriceException(Resources.InvaliContentCartValueOfPrice);
            }

            var config = Configuration.GetConfig();

            var accessToken = new OAuthTokenCredential(config).GetAccessToken();

            var apiContext = new APIContext(accessToken);

            string payerId = "payerId"; // Request.Params["PayerID"];

            // ###Items
            // Items within a transaction.
            var itemList = new PayPal.Api.ItemList();

            itemList.items = this.GetItemList(cart.ContentCartDtoCollection);

            // ###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 redirUrls = this.GetRedirectUrls(baseUrl);

            // ###Details
            // Let's you specify details of a payment amount.
            var tax = this.GetTax(cart.PriceAllItemsCollection);

            var details = new PayPal.Api.Details()
            {
                tax      = decimal.Round(tax, 2).ToString(CultureInfo.CreateSpecificCulture("en-US")),
                shipping = "0",
                subtotal = decimal.Round(cart.PriceAllItemsCollection, 2).ToString(CultureInfo.CreateSpecificCulture("en-US"))
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new PayPal.Api.Amount()
            {
                currency = "USD",
                total    = decimal.Round(cart.PriceAllItemsCollection + tax, 2).ToString(CultureInfo.CreateSpecificCulture("en-US")),

                // 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    = "Payd contents.",
                invoice_number = new System.Random().Next(999999).ToString(), // Get id number transaction
                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);

            // return Redirect(createdPayment.GetApprovalUrl(true));
            return(createdPayment.GetApprovalUrl(true));
        }
Exemple #11
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 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);
        }
        //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);
        }
Exemple #14
0
        public ActionResult PaymentWithCreditCard(Bids bid)
        {
            ApplicationUser currentUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());

            #region Item Info
            Item item = new Item();
            item.name = bid.bidStake.ToString() + "% stake in " + bid.ventureID;
            item.currency = "USD";
            item.price = bid.bid.ToString();
            item.quantity = "1";
            item.sku = bid.ventureID.ToString();
            List<Item> itms = new List<Item>();
            itms.Add(item);
            ItemList itemList = new ItemList();
            itemList.items = itms;
            #endregion

            #region Billing Info 
            Address billingAddress = new Address();
            //billingAddress.city = currentUser.City;
            //billingAddress.country_code = currentUser.CountryCode;
            //billingAddress.line1 = currentUser.AddressLine1;
            //billingAddress.postal_code = currentUser.ZipCode;
            //billingAddress.state = currentUser.State;
            #endregion

            #region Credit Card
            CreditCard crdtCard = new CreditCard();
            crdtCard.billing_address = billingAddress;
            //crdtCard.cvv2 = currentUser.CCV2;
            //crdtCard.expire_month = currentUser.CCExpireMonth;
            //crdtCard.expire_year = currentUser.CCExpireYear;
            //crdtCard.first_name = currentUser.FirstName;
            //crdtCard.last_name = currentUser.LastName;
            //crdtCard.number = currentUser.CCNumber;
            //crdtCard.type = currentUser.CCType; //paypal allows 4 types
            #endregion

            #region Transaction Details
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = bid.bid.ToString();
            details.tax = "0";

            Amount amnt = new Amount();
            amnt.currency = "USD";
            amnt.total = details.subtotal;
            amnt.details = details;

            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = bid.createdOn.ToString();
            tran.item_list = itemList;
            tran.invoice_number = bid.Id.ToString();
            #endregion

            #region Payment
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(tran);
            FundingInstrument fundInstrument = new FundingInstrument();
            fundInstrument.credit_card = crdtCard;
            List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
            fundingInstrumentList.Add(fundInstrument);

            Payer payer = new Payer();
            payer.funding_instruments = fundingInstrumentList;
            payer.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 = payer;
            payment.transactions = transactions;

            try
            {
                APIContext apiContext = Configuration.GetAPIContext();
                Payment createdPayment = payment.Create(apiContext);

                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>() };
            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);
        }
        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;
        }
        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;
        }
        //****************
        //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 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;
        }
        public ActionResult PaymentWithCreditCard(Donor d, string CreditCardNumber, string CreditCardType, string CreditCardExpMonth, string CreditCardExpYear)
        {
            //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 = "Item Name";
            item.currency = "USD";
            item.price = d.Amount.ToString();
            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
            PayPal.Api.Address billingAddress = new PayPal.Api.Address();
            billingAddress.city = d.City;
            billingAddress.country_code = "US";
            billingAddress.line1 = d.Address1;
            billingAddress.postal_code = d.ZipCode;
            billingAddress.state = d.State;

            //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; 
            crdtCard.expire_month = Convert.ToInt32(CreditCardExpMonth);
            //crdtCard.expire_year = 2021; //card expire year
            crdtCard.expire_year = Convert.ToInt32(CreditCardExpYear);
            //crdtCard.first_name = "test";
            crdtCard.first_name = d.FirstName;
            //crdtCard.last_name = "buyer";
            crdtCard.last_name = d.LastName;
            //crdtCard.number = "4032033901230495"; 
            crdtCard.number = CreditCardNumber;
            //crdtCard.type = "visa"; 
            crdtCard.type = CreditCardType;

            // Specify details of your payment amount.
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = d.Amount.ToString();
            details.tax = "0";

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

            // Now make a transaction object and assign the Amount object
            Transaction tran = new Transaction();
            tran.amount = amnt;
            tran.description = "Donation";
            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

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

                //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("DonationFailureView");
                }
            }
            catch (PayPal.PayPalException e)
            {
                string error = e.ToString();
                return View("DonationFailureView");
            }
            return View("DonationSuccessView");
        }
Exemple #21
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);
        }
        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/).
            }

        }
        private List<Transaction> GenerateteTransactions(Cart cart)
        {
            var itemList = new ItemList() { items = new List<Item>() };

            foreach(CartLine cartLine in cart.Lines)
            {
                itemList.items.Add(new Item()
                {
                    name = cartLine.Product.Name,
                    currency = "USD",
                    price = cartLine.Product.Price.ToString(),
                    quantity = cartLine.Quantity.ToString(),
                    //sku = "sku"
                });
            }

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

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax = "0",
                shipping = "0",
                subtotal = "0"
            };

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

            return transactionList;
        }
Exemple #24
0
        private Amount CreateAmount(GroveCM.Models.Order order)
        {
            var details = new Details
            {
                subtotal = order.SubTotal.ToString("0.00", CultureInfo.CurrentCulture),
                shipping = order.Shipping.ToString("0.00", CultureInfo.CurrentCulture),
                tax = order.Tax.ToString("0.00", CultureInfo.CurrentCulture),
                //fee = order.Fees.ToString("0.00", CultureInfo.CurrentCulture)
            };

            var total = order.SubTotal + order.Shipping + order.Tax; //+ order.Fees;

            var amount = new Amount
            {
                currency = "GBP",
                details = details,
                total = total.ToString("0.00", CultureInfo.CurrentCulture)
            };

            return amount;
        }