protected PaymentStatus GetPaymentStatus(PayPalOrder payPalOrder, out PayPalPayment payPalPayment)
        {
            payPalPayment = null;

            if (payPalOrder.PurchaseUnits != null && payPalOrder.PurchaseUnits.Length == 1)
            {
                var purchaseUnit = payPalOrder.PurchaseUnits[0];
                if (purchaseUnit.Payments != null)
                {
                    if (purchaseUnit.Payments.Refunds != null && purchaseUnit.Payments.Refunds.Length > 0)
                    {
                        payPalPayment = purchaseUnit.Payments.Refunds.First();
                    }
                    else if (purchaseUnit.Payments.Captures != null && purchaseUnit.Payments.Captures.Length > 0)
                    {
                        payPalPayment = purchaseUnit.Payments.Captures.First();
                    }
                    else if (purchaseUnit.Payments.Authorizations != null && purchaseUnit.Payments.Authorizations.Length > 0)
                    {
                        payPalPayment = purchaseUnit.Payments.Authorizations.First();
                    }

                    if (payPalPayment != null)
                    {
                        return(GetPaymentStatus(payPalPayment));
                    }
                }
            }

            return(PaymentStatus.Initialized);
        }
예제 #2
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));
        }
예제 #3
0
    public static PayPalRedirect ExpressCheckout(PayPalOrder order)
    {
        NameValueCollection values = new NameValueCollection();

        values["METHOD"]        = "SetExpressCheckout";
        values["RETURNURL"]     = PayPalSettings.ReturnUrl;
        values["CANCELURL"]     = PayPalSettings.CancelUrl;
        values["AMT"]           = "";
        values["PAYMENTACTION"] = "Sale";
        values["CURRENCYCODE"]  = "GBP";
        values["BUTTONSOURCE"]  = "PP-ECWizard";
        values["USER"]          = PayPalSettings.Username;
        values["PWD"]           = PayPalSettings.Password;
        values["SIGNATURE"]     = PayPalSettings.Signature;
        values["SUBJECT"]       = "";
        values["VERSION"]       = "2.3";
        values["AMT"]           = order.Amount.ToString(CultureInfo.InvariantCulture);

        values = Submit(values);

        string ack = values["ACK"].ToLower();

        if (ack == "success" || ack == "successwithwarning")
        {
            return(new PayPalRedirect
            {
                Token = values["TOKEN"],
                Url = String.Format("https://{0}/cgi-bin/webscr?cmd=_express-checkout&token={1}",
                                    PayPalSettings.CgiDomain, values["TOKEN"])
            });
        }
        else
        {
            throw new Exception(values["L_LONGMESSAGE0"]);
        }
    }
예제 #4
0
        public virtual PayPalOrder BuildPayPalOrder(Basket basket)
        {
            var basketLine = basket.BasketLines.FirstOrDefault();

            if (basketLine == null)
            {
                return(null);
            }

            var ticket          = _ticketService.GetTicketById(basketLine.TicketId.ToString());
            var currencyIsoCode = _currencyService.GetCurrencyIsoCodeById(basket.CurrencyId.ToString());
            var language        = _translationService.GetLanguage(basket.PurchaseLanguage);

            var orderItem = new PayPalOrderItem(
                ticket.Name,
                basketLine.Id.ToString(),
                1,
                basket.Total,
                0);

            var order = new PayPalOrder()
            {
                Items = new List <PayPalOrderItem>()
                {
                    orderItem
                },
                ISOCurrencyCode = currencyIsoCode,
                OrderSubTotal   = basket.Total,
                OrderTaxTotal   = 0,
                OrderTotal      = basket.Total,
                RequestShipping = true,
                orderLanguage   = language.ShortCode
            };

            return(order);
        }
        /// <summary>
        /// ShortcutExpressCheckout: The method that calls SetExpressCheckout API
        /// </summary>
        public PayPalReturn ShortcutExpressCheckout(string returnUrl, string cancelUrl, string pageStyle, PayPalOrder order, bool commit,
                                                    string solutionType = null)
        {
            var encoder = new NvpCodec();

            encoder["METHOD"]        = "SetExpressCheckout";
            encoder["RETURNURL"]     = returnUrl;
            encoder["CANCELURL"]     = cancelUrl;
            encoder["AMT"]           = order.OrderTotal.ToString("N2");
            encoder["TAXAMT"]        = order.OrderTaxTotal.ToString("N2");
            encoder["ITEMAMT"]       = order.OrderSubTotal.ToString("N2");
            encoder["PAYMENTACTION"] = "Sale";
            encoder["CURRENCYCODE"]  = order.ISOCurrencyCode;

            encoder["NOSHIPPING"]         = "0";
            encoder["LOCALECODE"]         = order.orderLanguage;
            encoder["REQCONFIRMSHIPPING"] = "0";
            if (!string.IsNullOrEmpty(solutionType))
            {
                encoder["SOLUTIONTYPE"] = solutionType;
            }

            if (!string.IsNullOrEmpty(pageStyle))
            {
                encoder["PAGESTYLE"] = pageStyle;
            }

            var c = 0;

            foreach (var item in order.Items)
            {
                encoder[string.Concat("L_NAME", c)]   = item.ProductName;
                encoder[string.Concat("L_AMT", c)]    = item.LineItemPrice.ToString("N2");
                encoder[string.Concat("L_NUMBER", c)] = item.ProductId;
                encoder[string.Concat("L_QTY", c)]    = item.Quantity.ToString();
                encoder[string.Concat("L_TAXAMT", c)] = item.LineItemTax.ToString("N2");
                c++;
            }

            var pStrrequestforNvp = encoder.Encode();
            var pStresponsenvp    = HttpCall(pStrrequestforNvp);

            var decoder = new NvpCodec();

            decoder.Decode(pStresponsenvp);

            var res = new PayPalReturn {
                AUK = decoder["ACK"].ToLower()
            };

            if (res.AUK != null && (res.AUK == "success" || res.AUK == "successwithwarning"))
            {
                res.Token       = decoder["TOKEN"];
                res.RedirectURL = string.Concat(_payPalUrl, "&token=", res.Token, commit ? "&useraction=commit" : string.Empty);
            }
            else
            {
                res.IsError      = true;
                res.ErrorMessage = decoder["L_LONGMESSAGE0"]; //decoder["L_SHORTMESSAGE0"]
                res.ErrorCode    = decoder["L_ERRORCODE0"];
                LoggerService.LogItem(res.ErrorCode + Environment.NewLine + res.ErrorMessage);
            }

            return(res);
        }
 public PayPalReturn ShortcutExpressCheckout(string returnUrl, string cancelUrl, string pageStyle, PayPalOrder order, bool commit)
 {
     return(ShortcutExpressCheckout(returnUrl, cancelUrl, pageStyle, order, commit, null));
 }
 protected PaymentStatus GetPaymentStatus(PayPalOrder payPalOrder)
 {
     return(GetPaymentStatus(payPalOrder, out PayPalPayment payPalPayment));
 }
예제 #8
0
        public async Task <PayPalOrder> CreatePendingOrder(Guid accountId, decimal amount)
        {
            // TODO: Make this range configurable.
            if (amount <= 0 || amount > 500)
            {
                throw new Exception("Invalid amount.");
            }

            _logger.LogInformation("Creating pending paypal order for {AccountId} for {Amount}", accountId, amount);

            var account = await _accountsService.GetAccount(AccountIdentification.ById(accountId));

            account.NotNull();

            var    potentialOrderId = Guid.NewGuid();
            string paypalOrderId;

            {
                var client  = _payPalClientProvider.BuildHttpClient();
                var request = new OrdersCreateRequest();
                request.Prefer("return=representation");
                request.RequestBody(new OrderRequest
                {
                    CheckoutPaymentIntent = "CAPTURE",
                    PurchaseUnits         = new List <PurchaseUnitRequest>
                    {
                        new PurchaseUnitRequest
                        {
                            ReferenceId         = potentialOrderId.ToString(),
                            AmountWithBreakdown = new AmountWithBreakdown
                            {
                                Value        = amount.ToString(CultureInfo.InvariantCulture),
                                CurrencyCode = "USD"
                            }
                        }
                    }
                });

                var response = await client.Execute(request);

                if (response.StatusCode != HttpStatusCode.Created)
                {
                    _logger.LogError("Invalid status code from PayPal order create: status: {Status} response: {Response}", response.StatusCode, SerializePayPalType(response.Result <object>()));
                    throw new Exception("Invalid PayPal response");
                }

                paypalOrderId = response.Result <Order>().Id;
            }

            // Great, we created a PayPal order, let's add the record into the database.
            using (var con = new ConScope(_dataService))
            {
                var pendingOrder = new PayPalOrder
                {
                    Id            = potentialOrderId,
                    OrderStatus   = PayPalOrderStatus.Pending,
                    PayPalOrderId = paypalOrderId,
                    AccountId     = account.Id,
                    Amount        = amount
                };

                await con.Connection.InsertAsync(pendingOrder);

                return(pendingOrder);
            }
        }