private RedirectUrls CreateRedirectUrls()
 {
     RedirectUrls urls = new RedirectUrls();
     urls.cancel_url = "http://ebay.com/";
     urls.return_url = "http://paypal.com/";
     return urls;
 }
        public Payment CreatePaymentPaypal(string orderAmount, string orderDescription, string paymentMethod, string returnUrl, string cancelUrl)
        {
            Payment pymnt = null;

            //Create item
            ItemList ItemList = new ItemList();
            ItemList.items = new List<Item>();
            ItemList.items.Add(new Item { name = "A", currency = "USD", price = "10", quantity = "1", sku = "1" });
            ItemList.items.Add(new Item { name = "B", currency = "USD", price = "20", quantity = "2", sku = "1" });
            ItemList.items.Add(new Item { name = "C", currency = "USD", price = "50", quantity = "3", sku = "1" });
            ItemList.items.Add(new Item { name = "D", currency = "USD", price = "100", quantity = "4", sku = "1" });

            Details amountDetails = new Details();
            amountDetails.shipping = "0";
            amountDetails.tax = "0";
            amountDetails.subtotal = orderAmount;

            Amount amount = new Amount();
            amount.currency = "USD";
            int total = Convert.ToInt32(amountDetails.tax) + Convert.ToInt32(amountDetails.shipping) + Convert.ToInt32(orderAmount);
            amount.total = total.ToString();
            amount.details = amountDetails;

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.item_list = ItemList;
            transaction.amount = amount;
            transaction.description = orderDescription;
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            Payer payer = new Payer();
            payer.payment_method = paymentMethod;

            Payment pyment = new Payment();
            pyment.intent = "sale";
            pyment.payer = payer;
            pyment.transactions = transactions;
            pyment.redirect_urls = redirectUrls;

            pymnt = pyment.Create(Api);
            return pymnt;
        }
        public Payment CreatePayment(string email, PaymentMethod payMethod, string orderAmount, string orderDescription, string returnUrl, string cancelUrl)
        {
            Payment pay = null;

            Details amountDetails = new Details();
            amountDetails.shipping = "2";
            amountDetails.tax = "1";
            amountDetails.subtotal = orderAmount;

            Amount amount = new Amount();
            amount.currency = "USD";
            int total = Convert.ToInt32(amountDetails.tax) + Convert.ToInt32(amountDetails.shipping) + Convert.ToInt32(orderAmount);
            amount.total = total.ToString();
            amount.details = amountDetails;

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.description = orderDescription;
            List<Transaction> transactions = new List<Transaction>();
            transactions.Add(transaction);

            Payer payr = new Payer();
            payr.payment_method = payMethod.ToString();

            Payment paymnt = new Payment();
            paymnt.intent = "sale";
            paymnt.payer = payr;
            paymnt.transactions = transactions;
            paymnt.redirect_urls = redirectUrls;

            pay = paymnt.Create(Api);
            return pay;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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.
                    APIContext apiContext = new APIContext(accessToken);
                    // Use this variant if you want to pass in a request id
                    // that is meaningful in your application, ideally
                    // a order id.
                    // String requestId = Long.toString(System.nanoTime();
                    // APIContext apiContext = new APIContext(accessToken, requestId ));
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext,
                            pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. Transaction is created with
                // a `Payee` and `Amount` types
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as 'sale'
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // ###AccessToken
                    // Retrieve the access token from
                    // OAuthTokenCredential by passing in
                    // ClientID and ClientSecret
                    // It is not mandatory to generate Access Token on a per call basis.
                    // Typically the access token can be generated once and
                    // reused within the expiry window
                    string accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();

                    // ### 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.
                    APIContext apiContext = new APIContext(accessToken);
                    // Use this variant if you want to pass in a request id
                    // that is meaningful in your application, ideally
                    // a order id.
                    // String requestId = Long.toString(System.nanoTime();
                    // APIContext apiContext = new APIContext(accessToken, requestId ));

                    // Create a payment by posting to the APIService
                    // using a valid AccessToken
                    // The return object contains the status;
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ### 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..
            APIContext apiContext = Configuration.GetAPIContext();

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            {
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                {
                    pymnt.id = (string)Session[Request.Params["guid"]];

                }
                try
                {
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }

            // ## Creating Payment
            else
            {
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name = "Item Name";
                item.currency = "USD";
                item.price = "15";
                item.quantity = "5";
                item.sku = "sku";

                List<Item> itms = new List<Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                tran.item_list = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                {
                    // Create a payment using a valid APIContext
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                }
                catch (PayPal.Exception.PayPalException ex)
                {
                    CurrContext.Items.Add("Error", ex.Message);
                }
            }
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");

        }
        public PayPal.Api.Payments.Payment CreatePayment(IOrder order, string returnUrl, string cancelUrl)
        {
            Amount amount = new Amount();
            amount.currency = "AUD";
            amount.total = order.Total.ToString();
            amount.details = new Details();

            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.return_url = returnUrl;
            redirectUrls.cancel_url = cancelUrl;

            Transaction transaction = new Transaction();
            transaction.amount = amount;
            transaction.item_list = new ItemList() { items = new List<Item>() };

            foreach (var orderItem in order.Items)
            {
                Item item = new Item()
                {
                    name = orderItem.Product.Title,
                    price = orderItem.Product.Cost.ToString(),
                    quantity = orderItem.Quantity.ToString(),
                    currency = "AUD"
                };

                transaction.item_list.items.Add(item);
            }

            List<Transaction> transactions = new List<Transaction>() { transaction };

            Payer payer = new Payer() { payment_method = "paypal" };

            PayPal.Api.Payments.Payment pyment = new PayPal.Api.Payments.Payment();
            pyment.intent = "sale";
            pyment.payer = payer;
            pyment.transactions = transactions;
            pyment.redirect_urls = redirectUrls;

            return pyment.Create(this.GetApiContext());
        }
Exemple #7
0
        public PaymentResponse ProcessPaymentForCart(Cart cart, string cancelUrl, string returnUrl)
        {
            var apiContext = ApiContextFactory.Create();

            var paypalItems = new ItemList
            {
                items = cart.GetItems().OfType<ProductCartItem>().Select(li => new Item
                {
                    name = li.Title,
                    price = li.PriceWithoutTax.ToString("N"),
                    currency = _config.Currency,
                    quantity = li.Quantity.ToString(),
                    sku = li.Id.ToString()
                }).ToList()
            };

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            var payer = new Payer { payment_method = "paypal" };

            //// # Redirect URLS
            var redirUrls = new RedirectUrls
            {
                cancel_url = cancelUrl,
                return_url = returnUrl
            };

            // ###Details
            // Let's you specify details of a payment amount.
            var details = new Details
            {
                tax = cart.CalculateTotalTax().TaxAmount.ToString("N"),
                shipping = cart.ShippingCost.Cost.ToString("N"),
                subtotal = cart.CalculateSubTotalWithoutTax().ToString("N"),
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount
            {
                currency = _config.Currency,
                total = cart.CalculateGrandTotal().ToString("N"), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            var transactionList = new List<Transaction>
            {
                new Transaction
                {
                    description = "UNIXMO Online Store",
                    amount = amount,
                    item_list = paypalItems
                }
            };

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            var payment = new Payment
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };

            var myResponse = payment.Create(apiContext);

            if (myResponse == null || myResponse.links == null)
            {
                return PaymentResponse.Failed();
            }

            var approvalUrl = myResponse.links.FirstOrDefault(lnk => lnk.rel.Equals("approval_url", StringComparison.OrdinalIgnoreCase));
            if (approvalUrl == null)
                return PaymentResponse.Failed();

            cart.SetPaymentTransaction(myResponse.id);

            return PaymentResponse.Completed(approvalUrl.href, myResponse.id);
        }
        private Payment CreatePaymentCreditCard()
        {
            //Create Payment With Credit Card
            try
            {
                Transaction tran = new Transaction();

                //Redirect Url
                RedirectUrls red = new RedirectUrls();
                red.return_url = "";
                red.cancel_url = "";

                //Detail
                Details det = new Details();
                det.shipping = "0";
                det.tax = "0";
                det.fee = "0";

                //Address
                Address billingAddress = new Address();
                billingAddress.city = "Johnstown";
                billingAddress.country_code = "US";
                billingAddress.line1 = "52 N Main ST";
                billingAddress.postal_code = "43210";
                billingAddress.state = "OH";

                //CreditCard
                CreditCard creditCard = new CreditCard();
                creditCard.number = "4417119669820331";
                creditCard.type = "visa";
                creditCard.expire_month = 11;
                creditCard.expire_year = 2018;
                creditCard.cvv2 = "111";
                creditCard.first_name = "TestF";
                creditCard.last_name = "TestL";
                creditCard.billing_address = billingAddress;

                //Create item
                ItemList ItemList = new ItemList();
                ItemList.items = new List<Item>();
                ItemList.items.Add(new Item { name = "A", currency = "USD", price = "10", quantity = "1", sku = "1" });
                ItemList.items.Add(new Item { name = "B", currency = "USD", price = "20", quantity = "2", sku = "1" });
                ItemList.items.Add(new Item { name = "C", currency = "USD", price = "50", quantity = "3", sku = "1" });
                ItemList.items.Add(new Item { name = "D", currency = "USD", price = "100", quantity = "4", sku = "1" });
                //tran.item_list = ItemList;

                //Create Amount
                Amount amnt = new Amount();
                amnt.currency = "USD";
                amnt.total = "600";
                //amnt.details = det;
                tran.amount = amnt;

                //Transaction
                tran.description = "TestPaypal Sandbox";
                List<Transaction> transactions = new List<Transaction>();
                transactions.Add(tran);

                //Instrument
                FundingInstrument fundingInstrument = new FundingInstrument();
                fundingInstrument.credit_card = creditCard;

                List<FundingInstrument> fundingInstruments = new List<FundingInstrument>();
                fundingInstruments.Add(fundingInstrument);

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

                //Payment
                Payment payment = new Payment();
                payment.intent = "sale";
                payment.payer = payer;
                payment.transactions = transactions;
                payment.redirect_urls = red;

                Payment createdPayment = payment.Create(Api);

                return createdPayment;
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                var a = ex.Message;
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            // ###Items
            // Items within a transaction.
            var itemList = new ItemList() { items = new List<Item>() };
            itemList.items.Add(new Item()
            {
                name = "Item Name",
                currency = "USD",
                price = "15",
                quantity = "5",
                sku = "sku"
            });

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            var payer = new Payer() { payment_method = "paypal" };
            
            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Details
            // Let's you specify details of a payment amount.
            var details = new Details()
            {
                tax = "15",
                shipping = "10",
                subtotal = "75"
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = "USD",
                total = "100", // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. 
            var transactionList = new List<Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount = amount,
                item_list = itemList
            });

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            this.payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a valid APIContext
            return this.payment.Create(apiContext);
        }
        /// <summary>
        /// Code example for creating a future payment object.
        /// </summary>
        /// <param name="correlationId"></param>
        /// <param name="authorizationCode"></param>
        private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl)
        {
            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            Payer payer = new Payer()
            {
                payment_method = "paypal"
            };

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details()
            {
                tax = "15",
                shipping = "10",
                subtotal = "75"
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = "USD",
                total = "100", // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Items
            // Items within a transaction.
            var itemList = new ItemList() { items = new List<Item>() };
            itemList.items.Add(new Item()
            {
                name = "Item Name",
                currency = "USD",
                price = "15",
                quantity = "5",
                sku = "sku"
            });

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. 
            var transactionList = new List<Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount = amount,
                item_list = itemList
            });

            var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters();
		    authorizationCodeParameters.setClientId(Configuration.ClientId);
		    authorizationCodeParameters.setClientSecret(Configuration.ClientSecret);
		    authorizationCodeParameters.SetCode(authorizationCode);

		    var apiContext = new APIContext();
            apiContext.Config = Configuration.GetConfig();

            var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters);
            var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token);

            // ###Payment
            // A FuturePayment Resource
            this.futurePayment = new FuturePayment()
            {
                intent = "authorize",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            return this.futurePayment.Create(accessToken, correlationId);
        }