Beispiel #1
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());
        }
Beispiel #2
0
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, EPayBamboraSettings settings)
        {
            string transactionId = request.QueryString["txnid"];
            string strAmount     = request.QueryString["amount"];
            string hash          = request.QueryString["hash"];

            string md5CheckValue = string.Empty;

            foreach (string k in request.QueryString.Keys)
            {
                if (k != "hash")
                {
                    md5CheckValue += request.QueryString[k];
                }
            }
            if (!string.IsNullOrEmpty(settings.Md5Key))
            {
                md5CheckValue += settings.Md5Key;
            }


            if (order.CartNumber == request.QueryString["orderid"] && GenerateMD5Hash(md5CheckValue) == hash.ToUpper())
            {
                string fee           = request.QueryString["txnfee"];
                string cardid        = request.QueryString["paymenttype"];
                string cardnopostfix = request.QueryString["cardno"];

                decimal totalAmount = (decimal.Parse(strAmount, CultureInfo.InvariantCulture) + decimal.Parse(fee, CultureInfo.InvariantCulture));

                //bool autoCaptured = settings.ContainsKey("instantcapture") && settings["instantcapture"] == "1";

                //callbackInfo = new CallbackInfo(totalAmount / 100M, transaction, !autoCaptured ? PaymentState.Authorized : PaymentState.Captured, cardid, cardnopostfix);

                return(CallbackResult.Ok(new TransactionInfo
                {
                    TransactionId = transactionId,
                    AmountAuthorized = AmountFromMinorUnits(Convert.ToInt64(totalAmount) + Convert.ToInt64(fee)),
                    TransactionFee = AmountFromMinorUnits(Convert.ToInt64(fee)),
                    PaymentStatus = PaymentStatus.Authorized
                }));
            }
            else
            {
                return(CallbackResult.BadRequest());
            }
        }
        public override async Task <CallbackResult> ProcessCallbackAsync(PaymentProviderContext <BamboraCheckoutSettings> ctx)
        {
            try
            {
                var clientConfig = GetBamboraClientConfig(ctx.Settings);
                var client       = new BamboraClient(clientConfig);

                if (client.ValidateRequest(ctx.Request, out var qs))
                {
                    var txnId   = qs["txnid"];
                    var orderId = qs["orderid"];
                    var amount  = int.Parse("0" + qs["amount"]);
                    var txnFee  = int.Parse("0" + qs["txnfee"]);

                    // Validate params
                    if (!string.IsNullOrWhiteSpace(txnId) &&
                        !string.IsNullOrWhiteSpace(orderId) &&
                        orderId == BamboraSafeOrderId(ctx.Order.OrderNumber) &&
                        amount > 0)
                    {
                        // Fetch the transaction details so that we can work out
                        // the status of the transaction as the querystring params
                        // are not enough on their own
                        var transactionResp = await client.GetTransactionAsync(txnId);

                        if (transactionResp.Meta.Result)
                        {
                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = transactionResp.Transaction.Id,
                                AmountAuthorized = AmountFromMinorUnits(amount + txnFee),
                                TransactionFee = AmountFromMinorUnits(txnFee),
                                PaymentStatus = GetPaymentStatus(transactionResp.Transaction)
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Bambora - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, StripeCheckoutOneTimeSettings settings)
        {
            // The ProcessCallback method is only intendid to be called via a Stripe Webhook and so
            // it's job is to process the webhook event and finalize / update the order accordingly

            try
            {
                var secretKey            = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey;
                var webhookSigningSecret = settings.TestMode ? settings.TestWebhookSigningSecret : settings.LiveWebhookSigningSecret;

                ConfigureStripe(secretKey);

                var stripeEvent = GetWebhookStripeEvent(request, webhookSigningSecret);
                if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    if (stripeEvent.Data?.Object?.Instance is Session stripeSession)
                    {
                        var paymentIntentService = new PaymentIntentService();
                        var paymentIntent        = paymentIntentService.Get(stripeSession.PaymentIntentId);

                        return(CallbackResult.Ok(new TransactionInfo
                        {
                            TransactionId = GetTransactionId(paymentIntent),
                            AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                            PaymentStatus = GetPaymentStatus(paymentIntent)
                        },
                                                 new Dictionary <string, string>
                        {
                            { "stripeSessionId", stripeSession.Id },
                            { "stripePaymentIntentId", stripeSession.PaymentIntentId },
                            { "stripeChargeId", GetTransactionId(paymentIntent) },
                            { "stripeCardCountry", paymentIntent.Charges?.Data?.FirstOrDefault()?.PaymentMethodDetails?.Card?.Country }
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, SquareSettings settings)
        {
            var accessToken = settings.SandboxMode ? settings.SandboxAccessToken : settings.LiveAccessToken;
            var environment = settings.SandboxMode ? SquareSdk.Environment.Sandbox : SquareSdk.Environment.Production;

            var squareEvent = GetSquareWebhookEvent(request, settings);

            if (squareEvent != null && squareEvent.IsValid)
            {
                try
                {
                    var client = new SquareSdk.SquareClient.Builder()
                                 .Environment(environment)
                                 .AccessToken(accessToken)
                                 .Build();

                    var orderApi = client.OrdersApi;

                    var orderId = GetOrderId(squareEvent);

                    var paymentStatus = PaymentStatus.PendingExternalSystem;
                    SquareSdk.Models.Order squareOrder = null;

                    if (!string.IsNullOrWhiteSpace(orderId))
                    {
                        var result = orderApi.BatchRetrieveOrders(
                            new BatchRetrieveOrdersRequest(new List <string>()
                        {
                            orderId
                        }));

                        squareOrder = result.Orders.FirstOrDefault();
                    }

                    if (squareOrder != null)
                    {
                        var orderStatus = squareOrder.State ?? "";

                        switch (orderStatus.ToUpper())
                        {
                        case "COMPLETED":
                        case "AUTHORIZED":
                            paymentStatus = PaymentStatus.Authorized;
                            break;

                        case "CANCELED":
                            paymentStatus = PaymentStatus.Cancelled;
                            break;
                        }
                    }

                    var callbackResult = CallbackResult.Ok(new TransactionInfo
                    {
                        AmountAuthorized = order.TransactionAmount.Value.WithTax,
                        TransactionFee   = 0m,
                        TransactionId    = squareOrder.Id,
                        PaymentStatus    = paymentStatus
                    });

                    return(callbackResult);
                }
                catch (Exception ex)
                {
                    Vendr.Log.Error <SquareCheckoutOnetimePaymentProvider>(ex, "Square - ProcessCallback");
                }
            }

            return(CallbackResult.BadRequest());
        }
        public override async Task <CallbackResult> ProcessCallbackAsync(PaymentProviderContext <StripeCheckoutSettings> ctx)
        {
            // The ProcessCallback method is only intendid to be called via a Stripe Webhook and so
            // it's job is to process the webhook event and finalize / update the ctx.Order accordingly

            try
            {
                var secretKey            = ctx.Settings.TestMode ? ctx.Settings.TestSecretKey : ctx.Settings.LiveSecretKey;
                var webhookSigningSecret = ctx.Settings.TestMode ? ctx.Settings.TestWebhookSigningSecret : ctx.Settings.LiveWebhookSigningSecret;

                ConfigureStripe(secretKey);

                var stripeEvent = await GetWebhookStripeEventAsync(ctx, webhookSigningSecret);

                if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    if (stripeEvent.Data?.Object?.Instance is Session stripeSession)
                    {
                        if (stripeSession.Mode == "payment")
                        {
                            var paymentIntentService = new PaymentIntentService();
                            var paymentIntent        = await paymentIntentService.GetAsync(stripeSession.PaymentIntentId, new PaymentIntentGetOptions
                            {
                                Expand = new List <string>(new[] {
                                    "review"
                                })
                            });

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(paymentIntent),
                                AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(paymentIntent)
                            },
                                                     new Dictionary <string, string>
                            {
                                { "stripeSessionId", stripeSession.Id },
                                { "stripeCustomerId", stripeSession.CustomerId },
                                { "stripePaymentIntentId", stripeSession.PaymentIntentId },
                                { "stripeSubscriptionId", stripeSession.SubscriptionId },
                                { "stripeChargeId", GetTransactionId(paymentIntent) },
                                { "stripeCardCountry", paymentIntent.Charges?.Data?.FirstOrDefault()?.PaymentMethodDetails?.Card?.Country }
                            }));
                        }
                        else if (stripeSession.Mode == "subscription")
                        {
                            var subscriptionService = new SubscriptionService();
                            var subscription        = await subscriptionService.GetAsync(stripeSession.SubscriptionId, new SubscriptionGetOptions {
                                Expand = new List <string>(new[] {
                                    "latest_invoice",
                                    "latest_invoice.charge",
                                    "latest_invoice.charge.review",
                                    "latest_invoice.payment_intent",
                                    "latest_invoice.payment_intent.review"
                                })
                            });

                            var invoice = subscription.LatestInvoice;

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(invoice),
                                AmountAuthorized = AmountFromMinorUnits(invoice.PaymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(invoice)
                            },
                                                     new Dictionary <string, string>
                            {
                                { "stripeSessionId", stripeSession.Id },
                                { "stripeCustomerId", stripeSession.CustomerId },
                                { "stripePaymentIntentId", invoice.PaymentIntentId },
                                { "stripeSubscriptionId", stripeSession.SubscriptionId },
                                { "stripeChargeId", invoice.ChargeId },
                                { "stripeCardCountry", invoice.Charge?.PaymentMethodDetails?.Card?.Country }
                            }));
                        }
                    }
                    else if (stripeEvent != null && stripeEvent.Type == Events.ReviewClosed)
                    {
                        if (stripeEvent.Data?.Object?.Instance is Review stripeReview && !string.IsNullOrWhiteSpace(stripeReview.PaymentIntentId))
                        {
                            var paymentIntentService = new PaymentIntentService();
                            var paymentIntent        = paymentIntentService.Get(stripeReview.PaymentIntentId, new PaymentIntentGetOptions
                            {
                                Expand = new List <string>(new[] {
                                    "review"
                                })
                            });

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(paymentIntent),
                                AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(paymentIntent)
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Stripe - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }