Paypal .Net SDK 在 Sandbox 和 live 之间动态切换不工作

Paypal .Net SDK dynamic switch between Sandbox and live not working

我有一个包含多个网站的网络应用程序。有些网站必须在 Sandbox 模式下使用 Paypal,而其他网站则必须在 Live 模式下使用。

因此,我需要在运行时而不是在 web.config 中设置配置(模式、clientId 和密码)。

问题是我的应用程序没有将模式更改为实时或沙盒。它继续使用 web.config 设置。

我创建了一个小型控制台应用程序来测试。

        static void Main(string[] args)
    {
        Console.WriteLine("Testing Paypal");
        Console.WriteLine("Test");

        Console.WriteLine(TestPaypal(true, "testClientId", "testSecret"));

        Console.WriteLine("Live");
        Console.WriteLine(TestPaypal(false, "myLiveClientId", "myLiveSecret"));

        Console.ReadLine();
    }

    public static string TestPaypal(bool isTest, string clientId, string secret)
    {
        try
        {
            var config = new Dictionary<string, string>
            {
                {"mode", isTest ? "sandbox" : "live"}
            };
            var accessToken = new OAuthTokenCredential(clientId, secret, config).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            var payment = Payment.Create(apiContext, new Payment
            {
                intent = "sale",
                payer = new Payer {payment_method = "paypal"},
                transactions = new List<Transaction>
                {
                    new Transaction
                    {
                        description = "Test via Console app",
                        invoice_number = Guid.NewGuid().ToString(),
                        amount = new Amount
                        {
                            currency = "EUR",
                            total = "100.00"
                        }
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = "http://www.google.com",
                    cancel_url = "http://www.google.com"
                }
            });
            var url = payment.links.Single(o => o.rel == "approval_url");
            return url.href;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

我的 app.config 设置如下所示

<paypal>
    <settings>
        <add name="mode" value="sandbox" />
        <add name="clientId" value="xxx" />
        <add name="clientSecret" value="xxx" />
    </settings>
</paypal>

对于代码中的两个请求,它一直使用 app.config 中的 de sandbox 设置。在这种情况下,我得到测试的正常结果和实时的错误(401 未授权)。 当我更改 app.config(生存模式)时。我收到 Testcall 的 401 和 Live 的成功结果。

所以,显然,我的两个凭据都是正确的,但模式在运行时不会改变。

有人知道为什么吗?

非常感谢!

经过数小时的研究,我自己找到了答案:

当然,我们还需要在 ApiContext 上设置配置,而不仅仅是获取 accesToken 对象。

创建 ApiContext 的行已更改为此,现在可以使用了

var apiContext = new APIContext(accessToken){Config = config};