A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.

See PayPal Developer documentation for more information.

Inheritance: CartBase
        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");
        }
Example #3
1
 public static Transaction GetTransaction()
 {
     var transaction = new Transaction();
     transaction.description = "Test Description";
     transaction.note_to_payee = "Test note to payee";
     transaction.amount = AmountTest.GetAmount();
     transaction.payee = PayeeTest.GetPayee();
     transaction.item_list = ItemListTest.GetItemList();
     transaction.related_resources = new List<RelatedResources>();
     transaction.related_resources.Add(RelatedResourcesTest.GetRelatedResources());
     return transaction;
 }
Example #4
1
 public static Payment CreateFuturePayment()
 {
     FuturePayment pay = new FuturePayment();
     pay.intent = "sale";
     CreditCard card = CreditCardTest.GetCreditCard();
     List<FundingInstrument> fundingInstruments = new List<FundingInstrument>();
     FundingInstrument fundingInstrument = new FundingInstrument();
     fundingInstrument.credit_card = card;
     fundingInstruments.Add(fundingInstrument);
     Payer payer = new Payer();
     payer.payment_method = "credit_card";
     payer.funding_instruments = fundingInstruments;
     List<Transaction> transactionList = new List<Transaction>();
     Transaction trans = new Transaction();
     trans.amount = AmountTest.GetAmount();
     transactionList.Add(trans);
     pay.transactions = transactionList;
     pay.payer = payer;
     Payment paymnt = pay.Create(TestingUtil.GetApiContext());
     return paymnt;
 }
Example #5
0
        public Payment CreatePayment(ICollection <IProduct> products)
        {
            var transaction = new PayPal.Api.Transaction()
            {
                amount = new PayPal.Api.Amount()
                {
                    currency = "USD",
                    total    = products.Sum(a => a.cost).ToString()
                },
                description = string.Join(", ", products.Select(a => a.name)),
                item_list   = new PayPal.Api.ItemList()
                {
                    items = products.Select(a => new PayPal.Api.Item()
                    {
                        name     = a.name,
                        currency = "USD",
                        price    = a.cost.ToString(),
                        quantity = products.Where(x => x.productid == a.productid).Count().ToString(),
                        sku      = a.sku
                    }).ToList()
                }
            };
            var payment = new PayPal.Api.Payment()
            {
                intent       = "sale",
                transactions = new System.Collections.Generic.List <PayPal.Api.Transaction>()
                {
                    transaction
                },
                redirect_urls = new PayPal.Api.RedirectUrls()
                {
                    return_url = "/"
                }
            };

            return(PayPal.Api.Payment.Create(apiContext, payment));
        }
        public static Payment CreatePayment(APIContext apiContext, string redirectUrl, string returnUrl, PayPal.Api.Transaction transaction)
        {
            var payer = new Payer()
            {
                payment_method = "paypal"
            };

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

            transactionList.Add(transaction);

            Payment payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = new RedirectUrls()
                {
                    cancel_url = redirectUrl,
                    return_url = returnUrl
                }
            };

            return(payment.Create(apiContext));
        }
Example #7
0
        /// <summary>
        /// ตัดบัตรเครดิต
        /// </summary>
        /// <param name="payment">ข้อมูลบัตรเครดิตที่ต้องการดำเนินการ</param>
        public PaymentResult ChargeCreditCard(PaymentInformation paymentInfo)
        {
            var tokenCredential = new OAuthTokenCredential(_appConfig.PaypalClientId, _appConfig.PaypalClientSecret, new Dictionary<string, string>());
            var accessToken = tokenCredential.GetAccessToken();
            var config = new Dictionary<string, string>();
            config.Add("mode", "sandbox"); // HACK: Paypal mode ('live' or 'sandbox')
            var apiContext = new APIContext
            {
                Config = config,
                AccessToken = accessToken
            };

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

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

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

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);
            var result = PaymentResult.Unknow;
            return Enum.TryParse<PaymentResult>(createdPayment.state, out result) ? result : PaymentResult.Unknow;
        }
Example #8
0
        public Transaction Transaction(Order order)
        {
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = "USD",
                    details = new Details()
                    {
                        shipping = "0",
                        subtotal = ConvertCurrencyToString(order.Total)
                    }
                },
                description = "This is the payment transaction description.",
                item_list = new ItemList()
                {
                    items = new List<Item>(),
                    shipping_address = new ShippingAddress
                    {
                        city = order.City,
                        country_code = order.CountryCode,
                        line1 = order.Address,
                        postal_code = order.Zip,
                        state = order.State,
                        recipient_name = $"{order.FirstName} {order.LastName}"
                    }
                },
                invoice_number = Convert.ToString(order.ID)
            };

            foreach (var nextOrderDetail in order.OrderDetails)
            {
                var orderDetailItemDetails =
                    _repositoryManager.InventoryRepository.GetByID(nextOrderDetail.InventoryItemID);
                transaction.item_list.items.Add(new Item()
                {
                    name = orderDetailItemDetails.itemName,
                    currency = "USD",
                    price = ConvertCurrencyToString(orderDetailItemDetails.price),
                    quantity = nextOrderDetail.Quantity.ToString(),
                    sku = orderDetailItemDetails.ID.ToString()
                });
            }

            //apply tax if in texas
            if (order.State == "TX")
            {
                transaction.amount.details.tax = ConvertCurrencyToString(order.Total * (decimal).085);
                transaction.amount.total = ConvertCurrencyToString(order.Total * (decimal)1.085);
            }
            else
            {
                transaction.amount.details.tax = "0";
                transaction.amount.total = ConvertCurrencyToString(order.Total);
            }

            return transaction;
        }
Example #9
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());
        }
Example #10
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 #11
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 #12
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");
        }
Example #13
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 #14
0
        public ActionResult RequestTransaction(string submit)
        {
            switch (submit)
            {
            case "Checkout":
                if (!(User.IsInRole(AppSettings.Roles.PURCHASINGAGENT) || User.IsInRole(AppSettings.Roles.CONGRESS)))
                {
                    return(new HttpNotFoundResult());
                }
                long cartId = getCartId();

                List <Transaction> trans;
                SessionSaver.Load.transactions(Session, out trans);
                paypal.ItemList paypalItems = new paypal.ItemList();
                paypalItems.items = new List <PayPal.Api.Item>();
                decimal sum = 0;
                for (int i = 0; i < trans.Count; i++)
                {
                    trans[i].cartId    = cartId;
                    trans[i].unitPrice = trans[i].Product.price;
                    sum += (trans[i].unitPrice * trans[i].quantity);
                    paypalItems.items.Add(new PayPal.Api.Item()
                    {
                        name     = trans[i].Product.name,
                        currency = "USD",
                        price    = trans[i].unitPrice.ToString("0.00"),
                        tax      = "0",
                        sku      = trans[i].productId.ToString(),
                        quantity = trans[i].quantity.ToString()
                    });
                }

                paypal.Transaction transaction = new PayPal.Api.Transaction()
                {
                    description    = "User added description",
                    invoice_number = cartId.ToString(),
                    amount         = new paypal.Amount()
                    {
                        currency = "USD",
                        total    = sum.ToString("0.00"),
                        details  = new paypal.Details()
                        {
                            tax      = "0",
                            shipping = "0",
                            subtotal = sum.ToString("0.00")
                        }
                    },
                    item_list = paypalItems
                };

                paypal.APIContext apiContext = PayPalHelper.GetAPIContext();
                try
                {
                    string payerId = Request.Params["PayerID"];

                    if (string.IsNullOrEmpty(payerId))
                    {
                        string baseURI        = Request.Url.Scheme + "://" + Request.Url.Authority;
                        var    guid           = Convert.ToString((new Random()).Next(100000));
                        var    createdPayment = PayPalHelper.CreatePayment(apiContext, baseURI + Url.Action("RequestTransaction", "Transaction") + "?guid=" + guid, baseURI + Url.Action("Completed", "Transaction"), transaction);
                        var    links          = createdPayment.links.GetEnumerator();

                        string paypalRedirectUrl = null;

                        while (links.MoveNext())
                        {
                            paypal.Links lnk = links.Current;
                            if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                            {
                                paypalRedirectUrl = lnk.href;
                            }
                        }
                        Session.Add(guid, createdPayment.id);

                        return(Redirect(paypalRedirectUrl));
                    }
                    else
                    {
                        var guid            = Request.Params["guid"];
                        var s               = Session[guid];
                        var executedPayment = PayPalHelper.ExecutePayment(apiContext, null, payerId, Session[guid] as string);

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

                return(View("Completed"));

            case "Request Checkout":
                using (FM_Datastore_Entities_EF db_manager = new FM_Datastore_Entities_EF())
                {
                    string email = User.Identity.Name;
                    User   usr   = db_manager.Users.FirstOrDefault(m => m.Email == email);
                    if (usr != null)
                    {
                        long userId        = usr.Id;
                        long cartIdRequest = getCartIdTransactionRequests();
                        List <Transaction> transactLst;
                        SessionSaver.Load.transactions(Session, out transactLst);
                        foreach (var item in transactLst)
                        {
                            db_manager.TransactionRequests.Add(new TransactionRequest()
                            {
                                cartId             = cartIdRequest,
                                productId          = item.productId,
                                quantity           = item.quantity,
                                unitPrice          = item.unitPrice,
                                requestedForUserId = userId
                            });
                        }

                        Session[AppSettings.SessionVariables.TRANSACTION] = null;
                        db_manager.Notifications.Add(new Notification()
                        {
                            Email      = usr.Email,
                            DivisionId = usr.Division,
                            AddressId  = usr.Address,
                            Address    = usr.Address1,
                            Division   = usr.Division1,
                            timeStamp  = DateTime.Now,
                            notifyType = AppSettings.Notify.pendingTransactionRequest,
                            notifyText = cartIdRequest.ToString()
                        });
                        db_manager.SaveChanges();
                    }
                }
                return(Redirect(Url.Action("RequestCompletion")));

            default:
                break;
            }
            return(new HttpNotFoundResult());
        }
        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/).
        }
        private List<Transaction> BuildTransactions(DexCMS.Tickets.Orders.Models.Order order)
        {
            var details = new Details { shipping = "0.00", tax = "0.00", subtotal = order.OrderTotal.ToString() };
            var amount = new Amount { currency = "USD", details = details, total = order.OrderTotal.ToString() };
            var itemList = new ItemList() { items = new List<Item>() };

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

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



            var transactions = new List<Transaction>
            {
                transaction
            };
            return transactions;
        }
        public ActionResult Create(order order, int?checkBilldingShipping)
        {
            if (ModelState.IsValid)
            {
                if (Session["ShoppingCart"] == null)
                {
                    return(RedirectToAction("UpdateCart", "Home"));
                }
                else
                {
                    try
                    {
                        var oldPriceOrder = 0.0;
                        if (order.ocid > 0)
                        {
                            var _order = db.orders.Where(t => t.ocid == order.ocid).FirstOrDefault();
                            oldPriceOrder          = _order.paid_amount.HasValue ? _order.paid_amount.Value : 0;
                            db.Entry(_order).State = EntityState.Detached;
                            db.SaveChanges();
                        }
                        order.d_companyname = string.IsNullOrEmpty(order.d_companyname) ? order.companyname : order.d_companyname;
                        order.d_fname       = string.IsNullOrEmpty(order.d_fname) ? order.fname : order.d_fname;
                        order.d_lname       = string.IsNullOrEmpty(order.d_lname) ? order.lname : order.d_lname;
                        order.d_email       = string.IsNullOrEmpty(order.d_email) ? order.email : order.d_email;
                        order.d_phone       = string.IsNullOrEmpty(order.d_phone) ? order.phone : order.d_phone;
                        order.d_addr1       = string.IsNullOrEmpty(order.d_addr1) ? order.addr1 : order.d_addr1;
                        if (checkBilldingShipping.HasValue && checkBilldingShipping.Value == 1)
                        {
                            order.b_companyname = string.IsNullOrEmpty(order.d_companyname) ? order.companyname : order.d_companyname;
                            order.b_fname       = string.IsNullOrEmpty(order.d_fname) ? order.fname : order.d_fname;
                            order.b_lname       = string.IsNullOrEmpty(order.d_lname) ? order.lname : order.d_lname;
                            order.b_email       = string.IsNullOrEmpty(order.d_email) ? order.email : order.d_email;
                            order.b_phone       = string.IsNullOrEmpty(order.d_phone) ? order.phone : order.d_phone;
                            order.b_addr1       = string.IsNullOrEmpty(order.d_addr1) ? order.addr1 : order.d_addr1;
                        }
                        order.status = "2";
                        if (order.payoption == "PayPal")
                        {
                            order.paid_status = 2;
                        }
                        if (order.payoption == "COD")
                        {
                            order.paid_status = 1;
                        }
                        ShoppingCart Cart = new ShoppingCart();
                        Cart = (ShoppingCart)Session["ShoppingCart"];
                        order.paid_amount = Cart.CartTotal + Cart.taxTotal;
                        String randomKey = Guid.NewGuid().ToString();
                        if (order.ocid == 0)
                        {
                            order.paid_key = randomKey;
                            db.orders.Add(order);
                            db.SaveChanges();
                        }
                        else
                        {
                            db.Entry(order).State = EntityState.Modified;
                            db.SaveChanges();
                        }

                        Cart.paid_key = order.paid_key;
                        WebApplication1.Models.AllLoggedUserInfo userFullInfo = (WebApplication1.Models.AllLoggedUserInfo)Session["LoggedAccount"];
                        if (userFullInfo != null)
                        {
                            var user = db.users.Find(userFullInfo.user.Id);
                            user.paidorder       = (user.paidorder ?? 0) + (decimal)Cart.CartTotal + (decimal)(order.feeshipping ?? 0) - (decimal)oldPriceOrder;
                            db.Entry(user).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                        double       cartAmount   = 0;
                        string       currencyName = "USD";
                        ordersetting ordersetting = db.ordersettings.Where(t => t.status == 1).FirstOrDefault();
                        if (ordersetting != null)
                        {
                            currencyName = ordersetting.name;
                        }

                        var itemList = new ItemList();
                        var items    = new List <Item>();

                        String paypalURL    = "";
                        var    paypayconfig = new PayPalConfiguration();
                        var    apiContext   = paypayconfig.GetAPIContext();

                        var _orderdetails = db.orderdetails.Where(t => t.ocid == order.ocid).ToList();
                        var listItems     = _orderdetails.Select(t => t.ocdetailcode);
                        var _items        = db.items.Where(t => listItems.Contains(t.ARTCODE)).ToList();
                        foreach (var item in _orderdetails)
                        {
                            if (item.stockId.HasValue && item.stockId.Value > 0)
                            {
                                var _item = _items.FirstOrDefault(t => t.ARTCODE == item.ocdetailcode);
                                if (_item != null)
                                {
                                    var _stock = db.stocks.Where(t => t.ARTNO == item.itemId && t.STOCKNO == item.stockId).FirstOrDefault();
                                    _stock.VOLUME         += item.ocdetailqty.Value;
                                    db.Entry(_stock).State = EntityState.Modified;
                                }
                            }
                        }
                        db.orderdetails.RemoveRange(_orderdetails);
                        var _listItems = Cart.cartItem.Select(t => t.Code);
                        var __items    = db.items.Where(t => _listItems.Contains(t.ARTCODE)).ToList();
                        foreach (var item in Cart.cartItem)
                        {
                            orderdetail od = new orderdetail();
                            od.ocid          = order.ocid;
                            od.ocdetailcode  = item.Code;
                            od.ocdetailname  = item.Name;
                            od.ocdetailprice = item.Price;
                            od.ocdetailqty   = item.Qty;
                            od.ocdetailgst   = item.Tax / item.Qty;
                            od.stockId       = item.StockId;
                            if (item.StockId > 0)
                            {
                                var _item = __items.FirstOrDefault(t => t.ARTCODE == od.ocdetailcode);
                                if (_item != null)
                                {
                                    var _stock = db.stocks.Where(t => t.ARTNO == _item.ARTNO && t.STOCKNO == item.StockId).FirstOrDefault();
                                    _stock.VOLUME         -= item.Qty;
                                    db.Entry(_stock).State = EntityState.Modified;
                                    od.itemId = _item.ARTNO;
                                }
                            }
                            db.orderdetails.Add(od);

                            var Item = new Item();
                            Item.name     = item.Code + " - " + item.Name;
                            Item.currency = currencyName;

                            Item.price    = (item.Price + (item.Tax / item.Qty)) + "";
                            Item.quantity = item.Qty + "";
                            items.Add(Item);
                        }
                        if (order.feeshipping.HasValue && order.feeshipping.Value > 0)
                        {
                            var Item = new Item();
                            Item.name     = "Fee Shipping";
                            Item.currency = currencyName;
                            Item.price    = order.feeshipping + "";
                            Item.quantity = "1";
                            items.Add(Item);
                        }
                        if (Cart.promotion != null)
                        {
                            if (Cart.promotion.TYPENO == 0)
                            {
                                var Item = new Item();
                                Item.name     = "Discount Promotion";
                                Item.currency = currencyName;
                                Item.price    = "-" + Cart.PromotionTotal + "";
                                Item.quantity = "1";
                                items.Add(Item);
                            }
                        }
                        cartAmount     = Cart.CartTotal + Cart.taxTotal + order.feeshipping ?? 0;
                        cartAmount     = Math.Round(cartAmount, 2);
                        itemList.items = items;
                        db.SaveChanges();
                        if (order.payoption == "PayPal")
                        {
                            var payer = new Payer()
                            {
                                payment_method = "paypal"
                            };
                            var redirUrls = new RedirectUrls()
                            {
                                cancel_url = UrlHelper.Root + "Checkout/PayPalCancel?" + UrlHelper.ToQueryString(new { paid_key = order.paid_key }),
                                return_url = UrlHelper.Root + "Checkout/PayPalSuccess?" + UrlHelper.ToQueryString(new { paid_key = order.paid_key })
                            };
                            var paypalAmount = new Amount()
                            {
                                currency = currencyName, total = cartAmount.ToString()
                            };

                            var transactionList = new List <PayPal.Api.Transaction>();
                            PayPal.Api.Transaction transaction = new PayPal.Api.Transaction();
                            transaction.amount    = paypalAmount;
                            transaction.item_list = itemList;
                            transactionList.Add(transaction);


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

                            try
                            {
                                var createdPayment = payment.Create(apiContext);
                                var links          = createdPayment.links.GetEnumerator();
                                while (links.MoveNext())
                                {
                                    var link = links.Current;
                                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                                    {
                                        paypalURL = link.href;
                                    }
                                }
                                return(Redirect(paypalURL));
                            }
                            catch (PaymentsException ex)
                            {
                                paypalURL = "ERROR: " + ex.Response;
                            }
                        }
                        else
                        {
                            SendTemplateEmail(order.d_email, order.d_email, "", "Order Success #" + order.ocid + "" + DateTime.Now.Day, 1, Cart, order);
                            SendTemplateEmail(order.d_email, order.d_email, "", "Order Success #" + order.ocid + "" + DateTime.Now.Day, 3, Cart, order);
                            return(RedirectToAction("Thankyou"));
                        }
                    }
                    catch (DbEntityValidationException e)
                    {
                        foreach (var eve in e.EntityValidationErrors)
                        {
                            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                              eve.Entry.Entity.GetType().Name, eve.Entry.State);
                            foreach (var ve in eve.ValidationErrors)
                            {
                                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                  ve.PropertyName, ve.ErrorMessage);
                            }
                        }
                    }
                }
            }
            return(RedirectToAction("Create"));
        }
        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");
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

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

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

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

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

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

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

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #20
0
        private static Transaction GetCardTransactionDetails(ItemList itemList, double amount)
        {
            Details details = new Details();
            details.shipping = "0";
            details.subtotal = amount.ToString();
            details.tax = "0";

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

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

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

            Guid uniqueGuid = Guid.NewGuid();

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

            return tran;
        }