Example #1
0
        public async Task <IActionResult> CreateOrder(bool debug = false)
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(BuildRequestBody());
            //3. Call PayPal to set up a transaction
            var response = await PayPalClient.client().Execute(request);

            if (debug)
            {
                var output = response.Result <Order>();
                Console.WriteLine("Status: {0}", output.Status);
                Console.WriteLine("Order Id: {0}", output.Id);
                Console.WriteLine("Intent: {0}", output.Intent);
                Console.WriteLine("Links:");
                foreach (LinkDescription link in output.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                AmountWithBreakdown amount = output.PurchaseUnits[0].Amount;
                Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);
            }
            var result = response.Result <Order>();
            var r      = new PayPalOrder();

            r.OrderId = result.Id;
            return(Ok(r));
        }
        //2. Set up your server to receive a call from the client

        /*
         * Method to create order
         *
         * @param debug true = print response data
         * @return HttpResponse<Order> response received from API
         * @throws IOException Exceptions from API if any
         */
        public async Task <HttpResponse> CreateOrder(bool debug = false)
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(BuildRequestBody());
            //3. Call PayPal to set up a transaction
            var response = await PayPalClient.Client(_configuration).Execute(request);

            if (debug)
            {
                var result = response.Result <Order>();
                Console.WriteLine("Status: {0}", result.Status);
                Console.WriteLine("Order Id: {0}", result.Id);
                Console.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
                Console.WriteLine("Links:");
                foreach (PayPalCheckoutSdk.Orders.LinkDescription link in result.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);
            }

            return(response);
        }
Example #3
0
        /*
         *  Method to create order
         *
         *  @param debug true = print response data
         *  @return HttpResponse<Order> response received from API
         *  @throws IOException Exceptions from API if any
         */
        public async static Task <HttpResponse> CreateOrder(bool debug = false)
        {
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBody());
            var response = await PayPalClient.client().Execute(request);

            if (debug)
            {
                var result = response.Result <Order>();
                Console.WriteLine("Status: {0}", result.Status);
                Console.WriteLine("Order Id: {0}", result.Id);
                Console.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
                Console.WriteLine("Links:");
                foreach (LinkDescription link in result.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);
                Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result));
            }

            return(response);
        }
Example #4
0
        public async Task <PaypalOrder> CreatePaypalOrder(IEnumerable <PurchaseUnitRequest> purchaseUnits, ApplicationContext applicationContext)
        {
            PayPalCheckoutSdk.Core.PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = purchaseUnits.ToList(),
                ApplicationContext    = applicationContext
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var result = response.Result <PaypalOrder>();

                return(result);
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                throw httpException;
            }
        }
        public async Task <HttpResponse> CreateOrderPaypal(string fullname, string address, string street, string city, int IDBill)
        {
            try
            {
                //string strHost = HttpContext.Current.Request.Url.Host.ToString();
                CartDetailsModel cart = LoadCartDetailsModel(IDBill);
                //  string host = Request.Url.Host;

                //  string urlReturn = "https://" + host;
                //  if (host.Equals("localhost"))
                //  {
                //     urlReturn = urlReturn + ":" + HttpContext.Request.Url.Port;
                // }
                // MessageBox.Show(urlReturn);
                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(CreateOrderSample.BuildRequestBody(fullname, address, street, city, cart));
                var response = await PayPalClient.client().Execute(request);

                var    createOrderResult = response.Result <Order>();
                string orderId           = createOrderResult.Id;
                string url = "https://www.sandbox.paypal.com/checkoutnow?token=" + orderId;
                Response.Redirect(url);
                return(response);
            }
            catch (Exception e)
            {
                SendMailSSL.SendErrorToAdmin("Error at CreateOrderPaypal: " + e.ToString());
            }
            return(null);
        }
        public async Task <ActionResult> CreateOrder([FromQuery] string cartId)
        {
            if (string.IsNullOrEmpty(cartId))
            {
                return(BadRequest());
            }

            try
            {
                // correlate cartid with result.id for paypal transactions
                var request      = new OrdersCreateRequest();
                var orderRequest = BuildSimpleOrder(new Random((int)DateTime.Now.Ticks).Next(10, 1000).ToString(), cartId);

                request.Headers.Add("prefer", "return=representation");
                request.RequestBody(orderRequest);

                var response = await _httpClient.Execute(request);

                var result = response.Result <Order>();

                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "PayPal Create Order Exception");

                return(Ok(ex.GetPayPalError()));
            }
        }
        public async Task <object> CreateOrder([FromBody] dynamic OrderAmount, bool debug = true)
        {
            var oa      = (string)OrderAmount["OrderAmount"];
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBody(oa));

            var response = await PayPalClient.client().Execute(request);

            var result = response.Result <Order>();

            response.Headers.Add("id", result.Id);
            if (debug)
            {
                Debug.WriteLine("Status: {0}", result.Status);
                Debug.WriteLine("Order Id: {0}", result.Id);
                Debug.WriteLine("Intent: {0}", result.Intent);
                Debug.WriteLine("Links:");
                foreach (LinkDescription link in result.Links)
                {
                    Debug.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
            }
            return(response);
        }
Example #8
0
        public async Task <HttpResponse> GetResponse(double value)
        {
            OrderRequest order = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = "EUR",
                            Value        = $"{Math.Round(value / 1.95583, 2)}"
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    ReturnUrl = "https://localhost:44351/",
                    CancelUrl = "https://localhost:44351/"
                }
            };

            OrdersCreateRequest request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.ContentType = "application/json";
            request.RequestBody(order);

            HttpResponse response = await Client().Execute(request);

            return(response);
        }
Example #9
0
        public async Task <DataResponse <string> > CreatePayment(int userId, int packageId, int subscriptionType, decimal amount)
        {
            try
            {
                var order = new OrderRequest
                {
                    CheckoutPaymentIntent = "CAPTURE",
                    PurchaseUnits         = new List <PurchaseUnitRequest>
                    {
                        new PurchaseUnitRequest
                        {
                            AmountWithBreakdown = new AmountWithBreakdown
                            {
                                Value        = 100.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture),
                                CurrencyCode = "EUR",
                            }
                        }
                    },
                    ApplicationContext = new ApplicationContext
                    {
                        ReturnUrl = _configuration["PayPal:SuccessUrl"],
                        CancelUrl = _configuration["PayPal:FailUrl"]
                    }
                };

                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(order);

                var responsepp = await PayPalClient.Client(_configuration["PayPal:ClientId"], _configuration["PayPal:ClientSecret"]).Execute(request);

                var result = responsepp.Result <Order>();

                var response = new DataResponse <string>
                {
                    Data      = result.Links.FirstOrDefault(link => link.Rel.Equals("approve"))?.Href,
                    Succeeded = true
                };

                var subscribeModel = new PackageSubscribeDto
                {
                    Id               = 0,
                    UserId           = userId,
                    PackageId        = packageId,
                    SubscriptionType = subscriptionType,
                    Amount           = amount,
                    PaymentId        = result.Id
                };

                _packageService.SubscribeForPackage(subscribeModel);

                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"On create paypal payment: Exception thrown with error {ex.Message}");
                throw new ApplicationException("Due to technical issues we are not able to create the payment!");
            }
        }
        public async static Task <HttpResponse> CreateOrder()
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(buildRequestBody());
            return(await TestHarness.client().Execute(request));
        }
Example #11
0
        public async static Task <HttpResponse> CreateOrder(string intent, int quantity0, int quantity1)
        {
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBody(intent, quantity0, quantity1));
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
        public async static Task <HttpResponse> CreateOrder(Demo.Models.Order order, bool debug = false)
        {
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBody(ConvertOrderToItems(order)));
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
Example #13
0
        public async static Task <HttpResponse> CreateOrderWithMinimumFields(string intent, string amount = "0.01")
        {
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBodyWithMinimumFields(intent, amount));
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
Example #14
0
        public async static Task <HttpResponse> CreateOrderWithMinimumFields(string amount, string currencyCode, string returnUrl, string cancelUrl)
        {
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBodyWithMinimumFields(amount, currencyCode, returnUrl, cancelUrl));
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
Example #15
0
        //2. Set up your server to receive a call from the client

        /*
         * Method to create order
         *
         * @param debug true = print response data
         * @return HttpResponse<Order> response received from API
         * @throws IOException Exceptions from API if any
         */
        public async static Task <HttpResponse> CreateOrder()
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(BuildRequestBody());
            //3. Call PayPal to set up a transaction
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
Example #16
0
        //Below function can be used to create an order with minimum payload.
        public async static Task <HttpResponse> CreateOrderWithMinimumFields()
        {
            Console.WriteLine("Create Order with minimum payload..");
            var request = new OrdersCreateRequest();

            request.Headers.Add("prefer", "return=representation");
            request.RequestBody(BuildRequestBodyWithMinimumFields());
            var response = await PayPalClient.client().Execute(request);

            return(response);
        }
Example #17
0
        //Below function can be used to create an order with complete payload.
        public async static Task <HttpResponse> CreateOrder(List <CartItem> carts, string Add, string host)
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(BuildRequestBody(carts, Add, host));
            var response = await PayPalClient.client().Execute(request);

            var result = response.Result <Order>();

            return(response);
        }
Example #18
0
        public async Task <InvoicePaymentProvider> UpdateAmountInvoice(InvoicePaymentProvider invoicePaymentProvider, Domain.Entities.Orders.Order order)
        {
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var getOrderRequest = new OrdersGetRequest(invoicePaymentProvider.Transaction);

            try
            {
                var getOrderResponse = await client.Execute(getOrderRequest);

                var getOrderResult = getOrderResponse.Result <PaypalOrder>();
                var payment        = new OrderRequest()
                {
                    CheckoutPaymentIntent = "CAPTURE",
                    PurchaseUnits         = new List <PurchaseUnitRequest>()
                    {
                        new PurchaseUnitRequest()
                        {
                            CustomId            = getOrderResult.PurchaseUnits[0].CustomId,
                            Description         = getOrderResult.PurchaseUnits[0].Description,
                            AmountWithBreakdown = new AmountWithBreakdown()
                            {
                                CurrencyCode = Currency.CurrencyValue.USD.ToString(),
                                Value        = Convert.ToInt32(order.TotalAmount).ToString()
                            }
                        }
                    },
                    ApplicationContext = CreateApplicationContext()
                };

                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(payment);
                var response = await client.Execute(request);

                var result = response.Result <PaypalOrder>();
                var uri    = new Uri(result.Links.Single(l => l.Rel == "approve").Href);

                await CancelInvoice(invoicePaymentProvider);

                invoicePaymentProvider.Link        = uri;
                invoicePaymentProvider.Transaction = result.Id;

                return(invoicePaymentProvider);
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                throw httpException;
            }
        }
Example #19
0
        public async Task <Order> OrderProduct(string productId, string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return(null);
            }
            var product         = PurchasesTool.GetProduct(productId);
            var purchaseRequest = new OrdersCreateRequest();

            purchaseRequest.Prefer("return=representation");
            purchaseRequest.RequestBody(product.GetOrderRequest(userId));
            return((await _httpClient.Execute(purchaseRequest)).Result <Order>());
        }
        private async Task <Order> PaypalTransaction(IDbConnection c, IDbTransaction t, string publicKey, string secretKey, string apiUrl)
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(Paypal.BuildOrderRequestBody(apiUrl));
            var response = await Paypal.client(publicKey, secretKey).Execute(request);

            // var statusCode = response.StatusCode;
            Order order = response.Result <Order>();

            return(order);
        }
Example #21
0
        public async Task <InvoicePaymentProvider> CreateUriForPayment(Invoice invoice, Domain.Entities.Orders.Order order, Plan plan)
        {
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = invoice.Id.ToString(),
                        Description         = plan.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = Currency.CurrencyValue.USD.ToString(),
                            Value        = Convert.ToInt32(plan.PlanPrices.Single(x => x.Currency.Code == Currency.CurrencyValue.USD).Price).ToString()
                        }
                    }
                },
                ApplicationContext = CreateApplicationContext()
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var result = response.Result <PaypalOrder>();
                var uri    = new Uri(result.Links.Single(l => l.Rel == "approve").Href);

                return(new InvoicePaymentProvider
                {
                    InvoceId = invoice.Id,
                    Link = uri,
                    Transaction = result.Id,
                    PaymentProvider = new PaymentProvider(PaymentProvider.PaymentProviderValue.Paypal)
                });
            }
            catch (HttpException httpException)
            {
                var debugId = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                throw httpException;
            }
        }
Example #22
0
        /// <summary>
        /// AUTHORIZE,CAPTURE
        /// </summary>
        /// <returns></returns>
        public async static Task <HttpResponse> createOrder()
        {
            HttpResponse response;
            // Construct a request object and set desired parameters
            // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
            var order = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = "USD",
                            Value        = "100.00"
                        },
                        Items = new List <Item>()
                        {
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    ReturnUrl = "https://www.example.com",
                    CancelUrl = "https://www.example.com"
                }
            };


            // Call API with your client and get a response for your call
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(order);
            response = await client().Execute(request);

            var   statusCode = response.StatusCode;
            Order result     = response.Result <Order>();

            Console.WriteLine("Status: {0}", result.Status);
            Console.WriteLine("Order Id: {0}", result.Id);
            Console.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
            Console.WriteLine("Links:");
            foreach (PayPalCheckoutSdk.Orders.LinkDescription link in result.Links)
            {
                Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
            }
            return(response);
        }
Example #23
0
        public static PayPalV2Response createOrder(string price)
        {
            HttpResponse     response;
            PayPalV2Response responsePaypal = new PayPalV2Response();
            // Construct a request object and set desired parameters
            // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
            var order = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = "EUR",
                            Value        = price
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    ReturnUrl = ObjectFactory.instanceName == "Live" ? "https://www.spartanboosting.com/Invoice/InvoiceComplete" : "https://localhost:44353/Invoice/InvoiceComplete",
                    CancelUrl = "https://www.spartanboosting.com"
                }
            };


            // Call API with your client and get a response for your call
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(order);
            response = client().Execute(request).Result;
            var   statusCode = response.StatusCode;
            Order result     = response.Result <Order>();

            foreach (LinkDescription link in result.Links)
            {
                if (link.Rel == "approve")
                {
                    responsePaypal.ApprovalURL = link.Href;
                }
                if (link.Rel == "capture")
                {
                    responsePaypal.CaptureURL = link.Href;
                }
            }
            return(responsePaypal);
        }
        //public void PaypalService()
        //{

        //    string SiteUrl = "http://www.appzero.com/api/payments/";
        //    var environment = new LiveEnvironment(ClientId, ClientSecret);
        //    m_PayPalHttpClient = new PayPalHttpClient(environment);
        //    m_ApplicationContext = new ApplicationContext
        //    {
        //        BrandName = "Naobiz",
        //        ReturnUrl =  SiteUrl + "comporder",
        //        CancelUrl =  SiteUrl + "canorder"
        //    };
        //    m_TaxRate = 5.5M ;
        //}

        public async Task <string> CreateOrder(AppZeroAPI.Entities.CustomerOrder order)
        {
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(CreateOrderRequest(order));
            var response = await m_PayPalHttpClient.Execute(request);

            var order2 = response.Result <PayPalCheckoutSdk.Orders.Order>();

            order.paypal_token = order2.Id;
            var link = order2.Links.Single(link => link.Rel == "approve");

            return(link.Href);
        }
Example #25
0
        public async Task <Uri> CreateUriForPayment(OrderCreateInputModel inputModel)
        {
            var options = paypalOptions.CurrentValue;
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = inputModel.OrderId.ToString(),
                        Description         = inputModel.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = inputModel.Price.Currency.ToString(),
                            Value        = inputModel.Price.Amount.ToString(CultureInfo.InvariantCulture)
                        }
                    }
                },
                ApplicationContext = CreateApplicationContext()
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var statusCode = response.StatusCode;
                var result     = response.Result <Order>();
                return(new Uri(result.Links.Single(l => l.Rel == "approve").Href));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                logger.LogError($"Il tentativo di reindirizzare l'utente alla pagina di pagamento รจ fallito con status code {statusCode} e debugId {debugId}");
                throw new PaymentException();
            }
        }
Example #26
0
        public async Task <HttpResponse> PayPalCreateOrder(string deliveryAddress, List <CartItem> carts, User user, string host, bool debug = false)
        {
            try
            {
                var request = new OrdersCreateRequest();

                request.Headers.Add(PAYPAL_HEADER_PREFER, PAYPAL_HEADER_RETURN);
                request.RequestBody(BuildRequestBody(carts, user, host, deliveryAddress));
                var response = await Client().Execute(request);

                return(response);
            }
            catch (Exception)
            {
                throw new Exception();
            }
        }
        public async Task <Order> CreateOrder(List <Item> items, decimal totalPrice)
        {
            // Construct a request object and set desired parameters
            // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
            var order = new OrderRequest
            {
                CheckoutPaymentIntent = "CAPTURE",

                PurchaseUnits = new List <PurchaseUnitRequest>
                {
                    new PurchaseUnitRequest
                    {
                        AmountWithBreakdown = new AmountWithBreakdown
                        {
                            CurrencyCode    = "AUD",
                            Value           = totalPrice.ToString(CultureInfo.InvariantCulture),
                            AmountBreakdown = new AmountBreakdown
                            {
                                ItemTotal = new Money
                                {
                                    CurrencyCode = "AUD",
                                    Value        = totalPrice.ToString(CultureInfo.InvariantCulture)
                                }
                            }
                        },
                        Items = items
                    }
                },
                ApplicationContext = new ApplicationContext
                {
                    ReturnUrl = "http://studio1btask.azurewebsites.net/",
                    CancelUrl = "http://studio1btask.azurewebsites.net/"
                }
            };
            // Call API with your client and get a response for your call
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(order);
            var response = await Client().Execute(request);

            var result = response.Result <Order>();

            return(result);
        }
Example #28
0
        public async Task <string> paypal()
        {
            HttpResponse response;

            var order = new OrderRequest()
            {
                Intent        = "AUTHORIZE",
                PurchaseUnits = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        Amount = new AmountWithBreakdown()
                        {
                            CurrencyCode = "BRL",
                            Value        = "100.00"
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    ReturnUrl = "https://www.example.com",
                    CancelUrl = "https://www.example.com"
                }
            };

            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(order);
            response = await PayPalClient.client().Execute(request);

            var   statusCode = response.StatusCode;
            Order result     = response.Result <Order>();

            Console.WriteLine("Status: {0}", result.Status);
            Console.WriteLine("Order Id: {0}", result.Id);
            Console.WriteLine("Intent: {0}", result.Intent);
            Console.WriteLine("Links:");
            foreach (LinkDescription link in result.Links)
            {
                Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
            }
            return(PayPalClient.ObjectToJSONString(result));
        }
        public async Task <String> CreateOrder(bool debug = false)
        {
            try
            {
                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(BuildRequestBody());
                //3. Call PayPal to set up a transaction


                PayPalEnvironment payPalEnvironment = new SandboxEnvironment("Af8jLh10kVlYkx4lunz6GSduOt92LyS_hRCOjzRZaU1SZrr1Eb7xYXBjLn-ue6SqiVlsTCEPPlMmL4bI", "EKQBNJEbuBx-yIx0vdtFTiptyfnnyjQVYwhPAmiuKe19T3Viko-B8E-wYrfQuvGdVCOJ97zH9-arreb4");
                //    PayPalEnvironment payPalEnvironment = new LiveEnvironment("ATX3PupfhuN__lU4HiU-Z6uItv6VwdQpFXHENptZYbY5_eJih3wujtYKYvisP6HKmqBv284neWr4bLz4", "EE4f6LT30Fkbi2QQFNRn9umiXv-opRgyTaaqpbkVfPAlXtvIqkywag-Sqczu9GsoF1Brx4FGmLOP7xil");

                var httpResponse = await new PayPalHttpClient(payPalEnvironment).Execute(request);



                //var result = httpResponse.Result;

                var result = httpResponse.Result <Order>();
                //Console.WriteLine("Status: {0}", result.Status);
                //Console.WriteLine("Order Id: {0}", result.Id);
                //Console.WriteLine("Intent: {0}", result.Payer);
                //Console.WriteLine("Links:");
                //foreach (LinkDescription link in result.Links)
                //{
                //    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                //}
                //AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                //Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);

                return(result.Id);
            }

            catch (Exception e)
            {
                var request = new OrdersCreateRequest();
                //PayPalEnvironment payPalEnvironment = new SandboxEnvironment("Af8jLh10kVlYkx4lunz6GSduOt92LyS_hRCOjzRZaU1SZrr1Eb7xYXBjLn-ue6SqiVlsTCEPPlMmL4bI", "EKQBNJEbuBx-yIx0vdtFTiptyfnnyjQVYwhPAmiuKe19T3Viko-B8E-wYrfQuvGdVCOJ97zH9-arreb4");
                PayPalEnvironment payPalEnvironment = new SandboxEnvironment("AWslfpHdNCbQxriW7vju-2SyILIfD62prHjvERnaG_G7B1WmGAP6Spw04MMwJBixLWd5peQ-3JQ1pasX", "EC-tZkW-enhtWH_Yf3Tmm5R15_9ULsIdfMDU150ivrTyJKUyfNioFaR1A7L0bPXPKN3Z3zawNMIp8wqU");
                //return await new PayPalHttpClient(payPalEnvironment).Execute(request);
                return("");
            }
        }
Example #30
0
        public async Task <HttpResponse> CreateOrder()
        {
            HttpResponse response;
            // Construct a request object and set desired parameters
            // Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
            var order = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = Currency,
                            Value        = Amount
                        }
                    }
                },
                ApplicationContext = new ApplicationContext()
                {
                    //ReturnUrl = "https://localhost:44367/api/Payment/verifypayment",
                    ReturnUrl = "https://localhost:44343/Order/GetPayPalPayVerifyPayment",

                    //https://localhost:44362/Orders/OrderConfirmationPage?orderId=&token=66322200JJ012074J&PayerID=HU7CLT2D5N5KE
                    CancelUrl = "https://localhost:44367/api/Payment/create"
                }
            };


            // Call API with your client and get a response for your call
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(order);
            response = await Client().Execute(request);

            var   statusCode = response.StatusCode;
            Order result     = response.Result <Order>();

            return(response);
        }