Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        public async static Task <PayPalHttp.HttpResponse> CreatePaypalOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersCaptureRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            //3. Call PayPal to capture an order
            var response = await PayPalClient.client().Execute(request);

            //4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.
            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);
                }
                Console.WriteLine("Capture Ids: ");
                foreach (PurchaseUnit purchaseUnit in result.PurchaseUnits)
                {
                    foreach (Capture capture in purchaseUnit.Payments.Captures)
                    {
                        Console.WriteLine("\t {0}", capture.Id);
                    }
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
            }

            return(response);
        }
Ejemplo n.º 3
0
        public override ApiResult FetchPaymentStatus(OrderReadOnly order, PayPalCheckoutOneTimeSettings settings)
        {
            try
            {
                if (order.Properties.ContainsKey("PayPalOrderId"))
                {
                    var payPalOrderId = order.Properties["PayPalOrderId"].Value;

                    var clientConfig = GetPayPalClientConfig(settings);
                    var client       = new PayPalClient(clientConfig);
                    var payPalOrder  = client.GetOrder(payPalOrderId);

                    var paymentStatus = GetPaymentStatus(payPalOrder, out PayPalPayment payPalPayment);

                    return(new ApiResult()
                    {
                        TransactionInfo = new TransactionInfoUpdate()
                        {
                            TransactionId = payPalPayment.Id,
                            PaymentStatus = paymentStatus
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <PayPalCheckoutOneTimePaymentProvider>(ex, "PayPal - FetchPaymentStatus");
            }

            return(ApiResult.Empty);
        }
Ejemplo n.º 4
0
Archivo: Order.cs Proyecto: p8b/OSnack
        internal async Task <bool> RefundOrder()
        {
            PayPalCheckoutSdk.Payments.RefundRequest refundRequest = new PayPalCheckoutSdk.Payments.RefundRequest()
            {
                Amount = new PayPalCheckoutSdk.Payments.Money
                {
                    CurrencyCode = AppConst.Settings.PayPal.CurrencyCode,
                    Value        = Payment.RefundAmount.ToString("0.00")
                },
                NoteToPayer = Payment.Message
            };
            var request = new PayPalCheckoutSdk.Payments.CapturesRefundRequest(Payment.Reference);

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

            var refund = response.Result <PayPalCheckoutSdk.Payments.Refund>();

            if (!refund.Status.Equals("COMPLETED"))
            {
                return(false);
            }
            if (Dispute != null)
            {
                Dispute.Messages.Add(new Message()
                {
                    Body       = $"{Dispute.CommunicationType} was closed",
                    IsCustomer = false
                });
                Dispute.Status = false;
            }
            return(true);
        }
Ejemplo n.º 5
0
        //This function can be used to perform authorization on the approved order.
        public async static Task <HttpResponse> AuthorizeOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersAuthorizeRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new AuthorizeRequest());
            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("Authorization Id: {0}", result.PurchaseUnits[0].Payments.Authorizations[0].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("Buyer:");
                Console.WriteLine("\tEmail Address: {0}", result.Payer.Email);
                Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result));
            }

            return(response);
        }
Ejemplo n.º 6
0
        public override ApiResult CancelPayment(OrderReadOnly order, PayPalCheckoutOneTimeSettings settings)
        {
            try
            {
                if (order.TransactionInfo.PaymentStatus == PaymentStatus.Authorized)
                {
                    var clientConfig = GetPayPalClientConfig(settings);
                    var client       = new PayPalClient(clientConfig);

                    client.CancelPayment(order.TransactionInfo.TransactionId);

                    // Cancel payment enpoint doesn't return a result so if the request is successfull
                    // then we'll deem it as successfull and directly set the payment status to Cancelled
                    return(new ApiResult()
                    {
                        TransactionInfo = new TransactionInfoUpdate()
                        {
                            TransactionId = order.TransactionInfo.TransactionId,
                            PaymentStatus = PaymentStatus.Cancelled
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <PayPalCheckoutOneTimePaymentProvider>(ex, "PayPal - CancelPayment");
            }

            return(ApiResult.Empty);
        }
Ejemplo n.º 7
0
        public override ApiResult RefundPayment(OrderReadOnly order, PayPalCheckoutOneTimeSettings settings)
        {
            try
            {
                if (order.TransactionInfo.PaymentStatus == PaymentStatus.Captured)
                {
                    var clientConfig = GetPayPalClientConfig(settings);
                    var client       = new PayPalClient(clientConfig);

                    var payPalPayment = client.RefundPayment(order.TransactionInfo.TransactionId);

                    return(new ApiResult()
                    {
                        TransactionInfo = new TransactionInfoUpdate()
                        {
                            TransactionId = payPalPayment.Id,
                            PaymentStatus = GetPaymentStatus(payPalPayment)
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <PayPalCheckoutOneTimePaymentProvider>(ex, "PayPal - RefundPayment");
            }

            return(ApiResult.Empty);
        }
Ejemplo n.º 8
0
        public async Task <HttpResponse> AuthorizeOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersAuthorizeRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new AuthorizeRequest());
            //3. Call PayPal to authorization an order
            var response = await PayPalClient.Client(_configuration).Execute(request);

            //4. Save the authorization ID to your database. Implement logic to save the authorization to your database for future reference.
            if (debug)
            {
                var result = response.Result <Order>();
                Console.WriteLine("Status: {0}", result.Status);
                Console.WriteLine("Order Id: {0}", result.Id);
                Console.WriteLine("Authorization Id: {0}",
                                  result.PurchaseUnits[0].Payments.Authorizations[0].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("Buyer:");
                Console.WriteLine("\tEmail Address: {0}", result.Payer.Email);
                Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result));
            }

            return(response);
        }
Ejemplo n.º 9
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));
        }
        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);
        }
Ejemplo n.º 11
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 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);
        }
        /*
         *  Method to capture order after creation. Valid approved order Id should be
         *       passed an argument to this method.
         */
        public async static Task <HttpResponse> CaptureOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersCaptureRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            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.Intent);
                Console.WriteLine("Links:");
                foreach (LinkDescription link in result.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                Console.WriteLine("Capture Ids: ");
                foreach (PurchaseUnit purchaseUnit in result.PurchaseUnits)
                {
                    foreach (Capture capture in purchaseUnit.Payments.Captures)
                    {
                        Console.WriteLine("\t {0}", capture.Id);
                    }
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].Amount;
                Console.WriteLine("Buyer:");
                Console.WriteLine("\tEmail Address: {0}\n\tName: {1}\n\tPhone Number: {2}{3}", result.Payer.EmailAddress, result.Payer.Name.FullName, result.Payer.Phone.CountryCode, result.Payer.Phone.NationalNumber);
                Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result));
            }

            return(response);
        }
        public async Task RefundOrderPaypal(string captureOrderId)
        {
            try
            {
                CartDetailsModel cart  = (CartDetailsModel)Session["CartDetails"];
                double           total = cart.Total;
                var request            = new CapturesRefundRequest(captureOrderId);
                request.Prefer("return=representation");
                RefundRequest refundRequest = new RefundRequest()
                {
                    Amount = new PayPalCheckoutSdk.Payments.Money
                    {
                        Value        = "" + total,
                        CurrencyCode = "USD"
                    }
                };
                request.RequestBody(refundRequest);
                var response = await PayPalClient.client().Execute(request);

                var result = response.Result <PayPalCheckoutSdk.Payments.Refund>();
                if (result.Status.Equals("COMPLETED"))
                {
                    TempData["RefundMess"] = "Refund money success !!";
                }
            }
            catch (Exception e)
            {
                SendMailSSL.SendErrorToAdmin("Error at RefundOrderPaypal: " + e.ToString());
            }
        }
Ejemplo n.º 14
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!");
            }
        }
Ejemplo n.º 15
0
 public PayPalController(
     IOptions <BillingSettings> billingSettings,
     PayPalClient paypalClient,
     ITransactionRepository transactionRepository)
 {
     _billingSettings       = billingSettings?.Value;
     _paypalClient          = paypalClient;
     _transactionRepository = transactionRepository;
 }
Ejemplo n.º 16
0
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, PayPalCheckoutOneTimeSettings settings)
        {
            try
            {
                var clientConfig       = GetPayPalClientConfig(settings);
                var client             = new PayPalClient(clientConfig);
                var payPalWebhookEvent = GetPayPalWebhookEvent(client, request);

                if (payPalWebhookEvent != null && payPalWebhookEvent.EventType.StartsWith("CHECKOUT.ORDER.APPROVED"))
                {
                    var webhookPayPalOrder = payPalWebhookEvent.Resource.ToObject <PayPalOrder>();

                    // Fetch persisted order as it may have changed since the webhook
                    // was initially sent (it could be a webhook resend)
                    var persistedPayPalOrder = client.GetOrder(webhookPayPalOrder.Id);

                    PayPalOrder   payPalOrder;
                    PayPalPayment payPalPayment;

                    if (persistedPayPalOrder.Intent == PayPalOrder.Intents.AUTHORIZE)
                    {
                        // Authorize
                        payPalOrder = persistedPayPalOrder.Status != PayPalOrder.Statuses.APPROVED
                            ? persistedPayPalOrder
                            : client.AuthorizeOrder(persistedPayPalOrder.Id);

                        payPalPayment = payPalOrder.PurchaseUnits[0].Payments?.Authorizations?.FirstOrDefault();
                    }
                    else
                    {
                        // Capture
                        payPalOrder = persistedPayPalOrder.Status != PayPalOrder.Statuses.APPROVED
                            ? persistedPayPalOrder
                            : client.CaptureOrder(persistedPayPalOrder.Id);

                        payPalPayment = payPalOrder.PurchaseUnits[0].Payments?.Captures?.FirstOrDefault();
                    }

                    return(CallbackResult.Ok(new TransactionInfo
                    {
                        AmountAuthorized = decimal.Parse(payPalPayment?.Amount.Value ?? "0.00"),
                        TransactionId = payPalPayment?.Id ?? "",
                        PaymentStatus = GetPaymentStatus(payPalOrder)
                    },
                                             new Dictionary <string, string>
                    {
                        { "PayPalOrderId", payPalOrder.Id }
                    }));
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <PayPalCheckoutOneTimePaymentProvider>(ex, "PayPal - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> BuyTicket(BuyTicketBindingModel bindingModel)
        {
            var user = unitOfWork.Users.Find(u => u.Email.Equals(bindingModel.Email)).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest("User with that email doesn't exist"));
            }

            DateTime currentTime   = DateTime.Now;
            var      pricelistItem = unitOfWork.Pricelists.GetPricelistItemForSelectedTypes(bindingModel.TicketType, user.PassengerType, currentTime);

            if (pricelistItem == null)
            {
                return(NotFound());
            }

            OrdersGetRequest request = new OrdersGetRequest(bindingModel.OrderId);
            var response             = await PayPalClient.client().Execute(request);

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

            if (result.Status == "COMPLETED")
            {
                transaction = new Transaction()
                {
                    OrderId    = result.Id,
                    CreateTime = result.CreateTime,
                    PayerEmail = result.Payer.Email,
                    Status     = result.Status,
                    UserId     = user.Id
                };

                unitOfWork.Transactions.Add(transaction);
                unitOfWork.Complete();
            }
            else
            {
                return(BadRequest("Transaction was not validated."));
            }

            Ticket ticket = new Ticket()
            {
                TimeOfPurchase = currentTime,
                TicketInfo     = pricelistItem,
                IsCanceled     = false,
                PassengerId    = user.Id
            };

            SendTicketToEmail(ticket, transaction.PayerEmail);

            unitOfWork.Tickets.Add(ticket);
            unitOfWork.Complete();

            return(Ok());
        }
Ejemplo n.º 18
0
        public void GetToken1()
        {
            var client = new PayPalClient(true,
                                          "AaYECKE7yGsxfx2jyXhQDUT8sQDUF2WZ-YXXuHb9q91J2eIn3_dbPZpfjwsUAWkj7zLkD5uvrXnUugzR",
                                          "EF8v_xfVUKe05PpwGJ5MPKPgLZcKgTMagEAhmWUEAsdYl4Sik8TFHXu0eTYEa6w5iyiXvgXPXDmxDM6y");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            client.Authenticate();

            Assert.IsTrue(true);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            PayPalClient client = new PayPalClient();
            var          result = client.pagar(new Transaccion()
            {
                NombreUsuario = "David",
                Contrasenia   = "swDavid",
                Valor         = 30.0
            });

            System.Console.WriteLine(result);
            System.Console.ReadLine();
        }
Ejemplo n.º 20
0
        // [HttpGet("paypal")]
        // public async Task<HttpResponse> paypal() {

        //     HttpResponse response;

        //     var payer = new Payer()
        // }


        public async static Task <HttpResponse> captureOrder(string id)
        {
            var request = new OrdersCaptureRequest(id);

            request.RequestBody(new OrderActionRequest());
            HttpResponse response = await PayPalClient.client().Execute(request);

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

            Console.WriteLine("Status: {0}", result.Status);
            Console.WriteLine("Capture Id: {0}", result.Id);
            return(response);
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> CaptureOrder(string orderId, bool debug = false)
        {
            string captureId = null;
            var    request   = new OrdersCaptureRequest(orderId);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            //3. Call PayPal to capture an order
            var response = await PayPalClient.client().Execute(request);

            //4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.
            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);
                }
                Console.WriteLine("Capture Ids: ");
                foreach (PurchaseUnit purchaseUnit in output.PurchaseUnits)
                {
                    foreach (Capture capture in purchaseUnit.Payments.Captures)
                    {
                        captureId = capture.Id;
                        Console.WriteLine("\t {0}", capture.Id);
                    }
                }
                AmountWithBreakdown amount = output.PurchaseUnits[0].Amount;
                Console.WriteLine("Buyer:");
                Console.WriteLine("\tEmail Address: {0}\n\tName: {1}\n\tPhone Number: {2}{3}", output.Payer.EmailAddress, output.Payer.Name.FullName, output.Payer.Phone.CountryCode, output.Payer.Phone.NationalNumber);
            }

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

            r.OrderId = orderId;
            foreach (PurchaseUnit purchaseUnit in result.PurchaseUnits)
            {
                foreach (Capture capture in purchaseUnit.Payments.Captures)
                {
                    captureId = capture.Id;
                }
            }
            r.CaptureId = captureId;
            return(Ok(r));
        }
Ejemplo n.º 22
0
        public async Task <DataResponse <Order> > CapturePayPalPayment(string token, string payerId)
        {
            var response = new DataResponse <Order>()
            {
                Succeeded = false, Data = null
            };

            try
            {
                var request = new OrdersCaptureRequest(token);
                request.RequestBody(new OrderActionRequest());

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

                if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created)
                {
                    var order = httpResponse.Result <Order>();

                    var saved = _packageService.MarkSubscriptionAsPayed(order.Id);

                    if (saved)
                    {
                        response.Succeeded = true;
                        response.Data      = order;
                    }
                    else
                    {
                        _logger.LogError($"PayPal Payment capture failure, Status: '{httpResponse.StatusCode}'");
                        response.ErrorMessage = "Update subscription payment statys failed";
                    }
                }
                else
                {
                    _logger.LogError($"PayPal Payment capture failure, Status: '{httpResponse.StatusCode}'");
                    response.ErrorMessage = "PayPal payment couldn't be captured, please contact administrators!";
                }

                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"On capture paypal payment: Exception thrown with error {ex.Message}");
                response.ErrorMessage = "Due to technical issues we are not able to capture the paypal payment";
            }

            return(response);
        }
        protected PayPalWebhookEvent GetPayPalWebhookEvent(PayPalClient client, HttpRequestBase request)
        {
            PayPalWebhookEvent payPalWebhookEvent;

            if (HttpContext.Current.Items["Vendr_PayPalWebhookEvent"] != null)
            {
                payPalWebhookEvent = (PayPalWebhookEvent)HttpContext.Current.Items["Vendr_PayPalWebhookEvent"];
            }
            else
            {
                payPalWebhookEvent = client.ParseWebhookEvent(request);;

                HttpContext.Current.Items["Vendr_PayPalWebhookEvent"] = payPalWebhookEvent;
            }

            return(payPalWebhookEvent);
        }
Ejemplo n.º 24
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));
        }
Ejemplo n.º 25
0
 public PayPalController(
     IOptions <BillingSettings> billingSettings,
     PayPalClient paypalClient,
     PayPalIpnClient paypalIpnClient,
     ITransactionRepository transactionRepository,
     IOrganizationRepository organizationRepository,
     IUserRepository userRepository,
     IMailService mailService,
     IPaymentService paymentService)
 {
     _billingSettings        = billingSettings?.Value;
     _paypalClient           = paypalClient;
     _paypalIpnClient        = paypalIpnClient;
     _transactionRepository  = transactionRepository;
     _organizationRepository = organizationRepository;
     _userRepository         = userRepository;
     _mailService            = mailService;
     _paymentService         = paymentService;
 }
Ejemplo n.º 26
0
        public override PaymentFormResult GenerateForm(OrderReadOnly order, string continueUrl, string cancelUrl, string callbackUrl, PayPalCheckoutOneTimeSettings settings)
        {
            // Get currency information
            var currency = Vendr.Services.CurrencyService.GetCurrency(order.CurrencyId);

            // Create the order
            var clientConfig = GetPayPalClientConfig(settings);
            var client       = new PayPalClient(clientConfig);
            var payPalOrder  = client.CreateOrder(new PayPalCreateOrderRequest
            {
                Intent = settings.Capture
                    ? PayPalOrder.Intents.CAPTURE
                    : PayPalOrder.Intents.AUTHORIZE,
                PurchaseUnits = new[] {
                    new PayPalPurchaseUnitRequest {
                        CustomId = order.GenerateOrderReference(),
                        Amount   = new PayPalAmount {
                            CurrencyCode = currency.Code,
                            Value        = order.TotalPrice.Value.WithTax.ToString("0.00", CultureInfo.InvariantCulture)
                        }
                    }
                },
                AplicationContext = new PayPalOrderApplicationContext
                {
                    BrandName  = settings.BrandName,
                    UserAction = "PAY_NOW",
                    ReturnUrl  = continueUrl,
                    CancelUrl  = cancelUrl
                }
            });

            // Setup the payment form to redirect to approval link
            var approveLink       = payPalOrder.Links.FirstOrDefault(x => x.Rel == "approve");
            var approveLinkMethod = (FormMethod)Enum.Parse(typeof(FormMethod), approveLink.Method, true);

            return(new PaymentFormResult()
            {
                Form = new PaymentForm(approveLink.Href, approveLinkMethod)
            });
        }
Ejemplo n.º 27
0
Archivo: Order.cs Proyecto: p8b/OSnack
        internal async Task <bool> CapturePaypalPayment(string paypalId)
        {
            Payment = new Payment()
            {
                PaymentProvider = "PayPal",
                Reference       = paypalId,
            };
            var request = new OrdersCaptureRequest(paypalId);

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

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

            if (!paypalOrder.Status.Equals("COMPLETED"))
            {
                return(false);
            }
            Status            = OrderStatusType.InProgress;
            Payment.Reference = paypalOrder.PurchaseUnits.FirstOrDefault().Payments.Captures.FirstOrDefault().Id;
            Payment.DateTime  = DateTime.Parse(paypalOrder.UpdateTime);
            Payment.Type      = PaymentType.Complete;
            Payment.Email     = paypalOrder.Payer.Email;
            var purchaseUnit = paypalOrder.PurchaseUnits.FirstOrDefault();

            Name       = purchaseUnit.ShippingDetail.Name.FullName;
            FirstLine  = purchaseUnit.ShippingDetail.AddressPortable.AddressLine1;
            SecondLine = purchaseUnit.ShippingDetail.AddressPortable.AddressLine2;
            if (purchaseUnit.ShippingDetail.AddressPortable.AdminArea1 != null)
            {
                City = purchaseUnit.ShippingDetail.AddressPortable.AdminArea1;
            }
            if (purchaseUnit.ShippingDetail.AddressPortable.AdminArea2 != null)
            {
                City = purchaseUnit.ShippingDetail.AddressPortable.AdminArea2;
            }
            Postcode = purchaseUnit.ShippingDetail.AddressPortable.PostalCode;
            return(true);
        }
        //This method  can be used to capture the payment on the approved authorization.
        public async static Task<HttpResponse> CaptureOrder(string AuthorizationId, bool debug = false)
        {
            var request = new AuthorizationsCaptureRequest(AuthorizationId);
            request.Prefer("return=representation");
            request.RequestBody(new CaptureRequest());
            var response = await PayPalClient.client().Execute(request);

            if (debug)
            {
                var result = response.Result<Capture>();
                Console.WriteLine("Status: {0}", result.Status);
                Console.WriteLine("Order Id: {0}", result.Id);
                Console.WriteLine("Links:");
                foreach (LinkDescription link in result.Links)
                {
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
                }
                Console.WriteLine("Response JSON: \n {0}", PayPalClient.ObjectToJSONString(result));
            }

            return response;
        }
Ejemplo n.º 29
0
        public async Task <HttpResponse> CaptureOrder(string OrderId, bool debug = false)
        {
            var request = new OrdersCaptureRequest(OrderId);

            request.Prefer("return=representation");
            request.RequestBody(new OrderActionRequest());
            //3. Call PayPal to capture an order
            var response = await PayPalClient.Client(_configuration).Execute(request);

            //4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.

            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);
                }
                Console.WriteLine("Capture Ids: ");
                foreach (PurchaseUnit purchaseUnit in result.PurchaseUnits)
                {
                    foreach (PayPalCheckoutSdk.Orders.Capture capture in purchaseUnit.Payments.Captures)
                    {
                        Console.WriteLine("\t {0}", capture.Id);
                    }
                }
                AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
                Console.WriteLine("Buyer:");
                Console.WriteLine("\tEmail Address: {0}\n\tName: {1}\n\tPhone Number: {2}{3}", result.Payer.Email, result.Payer.Name.FullName, result.Payer.PhoneWithType.PhoneNumber.CountryCallingCode, result.Payer.PhoneWithType.PhoneNumber.NationalNumber);
            }

            return(response);
        }
Ejemplo n.º 30
0
        public async Task <String> GetOrder(string id, bool debug = false)
        {
            OrdersGetRequest request = new OrdersGetRequest(id);
            //3. Call PayPal to get the transaction
            var response = await PayPalClient.client().Execute(request);

            //4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
            var result = response.Result <Order>();

            Console.WriteLine("Retrieved Order Status");
            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);
            }
            AmountWithBreakdown amount = result.PurchaseUnits[0].Amount;

            Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);

            return(PayPalClient.ObjectToJSONString(response.Result <Order>()));
        }