pythondjangoxmlbraintree

Braintree Client token generate method throws an XML error inside Django


I am using the below code to generate Client Token from the braintree gateway inside my payment View in Django.

def generate_token(request,id,token):
    if not validate_user_session(id,token):
        return JsonResponse({"error":"Invalid session"})


    gateway = braintree.BraintreeGateway(
    braintree.Configuration(
    braintree.Environment.Sandbox,
    merchant_id="xxxxxxxxxx",
    public_key="xxxxxxxxxxxx",
    private_key="xxxxxxxxxxxxxxxxxxxxxx"
    )

    print(gateway.client_token.generate())
    return JsonResponse({"clientToken":gateway.client_token.generate(), "success":True})

This throws an error

xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 0

However, the code works fine outside Django and in Python Shell and generates the token successfully. I don't seem to understand what is the issue ? The Ids and tokens are same in both the cases. Any help is appreciated.


Solution

  • As it turns out, Braintree has some issues with latest python versions . So making these changes solved the issue for me .

    In file (or wherever braintree is installed)

    /.local/share/virtualenvs/django_backend-ctIb9mpQ/lib/python3.8/site-packages/braintree/util/http.py line:125

    Replacing the code

    return [response.status_code, response.text]
    

    with

    ver = sys.version_info
    
    if ver.major == 3 and ver.minor > 5:
        return [response.status_code, response.content]
    else:
        return [response.status_code, response.text]
    

    solves this issue inside django.