Search code examples
httpc#-3.0blazor-webassemblyadyen

Read Adyen CreateCheckoutSessionResponse object as json string


My app is a Blazor Web Assembly client .net server... I am calling my server (succesfully) to create a 'CreateCheckoutSessionResponse' object and return it to the client. Looking at the browser, the response is a json coded string. This is from the debug preview tools in the chrome browser, looking at the response.. which seems fine: Chrome Browser Preview

Initially, I tried to just bring this into a CreateCheckoutSessionResponse object in the client service that calls the server:

            public async Task<CreateCheckoutSessionResponse> GetAdyenPaymentSessionAsync(string userId, decimal amount)
            {
                AdyenSessionRequestDTO request = new AdyenSessionRequestDTO(userId: userId, currencyCode: "GBP", amount);
                var response = await _http.PostAsJsonAsync(Routes.GetAdyenSessionRoute, request);
                CreateCheckoutSessionResponse? res = await response.Content.ReadFromJsonAsync<CreateCheckoutSessionResponse>();
                return res;
            }

But, to instatiate the drop-in, I need to pass this session response as Json. The CreateCheckoutSessionResponse oject has a '.ToJson()'

So the complete call looks like this:

        AdyenSessionResponse = await _transactionService.GetAdyenPaymentSessionAsync(_userService.CurrentUser.Id, CreditWanted);
        AdyenSession = AdyenSessionResponse.ToJson();
        await _JS.InvokeVoidAsync("setAdyenCheckoutConfiguration", AdyenSession, _transactionService.AdyenPublicClientKey);

I haven't really been able to get as far as debugging the javascript to see if the dropin gets instatiated, because the CreateCheckoutSessionResponse seems to be corrupted when operated on '.ToJson'.

Error message from the JS function

This is the object after '.ToJson' loaded into a VSCode json view page:

'{\n  "channel": "Web",\n  "amount": {\n    "currency": "GBP",\n    "value": 0\n
    },\n  "countryCode": "NL",\n  "expiresAt": "2023-03-31T12:06:39+01:00",\n  "lineItems": [\n    {\n      "amountExcludingTax": 0,\n      "amountIncludingTax": 0,\n      "description": "Site Credit",\n      "quantity": 1,\n      "taxAmount": 0,\n      "taxPercentage": 0\n
        }\n
    ],\n  "merchantAccount": "RedRocksTechnologyLtdECOM",\n  "reference": "000000113",\n  "returnUrl": "/redirect?orderRef=000000113",\n  "sessionData": "Ab02b4c0!B…c41T7F8gRuFdA/gf8NaFUV5OrVDhhMpKKaQp5ntwqhCmir9tvpqT+/z8/BsrrxmaseRwD06DHDbgtlqM40QV8IXV7kw7uIsoZVX8A9Ce+mAROdLvmQhrYZRX1psj0bZTWN/2fkiqTQhNHt6fYvBfZu0sTmhDiSt4f+E9TRjjChCFVeIU4iL7SLbh+3vVoIKWLxon7+DfImyPxrSNKrPDH18s+O4Ak1d5MyJYjrRXPSlrUxboI5Yfh6wLYDUrgvOpLR+sOBoL5bSqsOMX3FFKk8d6vbaRRaN2olMVqbHO7KYxJ/sKbKDoyDfTpeR/CojQSSabA4a45Ot7vMtPVhRy4eKfk4zWijeJSYC7ku0jK6ke9tJpIbUNaEYb3bthhgsc1ryYf8Ufz",\n  "shopperLocale": "en-US",\n  "splitCardFundingSources": false,\n  "threeDSAuthenticationOnly": false\n
}'

Which to be honest, doesnt look very much like good json...

So, I thought maybe a different approach... Rather than use the 'CreateCheckoutSessionResponse' object, I'll try to read the json, straight out of the http response.. Chenged the the functions to this:

             public async Task<string> GetAdyenPaymentSessionAsync(string userId, decimal amount)
            {
                AdyenSessionRequestDTO request = new AdyenSessionRequestDTO(userId: userId, currencyCode: "GBP", amount);
                var response = await _http.PostAsJsonAsync(Routes.GetAdyenSessionRoute, request);
                string? jsonresponse = await response.Content.ReadAsStringAsync();
                int length = jsonresponse.Length; // For Debugging

                return jsonresponse;
            }

Which I think should just return the raw string.. right? But when I do that, I am losing a lot of the information...

'{
    "channel": 3,
    "recurringProcessingModel": null,
    "shopperInteraction": null,
    "accountInfo": null,
    "additionalAmount": null,
    "additionalData": null,
    "allowedPaymentMethods": null,
    "amount": {
        "currency": "GBP",
        "value": 0
    },
    "applicationInfo": null,
    "authenticationData": null,
    "billingAddress": null,
    "blockedPaymentMethods": null,
    "captureDelayHours": null,
    "company": null,
    "countryCode": "NL",
    "dateOfBirth": null,
    "deliverAt": null,
    "deliveryAddress": null,
    "enableOneClick": null,
    "enablePayOut": null,
    "enableRecurring": null,
    "expiresAt": "…WMF4620wYAkhfLNzoDj2DP2NBpYUjm8gP0DY6MOTlcb0omHNkf7gQADv6eZMCq6tw+KQKtN8+XtAwCWQYdgrE7G+dj1KW0vlKPKJzv7dOloB8m/vXpkhZFBlfej0uTHJ0ir9BOoxKYjRv6mh3+e4VZeVjjsCfIrW8kfgYbnZ/ERb0Q==",
    "shopperEmail": null,
    "shopperIP": null,
    "shopperLocale": "en-US",
    "shopperName": null,
    "shopperReference": null,
    "shopperStatement": null,
    "socialSecurityNumber": null,
    "splitCardFundingSources": false,
    "splits": null,
    "store": null,
    "storePaymentMethod": null,
    "telephoneNumber": null,
    "threeDSAuthenticationOnly": false,
    "trustedShopper": null
}'

So I am losing something in the 'ReadAsString' functionality.

Any pointers where this could be going wrong? Thanks.


Solution

  • Ok, I think I solved it. The text is being decoded with UTF8 as a default.

            Stream? jsonresponse = await response.Content.ReadAsStreamAsync();
            string res;
            using (var reader = new StreamReader(jsonresponse, Encoding.ASCII))
            {
                res = reader.ReadToEnd();
            }
            return res;
    

    This returns the correct information.