Base Address object used as billing address in a payment or extended for Shipping Address.

See PayPal Developer documentation for more information.

Inheritance: BaseAddress
Beispiel #1
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");
        }
Beispiel #2
0
        public IActionResult PaymentWithCreditCard([FromBody] PaymentViewModelForCreditCard paymentViewModel)
        {
            Payment createdPayment = new Payment();

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

                //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
                //loop through each item or produce
                Item item = new Item();
                foreach (var item1 in paymentViewModel.items)
                {
                    item.currency    = "INR";
                    item.name        = item1.Name;
                    item.description = item1.Description;
                    item.price       = item1.Price.ToString();
                    item.quantity    = item1.Quantity.ToString();
                    item.sku         = "sku";

                    itms.Add(item);
                }


                //Item item = new Item();
                //item.name = "Item Name";
                //item.currency = "USD";
                //item.price = "1";
                //item.quantity = "5";
                //item.sku = "sku";



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

                //Address for the payment
                PayPal.Api.Address billingAddress = new PayPal.Api.Address();
                billingAddress.city         = paymentViewModel.shipping_Address.City;
                billingAddress.country_code = paymentViewModel.shipping_Address.Country_Code;
                billingAddress.line1        = paymentViewModel.shipping_Address.Line1;
                billingAddress.postal_code  = paymentViewModel.shipping_Address.postal_code;
                billingAddress.state        = paymentViewModel.shipping_Address.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            = paymentViewModel.creditCardDetails.CVV;              //"272";  //card cvv2 number
                crdtCard.expire_month    = paymentViewModel.creditCardDetails.Expire_Month;     //09; //card expire date
                crdtCard.expire_year     = paymentViewModel.creditCardDetails.Expire_Year;      //2022; //card expire year
                crdtCard.first_name      = paymentViewModel.creditCardDetails.FirstName;        //"John";
                crdtCard.last_name       = paymentViewModel.creditCardDetails.LastName;         //"Cena";
                crdtCard.number          = paymentViewModel.creditCardDetails.CreditCardNumber; //"4229047773305741"; //enter your credit card number here
                crdtCard.type            = paymentViewModel.creditCardDetails.CreditCardType;   // "visa"; //credit card type here paypal allows 4 types

                // Specify details of your payment amount.
                Details details = new Details();
                details.shipping = paymentViewModel.ShippingCharge.ToString();
                details.subtotal = paymentViewModel.SubTotal.ToString();
                details.tax      = paymentViewModel.Tax.ToString();

                // Specify your total payment amount and assign the details object
                Amount amnt = new Amount();
                amnt.currency = paymentViewModel.Currency;
                // Total = shipping tax + subtotal.
                amnt.total   = Convert.ToString(paymentViewModel.SubTotal + paymentViewModel.ShippingCharge + paymentViewModel.Tax);;
                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

                    // 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.

                    createdPayment = pymnt.Create(apiContext);

                    //if the createdPayment.state is "approved" it means the payment was successful else not

                    //if (createdPayment.state.ToLower() != "approved")
                    //{
                    //    return createdPayment;
                    //}
                }
                catch (PayPal.PayPalException e)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (createdPayment.state == "approved")
            {
                return(Ok("payment was successful"));
            }
            else
            {
                return(Ok("payment was not successful"));
            }
        }
        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");
        }
Beispiel #4
0
        public ActionResult PaymentWithCreditCard(Bids bid)
        {
            ApplicationUser currentUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());

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

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

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

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

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

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

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

            Payer payer = new Payer();
            payer.funding_instruments = fundingInstrumentList;
            payer.payment_method = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment payment = new Payment();
            payment.intent = "sale";
            payment.payer = payer;
            payment.transactions = transactions;

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

                if (createdPayment.state.ToLower() != "approved")
                {
                    return View("FailureView");
                }
            } catch (PayPal.PayPalException ex)
            {
                Logger.Log("Error: " + ex.Message);
                return View("FailureView");
            }

            return View("SuccessView");
        }
        private Payment CreatePayment(IOrder order, string paymentType, string redirectUrl, CardDetails cardDetails)
        {
            //Create items for which you are taking payment
            var items = order.OrderDetails.GetList().Select(product => new Item
            {
                name = product.Name,
                currency = "GBP",
                price = product.Price.ToString(CultureInfo.InvariantCulture),
                quantity = product.Quantity.ToString(CultureInfo.InvariantCulture),
                sku = product.Category
            }).ToList();
            // Create ItemList object
            var itemList = new ItemList { items = items };

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

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

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

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

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

                };

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

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

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

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

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

            return payment;
        }
        public static string ProcessSale(string firstName, string lastName, string billAddress1, string billAddress2, string billCity, string billState, string billCountry, string billZip,
                                         List <SaleProduct> CartItems, string CardNo, string cvv2, int expYear, int expMonth, decimal shippingCharge)
        {
            string  PaymentID  = "";
            decimal totalPrice = 0M;
            Dictionary <string, string> payPalConfig = new Dictionary <string, string>();

            payPalConfig.Add("mode", mode);

            try
            {
                string     AccessToken = GetPayPalAccessToken();
                APIContext AC          = new APIContext(AccessToken);
                AC.Config = payPalConfig;

                Payee pe = new Payee();
                pe.merchant_id = "Q4A2XY37JY7VW";

                PayPal.Api.Address billingAddress = new PayPal.Api.Address();
                billingAddress.city  = billCity;
                billingAddress.line1 = billAddress1;
                if (!string.IsNullOrWhiteSpace(billAddress2))
                {
                    billingAddress.line2 = billAddress2;
                }
                billingAddress.state        = billState;
                billingAddress.country_code = billCountry;
                billingAddress.postal_code  = billZip;

                CreditCard cc = new CreditCard();
                cc.billing_address = billingAddress;
                cc.number          = CardNo;
                cc.cvv2            = cvv2;
                cc.type            = CCUtils.CreditCardType(CardNo).ToLower();
                cc.first_name      = firstName;
                cc.last_name       = lastName;
                cc.expire_month    = expMonth;
                cc.expire_year     = expYear;

                FundingInstrument fi = new FundingInstrument();
                fi.credit_card = cc;

                Payer py = new Payer();
                py.payment_method      = "credit_card";
                py.funding_instruments = new List <FundingInstrument>()
                {
                    fi
                };

                Transaction t = new Transaction();
                t.amount = new Amount();

                foreach (SaleProduct item in CartItems)
                {
                    totalPrice = Math.Round(totalPrice + (item.UnitPrice * item.Quantity), 2, MidpointRounding.AwayFromZero);
                }

                t.amount.currency         = "USD";
                t.amount.details          = new Details();
                t.amount.details.subtotal = totalPrice.ToString("0.00");
                t.amount.details.tax      = "0.00";
                t.amount.details.shipping = shippingCharge.ToString("0.00");
                t.amount.total            = Math.Round(totalPrice + shippingCharge, 2, MidpointRounding.AwayFromZero).ToString("0.00");
                t.description             = "Chimaera Conspiracy Store Purchase";

                Payment p = new Payment();
                p.intent       = "sale";
                p.transactions = new List <Transaction>()
                {
                    t
                };
                p.payer = py;

                Payment pResp = p.Create(AC);

                if (pResp.state.Equals("approved", StringComparison.OrdinalIgnoreCase))
                {
                    PaymentID = pResp.id;
                }
            }
            catch (PayPal.PayPalException ppex)
            {
                LoggingUtil.InsertError(ppex);
            }
            catch (WebException ex)
            {
                LoggingUtil.InsertError(ex);
                WebResponse wr = ex.Response;
                if (wr != null)
                {
                    StreamReader sr = new StreamReader(wr.GetResponseStream());
                    string       ss = sr.ReadToEnd();
                    throw new Exception(ss);
                }
            }
            catch (Exception ex)
            {
                LoggingUtil.InsertError(ex);
            }

            return(PaymentID);
        }