Blazor 服务器应用程序未重定向到外部支付应用程序网址

问题描述 投票:0回答:1
<form @onsubmit="ProcessCheckout">
    <div>
        <h2>Checkout</h2>
        <button type="submit" class="btn btn-primary">Place Order</button>
        <a href="/cart" class="btn btn-secondary">Back to Shopping Bag</a>
    </div>
</form>

单击“下订单”按钮时重定向到新选项卡中的authorizationUrl 链接的最佳方式。

@code {
    private bool shouldRedirect;
    private string authorizationUrl;

    protected override async Task OnInitializedAsync()
    {
        await ProcessCheckout();
    }

    private async Task ProcessCheckout()
    {
        try
        {
            // Initialize checkout process
            var userId = await GetUserIdAsync();
            var netTotal = await _cartService.GetBasketNetTotalAsync(userId);

            var authState = await _authStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            string strEmail = user.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;

            string token = _configuration["PayStackSettings:PayStackSecretKey"];
            var payStack = new PayStackApi(token);

            TransactionInitializeRequest request = new()
            {
                AmountInKobo = Convert.ToInt32(netTotal) * 100,
                Email = strEmail,
                Reference = Generate().ToString(),
                Currency = "GHS"
            };

            // Initiate transaction
            var response = payStack.Transactions.Initialize(request);
            if (response.Status)
            {
                authorizationUrl = response.Data.AuthorizationUrl;

                shouldRedirect = true;
                StateHasChanged(); // Trigger re-render
            }
        }
        catch (Exception ex)
        {            
            throw new Exception(ex.Message);
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (shouldRedirect)
        {
            shouldRedirect = false; // Reset flag to prevent re-invoking
            await JS.InvokeVoidAsync("open", authorizationUrl, "_blank");
        }
    }

    private async Task<string> GetUserIdAsync()
    {
        var authState = await _authStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        return user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
    }

    private static int Generate() => new Random((int)DateTime.Now.Ticks).Next(100000000, 999999999);
}

大家好!单击“下订单”按钮时,我尝试在新的浏览器选项卡中打开authorizationUrl。我的代码只是刷新页面,尽管它在调试模式下点击了 ProcessCheckout。请注意,这是一个 Blazor 服务器应用程序

c# blazor
1个回答
0
投票

由于我使用的是 Blazor 服务器应用程序,因此我首先将 @rendermode InteractiveServer 添加到页面,然后从代码中删除 OnInitializedAsync() 方法,因此最终代码变为:

@page "/checkout"
@attribute [Authorize]
@rendermode InteractiveServer
@inject AuthenticationStateProvider _authStateProvider
@inject ICartService _cartService
@inject IUserService _userService
@inject IConfiguration _configuration
@inject IJSRuntime JS
@inject NavigationManager _navigation

<PageTitle>Checkout | LearnSpace</PageTitle>
<SectionContent SectionName="page-header-title">Checkout</SectionContent>

<div>
    <h2>Checkout</h2>
    <button class="btn btn-primary" @onclick="ProcessCheckout">Place Order</button>
    <a href="/cart" class="btn btn-secondary">Back to Shopping Bag</a>
</div>

@code {
    private bool shouldRedirect;
    private string authorizationUrl;
    private bool shouldOpenInNewTab = false;

    private async Task ProcessCheckout()
    {
        try
        {
            // Initialize checkout process
            var userId = await GetUserIdAsync();
            var netTotal = await _cartService.GetBasketNetTotalAsync(userId);

            var authState = await _authStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            string strEmail = user.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;

            string token = _configuration["PayStackSettings:PayStackSecretKey"];
            var payStack = new PayStackApi(token);

            TransactionInitializeRequest request = new()
            {
                AmountInKobo = Convert.ToInt32(netTotal) * 100,
                Email = strEmail,
                Reference = Generate().ToString(),
                Currency = "GHS"
            };

            // Initiate transaction
            var response = payStack.Transactions.Initialize(request);
            if (response.Status)
            {
                authorizationUrl = response.Data.AuthorizationUrl;
                shouldOpenInNewTab = true;
                StateHasChanged(); // Trigger re-render to ensure OnAfterRenderAsync runs
            }
        }
        catch (Exception ex)
        {            
            throw new Exception(ex.Message);
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (shouldOpenInNewTab && authorizationUrl != null)
        {
            shouldOpenInNewTab = false; // Reset the flag after the redirect
            await JS.InvokeVoidAsync("openInNewTab", authorizationUrl);
        }
    }

    private async Task<string> GetUserIdAsync()
    {
        var authState = await _authStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        return user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
    }

    private static int Generate() => new Random((int)DateTime.Now.Ticks).Next(100000000, 999999999);
}

就是这样。

© www.soinside.com 2019 - 2024. All rights reserved.