[DEPRECATED] Represents a credit card to fund a payment. Use Payment Card instead.

See PayPal Developer documentation for more information.

Inheritance: PayPalRelationalObject
Exemplo n.º 1
11
        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();
        }
        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 resource representing a credit card that can be used to fund a payment.
            var card = new CreditCard()
            {
                expire_month = 11,
                expire_year = 2018,
                number = "4877274905927862",
                type = "visa",
                cvv2 = "874"
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Create credit card", card);
            //--------------------
            #endregion

            // Creates the credit card as a resource in the PayPal vault. The response contains an 'id' that you can use to refer to it in the future payments.
            var createdCard = card.Create(apiContext);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(createdCard);
            //--------------------
            #endregion
        }
        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();

            // Create a new credit card resource that will be deleted for demonstration purposes.
            var credtCard = new CreditCard()
            {
                expire_month = 11,
                expire_year = 2018,
                number = "4877274905927862",
                type = "visa"
            };

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

            // Creates the credit card as a resource in the PayPal vault. The response contains an 'id' that you can use to refer to it in future payments.
            var createdCreditCard = credtCard.Create(apiContext);
            var createdCardId = createdCreditCard.id;

            // ^ Ignore workflow code segment
            #region Track Workflow
            flow.RecordResponse(createdCreditCard);
            this.flow.AddNewRequest("Get stored credit card details", description: "ID: " + createdCardId);
            #endregion

            // Retrieve the credit card information for the new created resource.
            var card = CreditCard.Get(apiContext, createdCardId);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordResponse(card);
            this.flow.AddNewRequest("Delete credit card", description: "ID: " + card.id);
            #endregion

            // Delete the credit card
            card.Delete(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            this.flow.RecordActionSuccess("Credit card deleted successfully");
            #endregion

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Exemplo n.º 4
0
        public ActionResult Create(CreditCard creditCard)
        {
            if (ModelState.IsValid)
            {
                var apiContext = Common.GetApiContext();

                creditCard.external_customer_id = customerId;
                creditCard.type = Common.GetCardType(creditCard.number);
                creditCard.Create(apiContext);

                TempData["success"] = "Credit card stored successfully";

                return RedirectToAction("Index");
            }

            AddPaymentDropdowns();
            return View(creditCard);
        }
        public PayPal<CreditCard> Create(CreditCard creditCard)
        {
            PayPal<CreditCard> paypal = new PayPal<CreditCard>();

            try
            {
                creditCard = new CreditCard()
                {
                    number = "4032035304110067",
                    type = "visa",
                    expire_month = 11,
                    expire_year = 2020,
                    cvv2 = "4960",
                    first_name = "Rafael",
                    last_name = "Aguiar",
                    billing_address = new Address()
                    {
                        phone = "1231231",
                        line1 = "1 First Street",
                        city = "Saratoga",
                        state = "CA",
                        postal_code = "95070",
                        country_code = "US"
                    }
                };

                paypal.Object = creditCard;

                return paypal;
            }
            catch (PayPal.HttpException he)
            {
                if (he.Response.Contains("INVALID_RESOURCE_ID"))
                {
                    paypal.Validations.Add("paymentCode", "Invalid ID");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return paypal;
        }
Exemplo n.º 6
0
        public Response <PayPal.Api.CreditCard> CreateCreditCard(PayPal.Api.CreditCard creditCard)
        {
            Response <CreditCard> response           = null;
            CreditCardBusiness    creditCardBusiness = null;
            PayPal <CreditCard>   paypal             = null;

            try
            {
                creditCardBusiness = new CreditCardBusiness();
                paypal             = creditCardBusiness.Create(creditCard);
                response           = new Response <CreditCard>(creditCard, ResponseStatus.Success, "Success");
            }
            catch (Exception ex)
            {
                response = new Response <CreditCard>(null, ResponseStatus.Error, ex.Message);
            }

            return(response);
        }
        public CreditCard GetFake()
        {
            CreditCard creditCard = new CreditCard()
            {
                number = "4032035304110067",
                type = "visa",
                expire_month = 11,
                expire_year = 2020,
                cvv2 = "496",
                first_name = "Rafael",
                last_name = "Aguiar",
                billing_address = new Address()
                {
                    phone = "1231231",
                    line1 = "1 First Street",
                    city = "Saratoga",
                    state = "CA",
                    postal_code = "95070",
                    country_code = "US"
                }
            };

            return creditCard;
        }
Exemplo n.º 8
0
        public ActionResult Edit(string id, CreditCard creditCard)
        {
            if (ModelState.IsValid)
            {
                var apiContext = Common.GetApiContext();

                creditCard.type = Common.GetCardType(creditCard.number);
                var existing = CreditCard.Get(apiContext, id);
                if (existing != null)
                {
                    var patchRequest = new PatchRequest();

                    // determine what's changed between the existing card
                    // and the posted values
                    if (creditCard.expire_month != existing.expire_month)
                    {
                        patchRequest.Add(new Patch { op = "replace", path = "/expire_month", value = creditCard.expire_month });
                    }

                    if (creditCard.expire_year != existing.expire_year)
                    {
                        patchRequest.Add(new Patch { op = "replace", path = "/expire_year", value = creditCard.expire_year });
                    }

                    if (!string.IsNullOrEmpty(creditCard.first_name) && creditCard.first_name != existing.first_name)
                    {
                        patchRequest.Add(new Patch { op = "replace", path = "/first_name", value = creditCard.first_name });
                    }

                    if (!string.IsNullOrEmpty(creditCard.last_name) && creditCard.last_name != existing.last_name)
                    {
                        patchRequest.Add(new Patch { op = "replace", path = "/last_name", value = creditCard.last_name });
                    }

                    if (patchRequest.Count > 0)
                    {
                        existing.Update(apiContext, patchRequest);

                        TempData["success"] = "Stored Card updated.";

                        return RedirectToAction("Details", new { id });
                    }
                    else
                    {
                        TempData["info"] = "Nothing to update";
                    }
                }
            }
            else
            {
                TempData["info"] = "ModelState is invalid";
            }

            AddPaymentDropdowns();
            return View(creditCard);
        }
 public CreditCard Create(CreditCard creditCard)
 {
     return CreditCard.Create(context, creditCard);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a new Credit Card Resource (aka Tokenize).
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="creditCard">CreditCard object to be used to create the PayPal resource.</param>
        /// <returns>CreditCard</returns>
        public static CreditCard Create(APIContext apiContext, CreditCard creditCard)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);

            // Configure and send the request
            var resourcePath = "v1/vault/credit-cards";
            return PayPalResource.ConfigureAndExecute<CreditCard>(apiContext, HttpMethod.POST, resourcePath, creditCard.ConvertToJson());
        }
Exemplo n.º 11
0
        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");
        }
Exemplo n.º 12
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));
            }
        }
Exemplo n.º 13
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;
        }
Exemplo n.º 15
0
        public ActionResult PaymentWithCreditCard([Bind(Include = "first_name,last_name,billing_address,number,expire_month,expire_year,cvv2")] PayPal.Api.CreditCard creditCard, FormCollection fc)
        {
            creditCard.type = fc["type"];

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

            //Get cart items and each to itms list below
            var cart = db.Carts.Where(m => m.MemberID == MyHelpers.LoggedInMember.MemberID && m.Status.Name.ToLower() == "active");

            if (cart.Count() > 0)
            {
                foreach (Cart_Items ci in cart.First().Cart_Items)
                {
                    ////create an item for which you are taking payment
                    Item item = new Item();
                    item.name     = ci.Catalog_Items.Name;
                    item.currency = "USD";
                    item.price    = String.Format("{0:0.00}", (decimal)ci.Catalog_Items.Price);
                    item.quantity = "1";
                    item.sku      = "sku";
                    item.tax      = "0";

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

                // Specify details of your payment amount.
                string subtotal = cart.First().Cart_Items.Sum(m => m.Catalog_Items.Price).ToString();

                Details details = new Details();
                details.shipping = "0";
                details.subtotal = String.Format("{0:0.00}", Convert.ToDecimal(subtotal));
                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   = String.Format("{0:0.00}", Convert.ToDecimal(subtotal));
                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;

                //generate Invoice Number
                DateTime _now   = DateTime.Now;
                string   invNbr = MyHelpers.LoggedInMember.MemberID.ToString() + _now.Year.ToString() + _now.Month.ToString() + _now.Day.ToString() + _now.Minute.ToString() + _now.Second.ToString();

                tran.invoice_number = invNbr;

                // 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 = creditCard;

                // 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")
                    {
                        ViewBag.message = "Card was not approved: " + createdPayment.state.ToString();
                        return(View("Index", creditCard));
                    }
                    else
                    {
                        //SUCCESSFUL
                        //create purchase record for member for each cart item. Then clear cart or mark inactive
                        try
                        {
                            foreach (Cart_Items ci in cart.First().Cart_Items)
                            {
                                Purchase purch = new Purchase();
                                purch.MemberID       = MyHelpers.LoggedInMember.MemberID;
                                purch.Price          = ci.Catalog_Items.Price;
                                purch.Catalog_ItemID = ci.Catalog_ItemID;
                                purch.CreateDate     = DateTime.Now;

                                db.Purchases.Add(purch);
                                db.SaveChanges();
                            }
                            //clear cart
                            db.Carts.First().StatusID = db.Status.Where(m => m.Name.ToLower() == "fulfilled").First().StatusID;
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            //could not complete purchase/clear cart operation
                            ViewBag.message = "Could not complete purchase/clear cart operation. " + ex.Message;
                            return(View("Index", creditCard));
                        }

                        ViewBag.message = createdPayment.state.ToString().ToUpper();
                        return(View("SuccessView"));
                    }
                }
                catch (PayPal.PayPalException ex)
                {
                    Logger.Log("Error: " + ex.Message);
                    ViewBag.error = JsonConvert.DeserializeObject <PayPal.Api.Error>(((PayPal.ConnectionException)ex).Response);

                    ViewBag.cnnerror = ((PayPal.ConnectionException)ex).ToString();

                    return(View("Index", creditCard));
                }
            }
            else
            {
                //cart is empty
                ViewBag.message = "Cart is empty";
                return(View("Index", creditCard));
            }
        }
Exemplo n.º 16
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");
        }
Exemplo n.º 17
0
        private static CreditCard GetPaymentCardDetails()
        {
            CreditCard creditCard = new CreditCard();
            creditCard.billing_address = GetCardPaymentAddress();
            creditCard.cvv2 = "123";
            creditCard.expire_month = 10;
            creditCard.expire_year = 2020;
            creditCard.first_name = "Joe";
            creditCard.last_name = "Smith";
            creditCard.number = "4137354109223726";
            creditCard.type = "visa";

            return creditCard;
        }