Ejemplo n.º 1
0
        public IActionResult Index()
        {
            PayStackApi api = new PayStackApi(SecretKey);

            TransactionInitializeRequest request = new TransactionInitializeRequest();

            request.AmountInKobo = 100;
            request.Email        = "*****@*****.**";


            //request.MetadataObject["CustomOrderNumber"] = postProcessPaymentRequest.Order.CustomOrderNumber;
            //request.MetadataObject["OrderGuid"] = postProcessPaymentRequest.Order.OrderGuid.ToString();
            //request.CallbackUrl = $"{storeLocation}Plugins/PaymentPayStackStandard/HandleCallback";
            request.Reference = Guid.NewGuid().ToString();


            var response = api.Transactions.Initialize(request, true);

            if (response.Status == true)
            {
                HttpContext.Response.Redirect(response.Data.AuthorizationUrl);
            }

            return(View());
        }
Ejemplo n.º 2
0
        private static void InitializeRequest_Setup()
        {
            var request = new TransactionInitializeRequest
            {
                AmountInKobo = 900000,
                Email        = "*****@*****.**",
                Reference    = Guid.NewGuid().ToString() // or your custom reference
            };

            // Add customer fields
            request.CustomFields.Add(CustomField.From("Name", "name", "ADEBISI Foluso A."));

            // Add other metadata
            request.MetadataObject["DataKey"] = "Containerization (Docker) is super Awesome!";

            // Show what the request JSON looks like
            Console.WriteLine("Request");
            request.Print();
            Console.WriteLine();

            // Initialize api with secret from the <appSettings /> of application configuration file (app.config or web.config)
            var response = _api.Transactions.Initialize(request);

            if (!response.Status) // Initialization failed
            {
                // Display response message and quit!
                var message = response.Message;
                return;
            }
            Console.WriteLine("Response");
            response.Print();
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> MakePayment(OrderPaymentVm model)
        {
            if (ModelState.IsValid)
            {
                //var totalSale = await storeDB.Sales.AsNoTracking().CountAsync();
                //var saleId = totalSale + 1;


                var sale = new Sale
                {
                    CustomerId = model.CustomerId,
                    Total      = model.TotalAmount,
                    IsPayed    = false,
                    SaleDate   = DateTime.Now
                };
                storeDB.Sales.Add(sale);
                await storeDB.SaveChangesAsync();

                //Process the order
                var cart = ShoppingCart.GetCart(this.HttpContext);
                sale = cart.CreateOrder(sale);
                var testOrLiveSecret = ConfigurationManager.AppSettings["PayStackSecret"];
                var api = new PayStackApi(testOrLiveSecret);
                // Initializing a transaction
                //var response = api.Transactions.Initialize("*****@*****.**", 5000000);
                var transactionInitializaRequest = new TransactionInitializeRequest
                {
                    //Reference = "SwifKampus",
                    AmountInKobo = _query.ConvertToKobo((int)model.TotalAmount),
                    CallbackUrl  = "http://localhost:59969/Checkout/ConfrimPayment",
                    Email        = model.Email,
                    Bearer       = "Ajaoko Order Payment",

                    CustomFields = new List <CustomField>
                    {
                        new CustomField("customerid", "customerid", model.CustomerId),
                        new CustomField("amount", "amount", model.TotalAmount.ToString(CultureInfo.InvariantCulture)),
                        new CustomField("saleid", "saleid", sale.SaleId.ToString())
                    }
                };
                var response = api.Transactions.Initialize(transactionInitializaRequest);

                if (response.Status)
                {
                    //redirect to authorization url
                    return(RedirectPermanent(response.Data.AuthorizationUrl));
                    // return Content("Successful");
                }
                return(Content("An error occurred"));
            }
            return(RedirectToAction("AddressAndPayment"));
        }
        public async Task <ActionResult> Create(MerchantPaymentVm model)
        {
            if (ModelState.IsValid)
            {
                var merchantId = User.Identity.GetUserId();

                var merchant = await _db.Merchants.AsNoTracking()
                               .FirstOrDefaultAsync(x => x.MerchantId.Equals(merchantId));

                var testOrLiveSecret = ConfigurationManager.AppSettings["PayStackSecret"];
                var api = new PayStackApi(testOrLiveSecret);
                // Initializing a transaction
                //var response = api.Transactions.Initialize("*****@*****.**", 5000000);
                var transactionInitializaRequest = new TransactionInitializeRequest
                {
                    //Reference = "SwifKampus",
                    AmountInKobo = _query.ConvertToKobo((int)model.Amount),
                    //CallbackUrl = "https://unibenportal.azurewebsites.net/SchoolFeePayments/ConfrimPayment",
                    CallbackUrl = "http://localhost:59969/MerchantPayments/ConfrimPayment",
                    Email       = merchant.Email,
                    Bearer      = "Application fee",

                    CustomFields = new List <CustomField>
                    {
                        new CustomField("merchantid", "merchantid", merchant.MerchantId),
                        new CustomField("amount", "amount", model.Amount.ToString(CultureInfo.InvariantCulture))
                        //new CustomField("sessionid", "sessionid", schoolFeePayment.SessionId.ToString()),
                        //new CustomField("feepaymentid","feepaymentid", schoolFeePayment.FeeCategoryId.ToString())
                        //new CustomField("paymentmode","paymentmode", schoolFeePayment.p)
                    }
                };
                var response = api.Transactions.Initialize(transactionInitializaRequest);

                if (response.Status)
                {
                    //redirect to authorization url
                    return(RedirectPermanent(response.Data.AuthorizationUrl));
                    // return Content("Successful");
                }
                return(Content("An error occurred"));
            }
            //return View(schoolFeePayment);
            return(RedirectToAction("Create"));
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var order         = postProcessPaymentRequest.Order;
            var orderUniqueId = postProcessPaymentRequest.Order.OrderGuid.ToString();

            var roundedOrderTotal        = Math.Round(order.OrderTotal, 2);
            var roundedOrderTotalPesewas = Convert.ToInt32(roundedOrderTotal * 100);

            _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, PaystackHelper.OrderTotalSentToPaystack, roundedOrderTotal);

            var secretKey = _paystackStandardPaymentSettings.UseSandbox ?
                            _paystackStandardPaymentSettings.TestSecretToken : _paystackStandardPaymentSettings.LiveSecretToken;

            var payStackApi = new PayStackApi(secretKey);

            var request = new TransactionInitializeRequest
            {
                Email        = order.Customer.Email,
                Reference    = orderUniqueId,
                AmountInKobo = roundedOrderTotalPesewas,
                Currency     = "GHS",
            };

            AddOrderInfoMetaData(request, postProcessPaymentRequest);

            if (_paystackStandardPaymentSettings.PassProductNamesAndTotals)
            {
                AddOrderItemsMetaData(request, postProcessPaymentRequest);
            }

            var response = payStackApi.Transactions.Initialize(request);

            if (response.Status)
            {
                _httpContextAccessor.HttpContext.Response.Redirect(response.Data.AuthorizationUrl);
            }
            else
            {
                var thisPage = _webHelper.GetThisPageUrl(true);
                _httpContextAccessor.HttpContext.Response.Redirect(thisPage);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            string storeLocation = _webHelper.GetStoreLocation(new bool?());

            Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);

            PayStackApi PaystackApi   = new PayStackApi(_PaystackPaymentSettings.SecretKey);
            Customer    customerById  = _customerService.GetCustomerById(postProcessPaymentRequest.Order.CustomerId);
            string      empty         = string.Empty;
            string      customerEmail = customerById.Email != null || customerById == null ? customerById.Email : _customerService.GetCustomerShippingAddress(customerById).Email;

            TransactionInitializeRequest request = new TransactionInitializeRequest();

            request.AmountInKobo = Convert.ToInt32(Math.Ceiling(postProcessPaymentRequest.Order.OrderTotal)) * 100;
            request.Email        = customerEmail;

            request.MetadataObject["CustomOrderNumber"] = (object)postProcessPaymentRequest.Order.CustomOrderNumber;
            Dictionary <string, object> metadataObject = request.MetadataObject;
            Guid orderGuid = postProcessPaymentRequest.Order.OrderGuid;

            string guidString = orderGuid.ToString();

            metadataObject["OrderGuid"] = (object)guidString;
            request.CallbackUrl         = storeLocation + "Plugins/PaymentPaystack/Callback";
            TransactionInitializeRequest initializeRequest = request;

            orderGuid = postProcessPaymentRequest.Order.OrderGuid;

            guidString = orderGuid.ToString();
            initializeRequest.Reference = guidString;
            TransactionInitializeResponse initializeResponse = PaystackApi.Transactions.Initialize(request, true);

            if (!initializeResponse.Status)
            {
                return;
            }

            _httpContextAccessor.HttpContext.Response.Redirect(initializeResponse.Data.AuthorizationUrl);
        }
        /// <summary>
        /// Create common query parameters for the request
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Created query parameters</returns>
        private void AddOrderInfoMetaData(TransactionInitializeRequest request, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //get store location
            var storeLocation = _webHelper.GetStoreLocation();

            //choosing correct order address
            var orderAddress = postProcessPaymentRequest.Order.PickupInStore
                    ? postProcessPaymentRequest.Order.PickupAddress
                    : postProcessPaymentRequest.Order.ShippingAddress;

            //create request metadata
            request.MetadataObject["currency_code"] = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode;

            //order identifier
            request.MetadataObject["invoice"] = postProcessPaymentRequest.Order.CustomOrderNumber;
            request.MetadataObject["custom"]  = postProcessPaymentRequest.Order.OrderGuid.ToString();

            //PDT, IPN and cancel URL
            request.MetadataObject["return"]        = $"{storeLocation}Plugins/PaymentPaystackStandard/CallbackHandler";
            request.MetadataObject["notify_url"]    = $"{storeLocation}Plugins/PaymentPaystackStandard/NotifyHandler";
            request.MetadataObject["cancel_return"] = $"{storeLocation}Plugins/PaymentPaystackStandard/CancelOrder";

            //shipping address, if exists
            request.MetadataObject["no_shipping"]      = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "1" : "2";
            request.MetadataObject["address_override"] = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "0" : "1";
            request.MetadataObject["first_name"]       = orderAddress?.FirstName;
            request.MetadataObject["last_name"]        = orderAddress?.LastName;
            request.MetadataObject["address1"]         = orderAddress?.Address1;
            request.MetadataObject["address2"]         = orderAddress?.Address2;
            request.MetadataObject["city"]             = orderAddress?.City;
            request.MetadataObject["state"]            = orderAddress?.StateProvince?.Abbreviation;
            request.MetadataObject["country"]          = orderAddress?.Country?.TwoLetterIsoCode;
            request.MetadataObject["zip"]         = orderAddress?.ZipPostalCode;
            request.MetadataObject["email"]       = orderAddress?.Email;
            request.MetadataObject["phonenumber"] = orderAddress?.PhoneNumber;
        }
Ejemplo n.º 8
0
        public async Task <PaymentResult> UsePaystack(User user, decimal amount)
        {
            bool customerExists = false;

            try
            {
                customerExists = Paystack.Customers.Fetch(user.Email).Status;
            }
            catch { }

            if (!customerExists)
            {
                Paystack.Customers.Create(new CustomerCreateRequest()
                {
                    Email     = user.Email,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Phone     = user.PhoneNumber
                });
            }

            PaymentResult result = new PaymentResult();

            bool isRecurring = !string.IsNullOrWhiteSpace(user.Wallet.PaystackAuthorization);

            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(p => p.Type == ChannelType.Paystack);

            // Convert to kobo
            int total = (int)Math.Round(amount * channel.ConversionRate);
            int fee   = (int)Math.Round((total * channel.FeePercentage) + channel.FixedFee);

            // Handle Recurring payments
            if (isRecurring)
            {
                var success = Paystack.Transactions
                              .ChargeAuthorization(user.Wallet.PaystackAuthorization, user.Email, total, user.WalletId.ToString(), false);

                if (success.Status)
                {
                    result.Status = PaymentStatus.Success;
                    return(result);
                }
            }

            var request = new TransactionInitializeRequest()
            {
                Email          = user.Email,
                AmountInKobo   = total,
                Reference      = Guid.NewGuid().ToString(),
                MetadataObject = new Dictionary <string, object>()
                {
                    { "walletId", user.WalletId.ToString() }
                }
            };



            var response = Paystack.Transactions.Initialize(request);

            result.Status  = response.Status ? PaymentStatus.Redirected : PaymentStatus.Failed;
            result.Message = response.Data.AuthorizationUrl;

            if (result.Status == PaymentStatus.Failed)
            {
                Logger.LogError("A Paystack Transaction appears to have failed. \n{0}", response.Message);
                result.Message = response.Message;
            }

            return(result);
        }
        /// <summary>
        /// Add order items to the request request metadata
        /// </summary>
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private void AddOrderItemsMetaData(TransactionInitializeRequest request, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //upload order items
            var cartTotal        = decimal.Zero;
            var roundedCartTotal = decimal.Zero;
            var itemCount        = 1;

            //add shopping cart items
            foreach (var item in postProcessPaymentRequest.Order.OrderItems)
            {
                var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);

                //add query parameters
                request.MetadataObject[$"item_name_{itemCount}"] = item.Product.Name;
                request.MetadataObject[$"amount_{itemCount}"]    = roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture);
                request.MetadataObject[$"quantity_{itemCount}"]  = item.Quantity.ToString();

                cartTotal        += item.PriceExclTax;
                roundedCartTotal += roundedItemPrice * item.Quantity;
                itemCount++;
            }

            //add checkout attributes as order items
            var checkoutAttributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);

            foreach (var attributeValue in checkoutAttributeValues)
            {
                var attributePrice        = _taxService.GetCheckoutAttributePrice(attributeValue, false, postProcessPaymentRequest.Order.Customer);
                var roundedAttributePrice = Math.Round(attributePrice, 2);

                //add query parameters
                if (attributeValue.CheckoutAttribute == null)
                {
                    continue;
                }

                request.MetadataObject[$"item_name_{itemCount}"] = attributeValue.CheckoutAttribute.Name;
                request.MetadataObject[$"amount_{itemCount}"]    = roundedAttributePrice.ToString("0.00", CultureInfo.InvariantCulture);
                request.MetadataObject[$"quantity_{itemCount}"]  = "1";

                cartTotal        += attributePrice;
                roundedCartTotal += roundedAttributePrice;
                itemCount++;
            }

            //add shipping fee as a separate order item, if it has price
            var roundedShippingPrice = Math.Round(postProcessPaymentRequest.Order.OrderShippingExclTax, 2);

            if (roundedShippingPrice > decimal.Zero)
            {
                request.MetadataObject[$"item_name_{itemCount}"] = "Shipping fee";
                request.MetadataObject[$"amount_{itemCount}"]    = roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture);
                request.MetadataObject[$"quantity_{itemCount}"]  = "1";

                cartTotal        += postProcessPaymentRequest.Order.OrderShippingExclTax;
                roundedCartTotal += roundedShippingPrice;
                itemCount++;
            }

            //add payment method additional fee as a separate order item, if it has price
            var roundedPaymentMethodPrice = Math.Round(postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax, 2);

            if (roundedPaymentMethodPrice > decimal.Zero)
            {
                request.MetadataObject[$"item_name_{itemCount}"] = "Payment method fee";
                request.MetadataObject[$"amount_{itemCount}"]    = roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture);
                request.MetadataObject[$"quantity_{itemCount}"]  = "1";

                cartTotal        += postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                roundedCartTotal += roundedPaymentMethodPrice;
                itemCount++;
            }

            //add tax as a separate order item, if it has positive amount
            var roundedTaxAmount = Math.Round(postProcessPaymentRequest.Order.OrderTax, 2);

            if (roundedTaxAmount > decimal.Zero)
            {
                request.MetadataObject[$"item_name_{itemCount}"] = "Tax amount";
                request.MetadataObject[$"amount_{itemCount}"]    = roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture);
                request.MetadataObject[$"quantity_{itemCount}"]  = "1";

                cartTotal        += postProcessPaymentRequest.Order.OrderTax;
                roundedCartTotal += roundedTaxAmount;
            }

            if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
            {
                //get the difference between what the order total is and what it should be and use that as the "discount"
                var discountTotal = Math.Round(cartTotal - postProcessPaymentRequest.Order.OrderTotal, 2);
                roundedCartTotal -= discountTotal;

                //gift card or rewarded point amount applied to cart in nopCommerce - shows in Paystack as "discount"
                request.MetadataObject["discount_amount_cart"] = discountTotal.ToString("0.00", CultureInfo.InvariantCulture);
            }

            //save order total that actually sent to Paystack (used for PDT order total validation)
            _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, PaystackHelper.OrderTotalSentToPaystack, roundedCartTotal);
        }
Ejemplo n.º 10
0
        public async Task <PaymentResultApiModel> ProcessPaymentAsync([FromBody] PaymentRequestApiModel paymentRequest)
        {
            // Get the user
            var user = await mUserManager
                       .GetUserAsync(HttpContext.User);

            // Initialize a paystack transaction

            var payStack = new PayStackApi(Configuration["PayStack:SecretKey"]);

            // Set the request parameters
            var request = new TransactionInitializeRequest
            {
                Reference    = paymentRequest.Reference,
                AmountInKobo = paymentRequest.Amount * 100,
                Email        = user.Email,
                CallbackUrl  = Configuration["AbsoluteUrl"] + ApiRoutes.VerifyPayment,
                Currency     = "NGN"
            };

            try
            {
                // Initialize the payment transaction
                var trxResult = payStack
                                .Transactions
                                .Initialize(request);

                // If the transaction was successful...
                if (trxResult.Status)
                {
                    // Get the authorization url
                    var authorizationUrl = trxResult
                                           .Data
                                           .AuthorizationUrl;

                    // Register a payment transaction
                    await mContext
                    .PaymentTransactions
                    .AddAsync(new PaymentTransactionsDataModel
                    {
                        Id              = Guid.NewGuid().ToString(),
                        Reference       = paymentRequest.Reference,
                        UserId          = user.Id,
                        PaymentVerified = false,
                        EditionId       = paymentRequest.EditionId
                    });

                    // Commit changes to the database
                    await mContext.SaveChangesAsync();

                    // Redirect to the authorised url
                    return(new PaymentResultApiModel
                    {
                        AuthorisationUrl = authorizationUrl
                    });
                }
                // Otherwise, if it was unsuccessful...
                else
                {
                    // Return error message
                    return(new PaymentResultApiModel
                    {
                        ErrorMessage = trxResult.Message
                    });
                }
            }
            catch (Exception ex)
            {
                return(new PaymentResultApiModel
                {
                    ErrorMessage = ex.Message
                });
            }
        }
        public async Task <JsonResult> PostHireBooking(GetHireRefcodeRequest hireRequest)
        {
            var response = await Logical.GetHireRefcode(hireRequest);

            IPayStackApi api = new PayStackApi("");
            TransactionInitializeRequest request = new TransactionInitializeRequest();

            Session["HireResponse_"] = response.Item1.Object;
            Session["HireRequest"]   = hireRequest;

            //HireRefCodeReturn call is successful  and payment method is paystack
            if (response.Item1.Code == "200" && hireRequest.PaymentMethod == "5")
            {
                try
                {
                    request.Email        = hireRequest.Email;
                    request.AmountInKobo = Convert.ToInt32(hireRequest.Amount) * 100;
                    // request.AmountInKobo = (int)Session["roundTripHire"] == 0 ? request.AmountInKobo : request.AmountInKobo * 2;
                    request.CallbackUrl = ConfigurationManager.AppSettings["PaystackResponse"];
                    request.MetadataObject["cancel_action"] = ConfigurationManager.AppSettings["PaystackResponse"];
                    request.Reference  = response.Item1.Object.RefCode;
                    request.SubAccount = ConfigurationManager.AppSettings["PaystackSubAccount"] ?? "";

                    var testOrLiveSecret = ConfigurationManager.AppSettings["PayStackSecret"];
                    api = new PayStackApi(testOrLiveSecret);


                    try
                    {
                        var payStackResponse = api.Transactions.Initialize(request);

                        if (payStackResponse.Status)
                        {
                            var PaystackDetails = new ProcessPayStackPayment
                            {
                                amount            = (int)request.AmountInKobo,
                                RefCode           = request.Reference,
                                PayStackReference = payStackResponse.Data.Reference,
                                email             = request.Email
                            };
                            Session["PaystackHireDetails"] = PaystackDetails;

                            Tuple <String, String, getHireRefcodeResponse> returnObject
                                = new Tuple <string, string, getHireRefcodeResponse>(payStackResponse.Data.AuthorizationUrl, "", response.Item1);

                            return(new JsonResult {
                                Data = returnObject
                            });
                        }
                        else
                        {
                            Tuple <String, String> returnObject = new Tuple <string, string>(String.Empty, "failed");
                            return(new JsonResult {
                                Data = returnObject
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Logical.WriteToLog(ex.Message);


                        return(new JsonResult {
                            Data = new Tuple <String, String>("failed", ex.Message)
                        });
                    }
                }
                catch (Exception ex)
                {
                    return(new JsonResult {
                        Data = new Tuple <String, String>("failed", ex.Message)
                    });
                }


                //Tuple<String, String> returnObject = new Tuple<string, string>("", "");
            }
            else if (hireRequest.PaymentMethod == "12")
            {
                var buttonId = "BankTransfer";
                Session["PaymentGatewayType"] = 12;

                var returnUrl = "/Pages/BookOnHold?refCode=" + response.Item1.Object.RefCode + "&buttonId=" + buttonId;

                return(new JsonResult {
                    Data = returnUrl
                });
            }
            else if (!String.IsNullOrEmpty(response.Item1.Code) && response.Item1.Code != "200")
            {
                return(new JsonResult {
                    Data = new Tuple <String, String>("failed", response.Item1.ShortDescription)
                });
            }


            return(new JsonResult {
                Data = new Tuple <String, String>("failed", "Server error")
            });
        }
        public async Task <JsonResult> PostBooking(PostSearchModel booking)
        {
            Session["BookingRequest"] = booking;
            booking.Discount          = 0;
            var payStackUrl = String.Empty;

            try
            {
                if (booking.Beneficiaries == null)
                {
                    booking.Beneficiaries = new List <GigmsBookingBeneficiary>();
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                booking.Beneficiaries = new List <GigmsBookingBeneficiary>();
            }

            var response = await Logical.PostSearchObjects(booking);

            if (!response.Item1.Code.Equals("200"))
            {
                return(new JsonResult {
                    Data = null
                });
            }


            Session["transactionDetails"] = response.Item1;
            var amount = Convert.ToInt64(booking.Amount) * 100;


            // var response = api.Transactions.Initialize(email, (int)amount);


            //Flutterwave
            if (booking.PaymentMethod.Equals(8))
            {
                Tuple <String, String, String> response_ = new Tuple <string, string, String>("", "", "");
                if (!String.IsNullOrEmpty(response.Item1.Object.BookingReferenceCode))
                {
                    var pubKey      = ConfigurationManager.AppSettings["FlutterWavePublicKey"];
                    var secKey      = ConfigurationManager.AppSettings["FlutterWaveSecretKey"];
                    var txref       = response.Item1.Object.BookingReferenceCode;
                    var redirectUrl = ConfigurationManager.AppSettings["FlutterWaveRedirect"] + txref;
                    //PBFPubKey.Text + amount.Text + "NG" + "NGN" + customer_email.Text + "card" + 1 + redirect_url.Text + txref.Text + secKey
                    var hash = _GetSha256Hash(pubKey + booking.Amount.Split(new String[] { "." }, StringSplitOptions.None)[0] + "NG" + "NGN" + booking.Email + "card" + 1 + redirectUrl + txref + secKey);

                    response_ = new Tuple <String, String, String>(response.Item1.Object.BookingReferenceCode, hash, redirectUrl);
                }

                return(new JsonResult {
                    Data = response_
                });
            }

            //Paystack
            else if (booking.PaymentMethod.Equals(5))
            {
                var request = new TransactionInitializeRequest();
                request.Email        = booking.Email;
                request.AmountInKobo = (int)amount;
                request.CallbackUrl  = ConfigurationManager.AppSettings["PaystackResponse"];
                request.MetadataObject["cancel_action"] = ConfigurationManager.AppSettings["PaystackResponse"];
                request.Reference  = response.Item1.Object.BookingReferenceCode;
                request.SubAccount = ConfigurationManager.AppSettings["PaystackSubAccount"] ?? "";

                var testOrLiveSecret = ConfigurationManager.AppSettings["PayStackSecret"];
                var api = new PayStackApi(testOrLiveSecret);

                try
                {
                    var payStackResponse = api.Transactions.Initialize(request);

                    if (payStackResponse.Status)
                    {
                        var PaystackDetails = new ProcessPayStackPayment
                        {
                            amount            = (int)amount,
                            RefCode           = request.Reference,
                            PayStackReference = payStackResponse.Data.Reference,
                            email             = request.Email
                        };
                        Session["PaystackDetails"] = PaystackDetails;
                        payStackUrl = payStackResponse.Data.AuthorizationUrl;

                        return(new JsonResult {
                            Data = payStackUrl
                        });
                    }
                    else
                    {
                        return(new JsonResult {
                            Data = null
                        });
                    }
                }
                catch (Exception ex)
                {
                    Logical.WriteToLog(ex.Message);


                    return(new JsonResult {
                        Data = null
                    });
                }
            }

            else if (booking.PaymentMethod.Equals(12))
            {
                var buttonId = "lnkbtnGtbUssd";
                Session["PaymentGatewayType"] = 12;

                var returnUrl = "/Pages/BookOnHold?refCode=" + response.Item1.Object.BookingReferenceCode + "&buttonId=" + buttonId;

                return(new JsonResult {
                    Data = returnUrl
                });
            }
            else if (booking.PaymentMethod.Equals(7) || booking.PaymentMethod.Equals(10) || booking.PaymentMethod.Equals(12) ||
                     booking.PaymentMethod.Equals(14) || booking.PaymentMethod.Equals(16))
            {
                var buttonId = "ussd";
                Session["PaymentGatewayType"] = 0;

                var returnUrl = "/Pages/BookOnHold?refCode=" + response.Item1.Object.BookingReferenceCode + "&buttonId=" + buttonId;

                return(new JsonResult {
                    Data = returnUrl
                });
            }
            else
            {
                return(null);
            }
        }