Example #1
0
        public async Task <PayPal.Api.Payment> GetPayPalPaymentAsync(Order order, Card card, string requestId = null)
        {
            // TODO: Put null handling on non-required fields
            // TODO: Put error handling on required fields.

            PayPal.Api.ItemList payPalItemList = new PayPal.Api.ItemList();

            payPalItemList.items = new List <PayPal.Api.Item>();
            foreach (var orderItem in order.OrderItems)
            {
                payPalItemList.items.Add(
                    new PayPal.Api.Item()
                {
                    currency    = String.IsNullOrEmpty(orderItem.Currency) ? "USD" : orderItem.Currency,  // Required
                    description = orderItem.Description,
                    price       = orderItem.Price.ToString("n2", CultureInfo.InvariantCulture),
                    name        = String.IsNullOrEmpty(orderItem.Name) ? "Product Name" : orderItem.Name, // Required
                    quantity    = orderItem.Quantity.ToString("n0", CultureInfo.InvariantCulture),
                    sku         = orderItem.ProductSKU,
                    //url = cartItem.ProductUrl, // Not defined for this resource type
                });
            }
            ;

            var transaction = new PayPal.Api.Transaction()
            {
                amount = new PayPal.Api.Amount()
                {
                    currency = "USD",
                    total    = order.Total.ToString(), // Required, and must be the sum of the item totals.
                    details  = new PayPal.Api.Details()
                    {
                        shipping = order.ShippingTotal.ToString("n2", CultureInfo.InvariantCulture),
                        subtotal = order.Subtotal.ToString("n2", CultureInfo.InvariantCulture),
                        tax      = order.TaxTotal.ToString("n2", CultureInfo.InvariantCulture),
                    }
                },
                invoice_number = order.OrderId.ToString(),
                item_list      = payPalItemList,
            };

            var payer = new PayPal.Api.Payer()
            {
                payment_method      = "credit_card", // required?
                funding_instruments = new List <PayPal.Api.FundingInstrument>()
                {
                    new PayPal.Api.FundingInstrument()
                    {
                        credit_card = new PayPal.Api.CreditCard()
                        {
                            first_name      = card.FirstName,
                            last_name       = card.LastName,
                            billing_address = new PayPal.Api.Address()
                            {
                                line1        = card.BillingAddress.AddressLine1,
                                line2        = card.BillingAddress.AddressLine2,
                                city         = card.BillingAddress.City,
                                country_code =
                                    card.BillingAddress.Country == null ? "US" : card.BillingAddress.Country.ToString().ToUpper(),
                                state       = card.BillingAddress.StateProvince,
                                postal_code = card.BillingAddress.ZipPostalCode,
                            },
                            type         = card.CardType.ToLowerInvariant(),
                            number       = card.CardNumber,
                            cvv2         = card.CardCvvCode,
                            expire_month = Convert.ToInt32(card.ExpirationMonth),
                            expire_year  = Convert.ToInt32(card.ExpirationYear),
                        }
                    }
                }
            };

            PayPal.Api.Payment paymentRequest = new PayPal.Api.Payment()
            {
                intent       = "sale",
                payer        = payer,
                transactions = new List <PayPal.Api.Transaction>()
                {
                    transaction
                }
            };

            if (order == null)
            {
                throw new ArgumentException("GetPayPalPaymentAsync: Cart can't be null.");
            }
            if (order == null)
            {
                throw new ArgumentException("GetPayPalPaymentAsync: Card can't be null.");
            }
            if (String.IsNullOrEmpty(requestId))
            {
                throw new ArgumentException("GetPayPalPaymentAsync: RequestID can't be null.");
            }

            PayPal.Api.APIContext apiContext = new PayPal.Api.APIContext();

            try
            {
                apiContext = await GetPayPalApiContextAsync(requestId);
            }
            catch (Exception ex)
            {
                throw;
            }

            //https://developer.paypal.com/docs/api/#create-a-payment
            PayPal.Api.Payment response = new PayPal.Api.Payment();

            try
            {
                // Wrap this in a Task so it's awaitable.
                response = paymentRequest.Create(apiContext);
            }
            catch (PayPal.HttpException ex) { throw; }
            catch (InvalidCastException ex) { throw; }
            catch (Exception ex) { throw; }

            State.Payment = response;
            await State.WriteStateAsync();

            return(await Task.FromResult(response));
        }
        public ActionResult SaveOrder(FormCollection fc)
        {
            if (IsCardNumberValid(NormalizeCardNumber(fc["cardNumber"])))
            {
                bool res = false;
                switch (GetCardType(fc["cardNumber"]))
                {
                case (CardType.Amex):
                    fc["cardType"] = "amex";
                    res            = true;
                    break;

                case (CardType.Discover):
                    fc["cardType"] = "discover";
                    res            = true;
                    break;

                case (CardType.MasterCard):
                    fc["cardType"] = "mastercard";
                    res            = true;
                    break;

                case (CardType.VISA):
                    fc["cardType"] = "visa";
                    res            = true;
                    break;

                default:
                    res = false;
                    break;
                }



                if (res)
                {
                    List <Item> cart    = (List <Item>)Session["cart"];
                    Invoice     invoice = new Invoice();
                    invoice.CustomerName    = fc["customerName"];
                    invoice.CustomerAddress = fc["customerAddress"];
                    invoice.Name            = "New Invoice";

                    PayPal.Api.Item        paitem;
                    List <Item>            lstItem  = (List <Item>)Session["cart"];
                    List <PayPal.Api.Item> itms     = new List <PayPal.Api.Item>();
                    PayPal.Api.ItemList    itemList = new PayPal.Api.ItemList();
                    decimal totalPrice = 0;
                    foreach (var item in lstItem)
                    {
                        paitem          = new PayPal.Api.Item();
                        paitem.name     = item.pr.ProductName;
                        paitem.currency = "USD";
                        paitem.price    = item.pr.Price.ToString();// "5";
                        paitem.quantity = "1";
                        paitem.sku      = "sku";

                        if (item.Quantity > 0)
                        {
                            for (int i = 0; i < Convert.ToInt16(item.Quantity); i++)
                            {
                                itms.Add(paitem);
                            }
                            itemList.items = new List <PayPal.Api.Item>();
                            foreach (var itm in itms)
                            {
                                itemList.items.Add(itm);
                            }

                            totalPrice = totalPrice + item.pr.Price * item.Quantity;
                        }
                    }
                    //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


                    //Address for the payment
                    PayPal.Api.Address billingAddress = new PayPal.Api.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
                    PayPal.Api.CreditCard crdtCard = new PayPal.Api.CreditCard();
                    crdtCard.billing_address = billingAddress;
                    crdtCard.cvv2            = fc["CVV"];                       //card cvv2 number
                    crdtCard.expire_month    = Convert.ToInt32(fc["expMonth"]); //card expire date
                    crdtCard.expire_year     = Convert.ToInt32(fc["expYear"]);  //card expire year
                    crdtCard.first_name      = fc["nameOnCardFirstName"];
                    crdtCard.last_name       = fc["nameOnCardLastName"];

                    crdtCard.number = fc["cardNumber"]; //enter your credit card number here
                    crdtCard.type   = fc["cardType"];   //credit card type here paypal allows 4 types

                    // Specify details of your payment amount.
                    PayPal.Api.Details details = new PayPal.Api.Details();
                    details.shipping = (1 * Convert.ToInt32(0)).ToString();
                    details.subtotal = totalPrice.ToString();
                    details.tax      = (1 * Convert.ToInt32(0)).ToString();

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

                    // Now make a transaction object and assign the Amount object
                    Random random = new Random();
                    PayPal.Api.Transaction tran = new PayPal.Api.Transaction();
                    tran.amount         = amnt;
                    tran.description    = "Description about the payment amount.";
                    tran.item_list      = itemList;
                    tran.invoice_number = random.Next().ToString();

                    // 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 <PayPal.Api.Transaction> transactions = new List <PayPal.Api.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

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

                    // The Payment creation API requires a list of FundingIntrument

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

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

                    // finally create the payment object and assign the payer object & transaction list to it
                    PayPal.Api.Payment pymnt = new PayPal.Api.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

                        PayPal.Api.APIContext apiContext = PayPalIntegration.Models.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.

                        PayPal.Api.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)
                    {
                        ViewBag.Error = "Error: " + ex.Message;
                        return(View("FailureView"));
                    }
                    return(View("Thanks"));
                }
                else
                {
                    ViewBag.Error = "Please provide valid card";
                    return(View("FailureView"));
                }
            }
            else
            {
                ViewBag.Error = "Please provide valid credit card number";
                return(View("FailureView"));
            }
        }
        public ActionResult AddressAndPayment(OrderViewModel orderViewModel)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Months = PayPalHelper.Months;

                ViewBag.Years = PayPalHelper.Years;

                ViewBag.CreditCardTypes = PayPalHelper.CreditCardTypes;

                ViewBag.Countries = PayPalHelper.Countries;

                return(View(orderViewModel));
            }

            try
            {
                //create the order to store information in our database
                var     cart       = ShoppingCart.GetCart(this.HttpContext);
                Order   order      = new Order();
                decimal orderTotal = 0;
                order.Username     = User.Identity.Name;
                order.OrderDate    = DateTime.Now;
                order.OrderDetails = new List <OrderDetail>();

                var cartProducts = cart.GetCartProducts();
                // Iterate over the products in the cart,
                // adding the order details for each
                foreach (var product in cartProducts)
                {
                    var orderDetail = new OrderDetail
                    {
                        ProductId = product.ProductId,
                        OrderId   = order.OrderId,
                        UnitPrice = product.Product.Price,
                        Quantity  = product.Count
                    };
                    // Set the order total of the shopping cart
                    orderTotal += (product.Count * product.Product.Price);
                    order.OrderDetails.Add(orderDetail);
                }
                // Set the order's total to the orderTotal count
                order.Total = orderTotal;

                //add everything to the DB
                dbContext.Orders.Add(order);
                dbContext.OrderDetails.AddRange(order.OrderDetails);

                //proccess to paypal
                List <PayPal.Api.Item> items = new List <PayPal.Api.Item>();
                foreach (OrderDetail orderDetail in order.OrderDetails)
                {
                    PayPal.Api.Item item = new PayPal.Api.Item();
                    item.name     = dbContext.Products.Single(p => p.ProductId == orderDetail.ProductId).Name;
                    item.currency = "USD";
                    item.price    = orderDetail.UnitPrice.ToString();
                    item.quantity = orderDetail.Quantity.ToString();
                    item.sku      = orderDetail.ProductId.ToString();

                    items.Add(item);
                }
                PayPal.Api.ItemList itemList = new PayPal.Api.ItemList();
                itemList.items = items;

                PayPal.Api.Address address = new PayPal.Api.Address();
                address.city         = orderViewModel.City;
                address.country_code = orderViewModel.Country;
                address.line1        = orderViewModel.Address;
                address.postal_code  = orderViewModel.PostalCode.ToString();
                address.state        = orderViewModel.State;

                PayPal.Api.CreditCard creditCard = new PayPal.Api.CreditCard();
                creditCard.billing_address = address;
                creditCard.cvv2            = orderViewModel.CSC.ToString();
                creditCard.expire_month    = Int32.Parse(orderViewModel.ExpirationMonth);
                creditCard.expire_year     = Int32.Parse(orderViewModel.ExpirationYear);
                creditCard.first_name      = orderViewModel.FirstName;
                creditCard.last_name       = orderViewModel.LastName;
                creditCard.number          = orderViewModel.CreditCardNumber;
                creditCard.type            = orderViewModel.CcType;

                PayPal.Api.Details details = new PayPal.Api.Details();
                details.shipping = "1";
                details.subtotal = order.Total.ToString();
                details.tax      = "1";

                PayPal.Api.Amount amount = new PayPal.Api.Amount();
                amount.currency = "USD";
                amount.total    = (order.Total + 2).ToString();
                amount.details  = details;

                PayPal.Api.Transaction transaction = new PayPal.Api.Transaction();
                transaction.amount         = amount;
                transaction.description    = "Description goes here";
                transaction.item_list      = itemList;
                transaction.invoice_number = order.OrderId.ToString();

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

                PayPal.Api.FundingInstrument fundInstrument = new PayPal.Api.FundingInstrument();
                fundInstrument.credit_card = creditCard;

                List <PayPal.Api.FundingInstrument> fundingList = new List <PayPal.Api.FundingInstrument>();
                fundingList.Add(fundInstrument);

                PayPal.Api.Payer payer = new PayPal.Api.Payer();
                payer.funding_instruments = fundingList;
                payer.payment_method      = "credit_card";

                PayPal.Api.Payment payment = new PayPal.Api.Payment();
                payment.intent       = "sale";
                payment.payer        = payer;
                payment.transactions = transactionList;

                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

                    PayPal.Api.APIContext apiContext = PayPalConfig.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.

                    PayPal.Api.Payment createdPayment = payment.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"));
                }


                cart.EmptyCart();
                return(RedirectToAction("Complete", new { id = order.OrderId }));
            }
            catch (Exception ex)
            {
                //Invalid - redisplay with errors
                //return View(order);
            }
            return(View());
        }