Create() public method

Creates and processes a payment. In the JSON request body, include a `payment` object with the intent, payer, and transactions. For PayPal payments, include redirect URLs in the `payment` object.
public Create ( APIContext apiContext ) : Payment
apiContext APIContext APIContext used for the API call.
return Payment
        public ActionResult CreatePurchase(PurchaseInfo purchaseInfo)
        {
            try
            {
                string action = "Index";

                var payer = new Payer
                {
                    payment_method = "credit_card",
                    funding_instruments = new List<FundingInstrument>(),
                    payer_info = new PayerInfo
                    {
                        email = "*****@*****.**"
                    }
                };

                var creditCard = new CreditCard();

                if (!string.IsNullOrEmpty(purchaseInfo.CreditCardId))
                {
                    payer.funding_instruments.Add(new FundingInstrument()
                    {
                        credit_card_token = new CreditCardToken()
                        {
                            credit_card_id = purchaseInfo.CreditCardId
                        }
                    });
                }
                else
                {
                    creditCard = new CreditCard()
                    {
                        billing_address = new Address()
                        {
                            city = "Orlando",
                            country_code = "US",
                            line1 = "123 Test Way",
                            postal_code = "32803",
                            state = "FL"
                        },
                        cvv2 = purchaseInfo.CVV2,
                        expire_month = purchaseInfo.ExpMonth,
                        expire_year = purchaseInfo.ExpYear,
                        first_name = purchaseInfo.FirstName,
                        last_name = purchaseInfo.LastName,
                        number = purchaseInfo.CreditCardNumber,
                        type = Common.GetCardType(purchaseInfo.CreditCardNumber)
                    };

                    payer.funding_instruments.Add(new FundingInstrument()
                    {
                        credit_card = creditCard
                    });
                }

                if (!purchaseInfo.IsRecurring)
                {
                    var transaction = new Transaction
                    {
                        amount = new Amount
                        {
                            currency = "USD",
                            total = purchaseInfo.Amount.ToString()
                        },
                        description = "Featured Profile on ProductionHUB",
                        invoice_number = Common.GetRandomInvoiceNumber()
                    };

                    var payment = new Payment()
                    {
                        intent = "sale",
                        payer = payer,
                        transactions = new List<Transaction>() { transaction }
                    };

                    var createdPayment = payment.Create(apiContext);
                    TempData["info"] = createdPayment.id;

                    if (createdPayment.state == "approved")
                    {
                        action = "Completed";
                    }
                    else
                    {
                        action = "Rejected";
                    }
                }
                else
                {
                    var agreement = new Agreement()
                    {
                        name = "Basic profile",
                        description = "Monthly basic profile in perpetuity",
                        payer = payer,
                        plan = new Plan { id = purchaseInfo.BillingPlanId },
                        start_date = DateTime.UtcNow.AddDays(1).ToString("u").Replace(" ", "T"),
                    };

                    var createdAgreement = agreement.Create(apiContext);

                    TempData["info"] = createdAgreement.create_time;

                    TempData["success"] = "Recurring agreement created";
                }

                if (purchaseInfo.SavePaymentInfo)
                {
                    creditCard.external_customer_id = customerId;
                    creditCard.Create(apiContext);
                }

                return RedirectToAction(action);

            }
            catch (Exception exc)
            {
                TempData["error"] = exc.Message;
            }

            ViewBag.Cards = CreditCard.List(apiContext, externalCustomerId: customerId);
            ViewBag.Plans = plans;
            AddPaymentDropdowns();
            return View();
        }
        public ActionResult PaymentWithPayPal(string donationAmt)
        {          
            //OAuthTokenCredential tokenCredential = new OAuthTokenCredential("AeJs4Inwk1Pn8ZNhkWiSLwerx4K64E1PD5TtL4FF7XImtEZ29aAWBTxYOVIBWxEXlW6FycnBz3U7J8jQ", "ENerw7v3F1YT1w5YRYHRPCbjfVSpAbvHVTJFfqc0jWPyeq8hcgmvaZn-1T1WzklDVqw7Pd7MGp3KEQXO");
            //string accessToken = tokenCredential.GetAccessToken();

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

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

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

                if (string.IsNullOrEmpty(payerId))
                {

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

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

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

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

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

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

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

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

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

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

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

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    var guid = Request.Params["guid"];
                    var paymentId = Session[guid] as string;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var pymnt = new Payment() { id = paymentId };
                    var executedPayment = pymnt.Execute(apiContext, paymentExecution);
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return View("DonationFailureView");
            }
            return View("DonationSuccessView");
        }
        public static Payment CreatePayment(string baseUrl, string intent)
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            var apiContext = PayPalConfiguration.GetAPIContext();

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

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

            return createdPayment;
        }
        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/).
            }
        }
        private PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl, Data.Models.Plan plan)
        {
            //var plan = new Data.Models.Plan();
            var listItems = new ItemList()
            {
                items = new List <Item>()
            };

            listItems.items.Add(new Item()
            {
                name     = plan.PlanName,
                currency = "USD",
                price    = plan.Price.ToString(),
                quantity = "1",
            });
            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 = plan.Price.ToString()
            };
            var amount = new Amount()
            {
                currency = "USD",
                total    = plan.Price.ToString(),
                details  = details
            };
            var transactionList = new List <Transaction>();

            transactionList.Add(new Transaction()
            {
                description    = plan.PlanName + " Plan Payment Description",
                invoice_number = Convert.ToString(new Random().Next(100000)),
                amount         = amount,
                item_list      = listItems,
            });
            payment = new PayPal.Api.Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            return(payment.Create(apiContext));
        }
        /// <summary>
        /// Creates a future payment using the specified API context and correlation ID.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="payment">FuturePayment object to be used in creating the PayPal resource.</param>
        /// <param name="correlationId">(Optional) Application correlation ID</param>
        /// <returns>A new payment object setup to be used for a future payment.</returns>
        public static Payment Create(APIContext apiContext, FuturePayment payment, string correlationId = "")
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);

            if (!string.IsNullOrEmpty(correlationId))
            {
                apiContext.HTTPHeaders["PAYPAL-CLIENT-METADATA-ID"] = correlationId;
            }

            return(Payment.Create(apiContext, payment));
        }
        public static Payment CreatePayment(string fileName, Currency currency, decimal price, int quantity, string fileId, string userId)
        {
            var apiContext = PaypalConfig.GetAPIContext();

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

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

            return createdPayment;
        }
        private string GetPayPalLink(decimal total)
        {
            var payer = new Payer
            {
                payment_method = PaymentMethod
            };

            var amount = new Amount
            {
                currency = Currency,
                total    = total.ToString()
            };

            var transaction = new Transaction
            {
                amount = amount
            };

            var payment = new Payment
            {
                payer        = payer,
                transactions = new[] { transaction }.ToList(),
                intent        = Intent,
                redirect_urls = new RedirectUrls
                {
                    return_url = ReturnUrl,
                    cancel_url = CancelUrl
                }
            };

            var created      = payment.Create(this.apiContext);
            var links        = created.links.ToList();
            var approvalLink = links.FirstOrDefault(l => l.rel == ApprovalUrlRel);

            return(approvalLink.href);
        }
        /// <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));
        }
        public PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl, List <Course> courses, string currencyCode)
        {
            long?totalPrice = 0;

            _currency = currencyCode;
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            foreach (var course in courses)
            {
                var item = new Item();
                item.name     = course.Title;
                item.currency = _currency;
                item.price    = course.Price.ToString();
                item.quantity = "1";
                item.sku      = course.Id.ToString();
                totalPrice   += course.Price;
                itemList.items.Add(item);
            }

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

            // Configure Redirect Urls here with RedirectUrls object
            var redirectUrls = new RedirectUrls
            {
                cancel_url = redirectUrl + "&Cancel=true",
                return_url = redirectUrl
            };

            // Adding Tax, shipping and Subtotal details
            var details = new Details
            {
                tax      = "1",
                shipping = "1",
                subtotal = "1"
            };

            //Final amount with details
            var amount = new Amount
            {
                currency = _currency,
                total    = totalPrice.ToString()
                           //details = details
            };

            var transactionList = new List <Transaction>
            {
                new Transaction
                {
                    description    = "Transaction description",
                    invoice_number = Guid.NewGuid().ToString("N"),
                    amount         = amount,
                    item_list      = itemList
                }
            };

            _payment = new PayPal.Api.Payment
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirectUrls
            };
            return(_payment.Create(apiContext));
        }
Example #11
0
        public string GetPayLink(int courseId, User student)
        {
            var course = this.db.Courses.FirstOrDefault(x => x.Id == courseId);

            if (course == null)
            {
                //TODO Exception or retunr null
            }

            var isCreatedCourseFromCurrentInstructor = course.InstructorId == student.Id;

            var existsCourse = this.db.StudentCourses
                               .Where(x => x.StudentId == student.Id)
                               .ToList()
                               .Any(x => x.CourseId == course.Id);

            if (existsCourse || isCreatedCourseFromCurrentInstructor)
            {
                return(null);
            }

            var token = new OAuthTokenCredential(this.settings.ClientId, this.settings.ClientSecret)
                        .GetAccessToken();

            var apiContext = new APIContext(token);

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

            var amount = new Amount()
            {
                currency = "EUR",
                total    = course.Price.ToString()
            };

            var transactions = new Transaction()
            {
                amount = amount,
            };

            var payment = new PayPal.Api.Payment()
            {
                payer        = payer,
                transactions = new[] { transactions }.ToList(),
                intent        = "sale",
                redirect_urls = new RedirectUrls()
                {
                    return_url = "https://coursesp2p.azurewebsites.net/Payments/Process",
                    cancel_url = "https://coursesp2p.azurewebsites.net/Payments/Cancel"
                }
            };

            var createdPayment = payment.Create(apiContext);
            var links          = createdPayment.links.ToList();
            var approvalLink   = links.FirstOrDefault(l => l.rel == "approval_url");

            var payModel = new Models.Payment
            {
                PaymentId    = createdPayment.id,
                StudentEmail = student.Email,
                StudentId    = student.Id,
                CourseId     = course.Id,
                Amount       = course.Price
            };

            this.db.Payments.Add(payModel);
            this.db.SaveChanges();

            return(approvalLink.href);
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

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

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

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

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

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

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

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

                // Using the information from the redirect, setup the payment to execute.
                var paymentId = Session[guid] as string;
                var paymentExecution = new PaymentExecution() { payer_id = payerId };
                var payment = new Payment() { id = paymentId };

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

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

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

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

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

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

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

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

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

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

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

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


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

                var createdProfile = profile.Create(apiContext);


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

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

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


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

                var createdPayment = payment.Create(apiContext);


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

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

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

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

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

                    // Using the information from the redirect, setup the payment to execute.
                    var paymentId = Session[guid] as string;
                    var paymentExecution = new PaymentExecution() { payer_id = payerId };
                    var payment = new Payment() { id = paymentId };

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

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

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

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
Example #14
0
 /// <summary>
 /// Creates (and processes) a new Payment Resource.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <returns>Payment</returns>
 public Payment Create(APIContext apiContext)
 {
     return(Payment.Create(apiContext, this));
 }
Example #15
0
        public ActionResult PaymentWithCreditCard(string CreditCardId = "")
        {
            var pvm = PaypalViewModel.GetSamplePayment("*****@*****.**");

            var apiContext = PayPalConfig.GetAPIContext();

            // A transaction defines the contract of a payment.
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = pvm.Transaction.Amount.Currency,
                    total    = pvm.Transaction.Amount.Total,
                    details  = new Details()
                    {
                        shipping = pvm.Transaction.Amount.Detail.Shipping,
                        subtotal = pvm.Transaction.Amount.Detail.Subtotal,
                        tax      = pvm.Transaction.Amount.Detail.Tax
                    }
                },
                description = pvm.Transaction.Description,
                item_list   = new ItemList()
                {
                    items = pvm.Transaction.ItemList.Select(s => new Item
                    {
                        name     = s.Name,
                        currency = s.Currency,
                        price    = s.Price,
                        quantity = s.Quantity,
                        sku      = s.Sku
                    }).ToList(),
                    shipping_address = new ShippingAddress
                    {
                        city           = pvm.Transaction.ShippingAddress.City,
                        country_code   = pvm.Transaction.ShippingAddress.CountryCodeDomain,
                        line1          = pvm.Transaction.ShippingAddress.AddressLine,
                        postal_code    = pvm.Transaction.ShippingAddress.PostalCode,
                        state          = pvm.Transaction.ShippingAddress.State,
                        recipient_name = pvm.Transaction.ShippingAddress.RecipientName
                    }
                },
                invoice_number = String.IsNullOrEmpty(pvm.Transaction.InvoiceNumber) ? GetRandomInvoiceNumber() : pvm.Transaction.InvoiceNumber
            };

            // A resource representing a Payer that funds a payment.
            var payer = new Payer()
            {
                payment_method = "credit_card",
                payer_info     = new PayerInfo
                {
                    email = pvm.Payer.PayerInfo.Email
                }
            };

            if (String.IsNullOrEmpty(CreditCardId))
            {
                payer.funding_instruments = new List <FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card = new CreditCard()
                        {
                            billing_address = new Address()
                            {
                                city         = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.City,
                                country_code = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.CountryCodeDomain,
                                line1        = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.AddressLine,
                                postal_code  = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.PostalCode,
                                state        = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.State
                            },
                            cvv2         = pvm.Payer.FundingInstrument.CreditCard.Cvv2,
                            expire_month = pvm.Payer.FundingInstrument.CreditCard.ExpireMonth,
                            expire_year  = pvm.Payer.FundingInstrument.CreditCard.ExpireYear,
                            first_name   = pvm.Payer.FundingInstrument.CreditCard.FirstName,
                            last_name    = pvm.Payer.FundingInstrument.CreditCard.LastName,
                            number       = pvm.Payer.FundingInstrument.CreditCard.CcNumber,
                            type         = pvm.Payer.FundingInstrument.CreditCard.CcType
                        }
                    }
                };

                CreditCardId = PaypalVault.StoreCreditCardInPaypal(pvm.Payer.FundingInstrument.CreditCard);
            }
            else
            {
                //Here, we are assigning the User's Credit Card ID which we saved in Database
                payer.funding_instruments = new List <FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card_token = new CreditCardToken
                        {
                            credit_card_id = CreditCardId
                        }
                    }
                };
            }


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

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

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

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

            if (createdPayment.state.ToLower() != "approved")
            {
                //return View("FailureView");
                return(Content("Failed"));
            }

            return(Content("Success Id: " + CreditCardId));

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #16
0
        public IHttpActionResult CreatePayment(object data)
        {
            string userId = this.User.Identity.GetUserId();
            RemoveCart(userId);

            var apiContext = GetApiContext();
            if (apiContext == null)
                return StatusCode(HttpStatusCode.NotAcceptable);

            Amount amount = new Amount();
            amount.currency = "USD";
            Transaction transaction = new Transaction();
            transaction.item_list = new ItemList();
            transaction.item_list.items = new List<PayPal.Api.Item>();

            string json = JsonConvert.SerializeObject(data);
            double total = 0;

            RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
            List<BitCoupon.API.Models.Item> items = root.data.items;

            if (items.Count == 0)
                return NotFound();

            for (int i = 0; i < items.Count; i++)
            {
                var coupon = db.Coupons.Find(Int32.Parse(items[i].id));
                //if there are no coupons to buy (qunatity of purchase is bigger then total number of coupons), return BadRequest (don't allow purchase)
                if (items[i].quantity * coupon.RequiredNumberOfCoupons > coupon.TotalNumberOfCoupons)
                    return BadRequest();

                total += items[i].total;

                transaction.item_list.items.Add(new PayPal.Api.Item()  //add items to item list
                {
                    name = items[i].name,
                    description = items[i].data.DescriptionOnCoupon,
                    quantity = items[i].quantity.ToString(),
                    price = items[i].price.ToString(),
                    currency = amount.currency
                });
            }
            amount.total = total.ToString();  //total amount to pay

            transaction.amount = amount;

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

            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payer;
            payment.transactions = new List<Transaction>();
            payment.transactions.Add(transaction);

            payment.redirect_urls = new RedirectUrls();  //create redirect urls where paypal will return depending did user finished payment

            payment.redirect_urls.return_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal?userId=" + this.User.Identity.GetUserId());

            payment.redirect_urls.cancel_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal");

            Payment createdPayment = null;

            try
            {
                createdPayment = payment.Create(apiContext);
            }
            catch
            {
                return StatusCode(HttpStatusCode.NotAcceptable);
            }

            CreateCart(userId, items, double.Parse(amount.total));

            return Json(createdPayment.GetApprovalUrl());
        }
Example #17
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;
        }
Example #18
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");
        }
        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();

            // ###Payment
            // A Payment Resource; create one with its intent set to `sale`, `authorize`, or `order`
            var payment = new Payment()
            {
                intent = "authorize",
                // A resource representing a Payer that funds a payment. Use the List of `FundingInstrument` and the Payment Method as 'credit_card'
                payer = new Payer()
                {
                    // The Payment creation API requires a list of
                    // FundingInstrument; add the created `FundingInstrument`
                    // to a List
                    funding_instruments = new List<FundingInstrument>() 
                    {
                        // A resource representing a Payeer's funding instrument.
                        // Use a Payer ID (A unique identifier of the payer generated
                        // and provided by the facilitator. This is required when
                        // creating or using a tokenized funding instrument)
                        // and the `CreditCardDetails`
                        new FundingInstrument()
                        {
                            // A resource representing a credit card that can be used to fund a payment.
                            credit_card = new CreditCard()
                            {
                                billing_address = new Address()
                                {
                                    city = "Johnstown",
                                    country_code = "US",
                                    line1 = "52 N Main ST",
                                    postal_code = "43210",
                                    state = "OH"
                                },
                                cvv2 = "874",
                                expire_month = 11,
                                expire_year = 2018,
                                first_name = "Joe",
                                last_name = "Shopper",
                                number = "4877274905927862",
                                type = "visa"
                            }
                        }
                    },
                    payment_method = "credit_card"
                },
                // The Payment creation API requires a list of transactions; add the created `Transaction` to a List
                transactions = new List<Transaction>()
                {
                    // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it. Transaction is created with a `Payee` and `Amount` types
                    new Transaction()
                    {
                        // Let's you specify a payment amount.
                        amount = new Amount()
                        {
                            currency = "USD",
                            // Total must be equal to sum of shipping, tax and subtotal.
                            total = "107.47",
                            details = new Details()
                            {
                                shipping = "0.03",
                                subtotal = "107.41",
                                tax = "0.03"
                            }
                        },
                        description = "This is the payment transaction description."
                    }
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest(title: "Create authorization for credit card payment", requestObject: payment);
            #endregion

            // Create a payment by posting to the APIService
            // using a valid APIContext
            var createdPayment = payment.Create(apiContext);

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

            // ###Authorization
            // Once the payment with intent set to `authorize` has been created, retrieve its authorization object.
            var authorization = createdPayment.transactions[0].related_resources[0].authorization;

            // Specify an amount to capture.  By setting 'is_final_capture' to true, all remaining funds held by the authorization will be released from the funding instrument.
            var capture = new Capture()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    total = "4.54"
                },
                is_final_capture = true
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.AddNewRequest("Capture authorized payment", capture, string.Format("URI: v1/payments/authorization/{0}/capture", authorization.id));
            #endregion

            // Capture an authorized payment by POSTing to
            // URI v1/payments/authorization/{authorization_id}/capture
            var responseCapture = authorization.Capture(apiContext, capture);

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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
        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;
        }
Example #21
0
        public string Payment()
        {
            var             culture = CultureInfo.GetCultureInfo("en-US");
            IFormatProvider numericFormatProvider = culture.NumberFormat;


            var orderLayer = new OrderLayer();

            var itemList = new ItemList();

            itemList.items = new List <Item>();
            foreach (var line in orderLayer.Order.Lines)
            {
                var item = new Item
                {
                    currency    = "TRY",
                    description = line.ProductName,
                    name        = line.ProductName,
                    price       = line.Price.ToString("F2", numericFormatProvider),
                    quantity    = line.Quantity.ToString(),
                    sku         = line.ProductId.ToString(),
                    tax         = line.Tax.ToString("F2", numericFormatProvider)
                };
                itemList.items.Add(item);
            }
            var payer = new Payer {
                payment_method = "paypal"
            };
            var baseUrl  = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Order/PaymentCallback/Paypal";
            var redirUrl = new RedirectUrls
            {
                return_url = baseUrl + "?result=ok",
                cancel_url = baseUrl + "?result=fail"
            };
            var details = new Details
            {
                fee      = (orderLayer.Order.InstallmentFee + orderLayer.Order.PaymentFee).ToString("F2", numericFormatProvider),
                shipping = orderLayer.Order.ShipCost.ToString("F2", numericFormatProvider),
                tax      = orderLayer.Order.TaxTotal.ToString("F2", numericFormatProvider),
                subtotal = orderLayer.Order.OrderTotal.ToString("F2", numericFormatProvider)
            };
            var amount = new Amount
            {
                currency = "TRY",
                total    = orderLayer.Order.GrandTotal.ToString("F2", numericFormatProvider),
                details  = details
            };
            var transactionList = new List <Transaction>();

            transactionList.Add(
                new Transaction
            {
                invoice_number = orderLayer.Order.Id.ToString("00000000"),
                amount         = amount,
                item_list      = itemList
            }
                );
            var payment = new PayPal.Api.Payment
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrl
            };
            var paymenter = payment.Create(apiCtx);
            var links     = paymenter.links.GetEnumerator();

            while (links.MoveNext())
            {
                var link = links.Current;
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    return(link.href);
                }
            }
            return(string.Empty);
        }
Example #22
0
        /// <summary>
        /// Creates PayPal payment
        /// </summary>
        /// <param name="apiContext">PayPal API context</param>
        /// <param name="redirectUrl">URL for redirecting after cancel of return from PayPal payment page</param>
        /// <returns></returns>
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, CartViewModel cart)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            foreach (var track in cart.Tracks)
            {
                var item = new Item();
                item.currency = cart.CurrencyShortName;
                item.name     = track.Name;
                item.price    = track.Price.Amount.ToString().Replace(',', '.');
                item.quantity = "1";

                itemList.items.Add(item);
            }

            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 = cart.TotalPrice.ToString().Replace(',', '.')
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = cart.CurrencyShortName,
                total    = cart.TotalPrice.ToString().Replace(',', '.'), // 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 = (new Random()).Next(1000000).ToString(), // "your invoice number",
                amount         = amount,
                item_list      = itemList
            });

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

            // Create a payment using a APIContext
            return(payment.Create(apiContext));
        }
Example #23
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);
        }
Example #24
0
        public Payment CreatePayment(GroveCM.Models.Order order, string cancelUrl, string returnUrl)
        {
            var amount = CreateAmount(order);

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

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

            payment = payment.Create(Api);

            return payment;
        }
Example #25
0
        public PaymentHandler(List <PaypalItem> items, int uid)
        {
            if (apiContext == null)
            {
                GetApiContext();
            }
            userId = uid;

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

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

            string DomainName = "http://localhost:20629";
            //string DomainName = "https://localhost:44394";
            var redirUrls = new RedirectUrls()
            {
                cancel_url = DomainName + "/Cancel/",
                return_url = DomainName + "/Wallet/PaymentSucess/"
            };

            // Add Items to List
            ItemList itemList = new ItemList();

            itemList.items = new List <Item>();

            double subtotal  = 0;
            double taxamount = 0;

            foreach (PaypalItem item in items)
            {
                List <NameValuePair> nl      = new List <NameValuePair>();
                NameValuePair        sizeadd = new NameValuePair();
                sizeadd.name  = "Size";
                sizeadd.value = item.size;
                nl.Add(sizeadd);

                PayPal.Api.Item tmp = new Item
                {
                    currency = item.currency,
                    price    = item.price.ToString(),
                    quantity = "1",
                    sku      = item.sku,
                };

                subtotal += (item.price * 1);
                itemList.items.Add(tmp);
            }

            taxamount = 0;

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

            double total = taxamount + _fixedShipping + subtotal;

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

            var    transactionList = new List <Transaction>();
            Random rand            = new Random(DateTime.Now.Second);
            String invoice         = "INV-" + System.DateTime.Now.Ticks.ToString();

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

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

            var createdPayment = payment.Create(apiContext);

            //    PopulateOrder(invoice , items, amount);

            var links = createdPayment.links.GetEnumerator();

            while (links.MoveNext())
            {
                var link = links.Current;
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    HttpContext.Current.Response.Redirect(link.href);
                }
            }
        }
Example #26
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);
            };
        }
        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");
        }
Example #28
0
        private Payment CreatePayment(APIContext apicontext, string redirectURl)
        {
            var ItemLIst = new ItemList()
            {
                items = new List <Item>()
            };
            List <Models.Home.Item> cart = (List <Models.Home.Item>)(Session["cart"]);

            foreach (var item in cart)
            {
                ItemLIst.items.Add(new Item()
                {
                    name     = item.Product.ProductName,
                    currency = "USD",
                    price    = item.Product.Price.ToString(),
                    quantity = item.Product.Quantity.ToString(),
                    sku      = "sku"
                });
            }

            var payer = new Payer()
            {
                payment_method = "paypal"
            };
            var redirUrl = new RedirectUrls()
            {
                cancel_url = redirectURl + "&Cancel=true",
                return_url = redirectURl
            };

            var details = new Details()
            {
                tax      = "1",
                shipping = "2",
                subtotal = Session["SesTotal"].ToString()
            };

            var amount = new Amount()
            {
                currency = "USD",
                total    = (Convert.ToDouble(details.tax) + Convert.ToDouble(details.shipping) + Convert.ToDouble(details.subtotal)).ToString(),
                details  = details
            };

            var transactionList = new List <Transaction>();

            transactionList.Add(new Transaction()
            {
                description    = "Transaction Description",
                invoice_number = Convert.ToString((new Random()).Next(100000)),
                amount         = amount,
                item_list      = ItemLIst
            });

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

            return(payment.Create(apicontext));
        }
Example #29
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)
                };
            }
        }
        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;
        }
        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();

            // Items within a transaction.
            var item = new Item()
            {
                name = "Item Name",
                currency = "USD",
                price = "1",
                quantity = "5",
                sku = "sku"
            };

            // A resource representing a credit card that can be used to fund a payment.
            var credCardToken = new CreditCardToken()
            {
                credit_card_id = "CARD-0F049886A57009534KRVL4LQ"
            };

            var amnt = new Amount()
            {
                currency = "USD",
                total = "7",
                details = new Details()
                {
                    shipping = "1",
                    subtotal = "5",
                    tax = "1"
                }
            };

            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. 
            var tran = new Transaction()
            {
                amount = amnt,
                description = "This is the payment transaction description.",
                item_list = new ItemList() { items = new List<Item>() { item } }
            };

            // A resource representing a Payer's funding instrument. For stored credit card payments, set the CreditCardToken field on this object.
            var fundInstrument = new FundingInstrument()
            {
                credit_card_token = credCardToken
            };

            // A Payment Resource; create one using the above types and intent as 'sale'
            var pymnt = new Payment()
            {
                intent = "sale",
                payer = new Payer()
                {
                    funding_instruments = new List<FundingInstrument>() { fundInstrument },
                    payment_method = "credit_card"
                },
                transactions = new List<Transaction>() { tran }
            };

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

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

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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #32
0
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, string sdt)
        {
            var sanpham = cn.XemGioHangs.SqlQuery("XemGioHang @SDT", new System.Data.SqlClient.SqlParameter("@SDT", sdt)).ToList();
            //thanh toán
            int tt = 0;

            foreach (var i in sanpham)
            {
                tt += (Convert.ToInt32(i.Gia) / 23000) * Convert.ToInt32(i.SoLuong);
            }
            //create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            //Adding Item Details like name, currency, price etc
            foreach (var sp in sanpham)
            {
                itemList.items.Add(new Item()
                {
                    name     = sp.TenSP,
                    currency = "USD",
                    price    = ((int)sp.Gia / 23000).ToString(),
                    quantity = "" + sp.SoLuong.ToString(),
                    //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
            };
            // Adding Tax, shipping and Subtotal details
            var details = new Details()
            {
                tax      = "1",
                shipping = "2",
                subtotal = "" + tt
            };
            //Final amount with details
            var amount = new Amount()
            {
                currency = "USD",
                total    = (Convert.ToDouble(details.tax) + Convert.ToDouble(details.shipping) + Convert.ToDouble(details.subtotal)).ToString(), // Total must be equal to sum of tax, shipping and subtotal.
                details  = details
            };
            var transactionList = new List <Transaction>();

            // Adding description about the transaction
            transactionList.Add(new Transaction()
            {
                description    = "De-Montre",
                invoice_number = Convert.ToString((new Random()).Next(100000)), //Generate an Invoice No
                amount         = amount,
                item_list      = itemList
            });
            payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a APIContext
            return(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))
            {
                var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPalWithDiscount.aspx?";
                var guid = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;

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

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

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

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

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

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

                // Using the information from the redirect, setup the payment to execute.
                var paymentId = Session[guid] as string;
                var paymentExecution = new PaymentExecution { payer_id = payerId };
                var payment = new Payment { id = paymentId };

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

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

                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
Example #34
0
        public IHttpActionResult PostCreatePayment([FromBody]PayPalPaymentConfirmation model)
        {
            var userName = this.User.Identity.Name;

            string userId = "";

            try
            {
                userId = db.Users.SingleOrDefault(x => x.Email == userName).Id;
            }
            catch
            {
                return BadRequest("Unregistered user");
            }

            List<RoomAvailability> listOfUnpaidRooms = new List<RoomAvailability>();
            List<ReservationsPaymentAPI> listOfUnpaidRoomsFullDetails = new List<ReservationsPaymentAPI>();
            if (userId != null)
            {
                listOfUnpaidRooms = db.RoomAvailabilities.Where(x => x.UserId == userId && x.IsPaid == false).ToList();
            }
            if (listOfUnpaidRooms.Count > 0)
            {
                foreach (var room in listOfUnpaidRooms)
                {
                    string accomodationName = db.Accomodations.Single(x => x.AccomodationId == room.AccomodationId).AccomodationName;
                    string roomName = db.Rooms.Single(x => x.RoomId == room.RoomId).RoomType.RoomTypeName;

                    listOfUnpaidRoomsFullDetails.Add(new ReservationsPaymentAPI 
                    { 
                        AccommodationName =  accomodationName,
                        RoomName = roomName,
                        AccomodationId = room.AccomodationId,
                        ArrivalDate = room.ArrivalDate,
                        DepartureDate = room.DepartureDate,
                        IsPaid = room.IsPaid,
                        RoomAvailabilityId = room.RoomAvailabilityId,
                        RoomId = room.RoomId,
                        TotalPrice = room.TotalPrice,
                        UserId = room.UserId,
                        UserEmail = userName
                    });
                }
            }

            //BEGIN OF PAYPAL PAYMENT

            var config = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            apiContext.Config = config;
            Amount amount = new Amount();

            amount.total = listOfUnpaidRoomsFullDetails.Sum(x => x.TotalPrice).ToString();
            amount.currency = "USD";

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.item_list = new ItemList();
            transaction.item_list.items = new List<Item>();

            List<Item> listOfRoomsToPay = new List<Item>();
            foreach(var room in listOfUnpaidRoomsFullDetails)
            {
                listOfRoomsToPay.Add(new Item
                {
                    name = room.RoomName,
                    description = room.AccommodationName,
                    quantity = "1",
                    price = room.TotalPrice.ToString(),
                    currency = "USD"
                });
            }


            transaction.item_list.items.AddRange(listOfRoomsToPay);

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

            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payer;
            payment.transactions = new List<Transaction>();
            payment.transactions.Add(transaction);
            payment.redirect_urls = new RedirectUrls();
            payment.redirect_urls.return_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal?userId=" + userId);
            payment.redirect_urls.cancel_url = String.Format("http://{0}{1}", HttpContext.Current.Request.Url.Authority, "/api/PayPal");
  
            Payment createdPayment = payment.Create(apiContext);

            return Ok(createdPayment.GetApprovalUrl());
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

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

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

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

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

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

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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
        public ActionResult Payment(Models.Payment model)
        {
            //Dictionary<string, string> payPalConfig = new Dictionary<string, string>();
            //payPalConfig.Add("mode", "sandbox");
            //OAuthTokenCredential tokenCredential = new AuthTokenCredential("AXVrBytGm6RdmOYfcUFM-VoOa8TvQhVYN6-TapoUzU2oErEpO0XzbYn8qD26R3iFduECZqOQmB78bZbS", "EGz3u0h-poL7i3MbLUQQXgqiYPEbbdzX95h57JzlnKrjKRV1-MNLPApqgKt30Y7VWmgwb5UxFWja0__2", payPalConfig);
            //string accessToken = tokenCredential.GetAccessToken();
            var apiContext = Configuration.GetAPIContext();
            try
            {
                string payerId = Request.Params["PayerID"];

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

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

                    // ###Redirect URLS
                    // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                    var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Tutors/AccountSettings?";
                    var guid = Convert.ToString((new Random()).Next(100000));
                    var redirectUrl = baseURI + "guid=" + guid;
                    var redirUrls = new RedirectUrls()
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    };

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

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

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

                    // The Payment creation API requires a list of
                    // Transaction; add the created `Transaction`
                    // to a List
                    transactionList.Add(new PayPal.Api.Transaction()
                    {
                        description = "Mezo Experts Services",
                        invoice_number = Common.GetRandomInvoiceNumber(),
                        amount = amount,
                        item_list = itemList
                    });

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

                    };

                    // Create a payment using a valid APIContext

                    var createdPayment = payment.Create(apiContext);

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

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

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return Redirect(paypalRedirectUrl);
                }
               
                return null;
            }
            catch (Exception ex)
            {
              
                return View("FailureView");
            }
            // return  Json(new { result = createdPayment.links[0].href, redirect = createdPayment.links[1].href, execute = createdPayment.links[2].href });
       
            return null;
        }
Example #37
0
        public static Payment CreatePayment(APIContext apiContext, string redirectUrl, List <Cart> productList)
        {
            List <CartItem> orderSession = new List <CartItem>();

            //similar to credit card create itemlist and add item objects to it
            var         itemList    = new ItemList();
            List <Item> listOfItems = new List <Item>();

            decimal subTotal = 0;

            foreach (var product in productList)
            {
                Item item = new Item();
                item.currency    = "USD";
                item.name        = product.Product_Name;
                item.description = product.Product_Description;
                item.quantity    = product.Quantity.ToString();
                item.sku         = product.Product_Id.ToString();
                item.price       = product.UnitPrice.ToString();
                listOfItems.Add(item);
                subTotal += (product.Quantity > 1) ? product.UnitPrice * product.Quantity : product.UnitPrice;

                CartItem _orderSession = new CartItem();
                _orderSession.Cart_Id    = product.Cart_Id;
                _orderSession.User_Id    = product.User_Id;
                _orderSession.Product_Id = product.Product_Id;
                _orderSession.Quantity   = product.Quantity;
                _orderSession.UnitPrice  = (decimal)product.PriceTotal;

                _cartDataService.AddCartItem(_orderSession);
            }
            itemList.items = listOfItems;
            var payer = new Payer()
            {
                payment_method = "paypal"
            };

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

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

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

            var    transactionList = new List <Transaction>();
            Random r           = new Random();
            string invoiceCode = DateTime.Now.ToString("MMddyyyyss") + r.Next(100);

            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",

                invoice_number = invoiceCode + 1,
                amount         = amount,
                item_list      = itemList,
            });


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

            // Create a payment using a APIContext
            return(payment.Create(apiContext));
        }
Example #38
0
        protected override void RunSample()
        {
            var apiContext = PayPalConfig.GetAPIContext();

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

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

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

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

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

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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #39
0
        private bool MakePayment(Payment payment)
        {
            try
            {
                payment.Create(CreatePaypalContext());

                return true;
            }
            catch (Exception ex)
            {
                _repositoryManager.OrderRepository.Delete(payment.transactions.First().invoice_number);
                return false;
            }
        }
Example #40
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");
        }
Example #41
0
        /// <summary>
        /// ตัดบัตรเครดิต
        /// </summary>
        /// <param name="payment">ข้อมูลบัตรเครดิตที่ต้องการดำเนินการ</param>
        public PaymentResult ChargeCreditCard(PaymentInformation paymentInfo)
        {
            var tokenCredential = new OAuthTokenCredential(_appConfig.PaypalClientId, _appConfig.PaypalClientSecret, new Dictionary<string, string>());
            var accessToken = tokenCredential.GetAccessToken();
            var config = new Dictionary<string, string>();
            config.Add("mode", "sandbox"); // HACK: Paypal mode ('live' or 'sandbox')
            var apiContext = new APIContext
            {
                Config = config,
                AccessToken = accessToken
            };

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

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

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

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);
            var result = PaymentResult.Unknow;
            return Enum.TryParse<PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow;
        }
        public ActionResult PaymentWithPaypal(Cart cart)
        {
            ShippingDetails shippingDetails = (ShippingDetails)TempData["shipping_details"];

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

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

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

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

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

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

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

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

                    List<Transaction> transactions = GenerateteTransactions(cart);

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

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

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

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

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

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

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

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

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

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

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

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

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

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

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

            return(Enum.TryParse <PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow);
        }