Item details.

See PayPal Developer documentation for more information.

Inheritance: PayPalSerializableObject
Beispiel #1
0
        public ActionResult CreditCardInfo(Models.CreditCard currentCard)
        {
            Session["ShopSessionID1"] = KeyGenerator.GetUniqueKey(20);

            string sessionID1 = Session["ShopSessionID1"].ToString();

            Session["ShopSessionID2"] = BCrypt.HashSession(sessionID1, BCrypt.GenerateSalt());

            if (string.IsNullOrEmpty(currentCard.creditCardNo))
            {
                ModelState.AddModelError("creditCardNo", "Credit card number is required.");
            }
            if (string.IsNullOrEmpty(currentCard.cvv2))
            {
                ModelState.AddModelError("creditCardNo", "CVV is required.");
            }
            if (string.IsNullOrEmpty(currentCard.first_name))
            {
                ModelState.AddModelError("creditCardNo", "First Name is required.");
            }
            if (string.IsNullOrEmpty(currentCard.last_name))
            {
                ModelState.AddModelError("creditCardNo", "Last Name is required.");
            }
            if (ModelState.IsValid)
            {
                //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

                string price = string.Empty;
                price = Convert.ToString(Session["price"]);

                string beansName = string.Empty;
                price = Convert.ToString(Session["beansName"]);

                string beansAmount = string.Empty;
                price = Convert.ToString(Session["beansAmount"]);

                PayPal.Api.Item item = new PayPal.Api.Item();
                item.name     = beansName + " (" + beansAmount + ") Beans";
                item.currency = "SGD";
                item.price    = price;
                item.quantity = "1";
                item.sku      = KeyGenerator.GetUniqueKey(20);

                //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 <PayPal.Api.Item> itms = new List <PayPal.Api.Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                //Address for the payment
                Address billingAddress = new Address
                {
                    city         = currentCard.billing_address.city,
                    country_code = "SG",
                    line1        = currentCard.billing_address.line1,
                    line2        = currentCard.billing_address.line2,
                    postal_code  = currentCard.billing_address.postal_code,
                    state        = currentCard.billing_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
                PayPal.Api.CreditCard crdtCard = new PayPal.Api.CreditCard
                {
                    billing_address = billingAddress,
                    cvv2            = currentCard.cvv2,         //card cvv2 number
                    expire_month    = currentCard.expire_month, //card expire date
                    expire_year     = currentCard.expire_year,  //card expire year
                    first_name      = currentCard.first_name,
                    last_name       = currentCard.last_name,
                    number          = currentCard.creditCardNo //enter your credit card number here
                };
                if (Regex.IsMatch(currentCard.creditCardNo, "^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$"))
                {
                    crdtCard.type = "mastercard";
                }

                if (Regex.IsMatch(currentCard.creditCardNo, "^4[0-9]{12}(?:[0-9]{3})?$"))
                {
                    crdtCard.type = "visa";
                }

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

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

                // Now make a transaction object and assign the Amount object
                Transaction tran = new Transaction();


                tran.amount         = amnt;
                tran.description    = "Purchase of " + beansAmount + " beans. Beans will be added after successful purchase.";
                tran.item_list      = itemList;
                tran.invoice_number = KeyGenerator.GetUniqueKey(20);

                // 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
                {
                    funding_instruments = fundingInstrumentList,
                    payment_method      = "credit_card"
                };

                // finally create the payment object and assign the payer object & transaction list to it
                Payment pymnt = new Payment
                {
                    intent       = "sale",
                    payer        = payr,
                    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 = Models.Configuration.GetAPIContext();

                    //Create is a Payment class function which actually sends the payment details
                    //to the paypal API for the payment. The function is passed with the ApiContext
                    //which we received above.

                    Payment createdPayment = pymnt.Create(apiContext);

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

                    if (createdPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
                catch (PayPal.PayPalException ex)
                {
                    Debug.WriteLine(ex);
                    return(View("FailureView"));
                }

                return(View("SuccessView"));
            }
            else
            {
                return(View(currentCard));
            }
        }
        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/).
        }