# Buggy code
def get_checkout_url(order, currency=None, credentials=None):
    if not credentials:
        credentials = PayPalPaymentsManager.get_credentials(order.event)

    if not credentials:
        raise Exception("PayPal credentials have not be set correctly")

    if current_app.config["TESTING"]:
        return credentials["CHECKOUT_URL"]

    currency = (
        order.event.payment_currency
        if not currency and order.event.payment_currency != ""
        else "USD"
    )
    data = {
        "USER": credentials["USER"],
        "PWD": credentials["PWD"],
        "SIGNATURE": credentials["SIGNATURE"],
        "SUBJECT": credentials["EMAIL"],
        "METHOD": "SetExpressCheckout",
        "VERSION": PayPalPaymentsManager.api_version,
        "PAYMENTREQUEST_0_PAYMENTACTION": "SALE",
        "PAYMENTREQUEST_0_AMT": order.amount,
        "PAYMENTREQUEST_0_CURRENCYCODE": currency,
        "RETURNURL": make_frontend_url(
            path="/orders/{identifier}/payment/success".format(
                identifier=order.identifier
            )
        ),
        "CANCELURL": make_frontend_url(
            path="/orders/{identifier}/payment/cancelled".format(
                identifier=order.identifier
            )
        ),
    }

    count = 1

    if type(order) is Order:
        for ticket_order in order.order_tickets:
            data["L_PAYMENTREQUEST_" + str(count) + "_NAMEm"] = ticket_order.ticket.name
            data["L_PAYMENTREQUEST_" + str(count) + "_QTYm"] = ticket_order.quantity
            data["L_PAYMENTREQUEST_" + str(count) + "_AMTm"] = ticket_order.ticket.price
            count += 1

    response = requests.post(credentials["SERVER"], data=data)
    token = dict(urlparse.parse_qsl(response.text))["TOKEN"]
    order.paypal_token = token
    save_to_db(order)
    return (
        credentials["CHECKOUT_URL"]
        + "?"
        + urlencode({"cmd": "_express-checkout", "token": token})
    )


# Traceback (KeyError)
2017-08-17T11:24:19.730791+00:00 app[web.1]: Exception on /v1/orders [POST]
2017-08-17T11:24:19.730793+00:00 app[web.1]: Traceback (most recent call last):
2017-08-17T11:24:19.730794+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
2017-08-17T11:24:19.730794+00:00 app[web.1]:     response = self.full_dispatch_request()
2017-08-17T11:24:19.730795+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
2017-08-17T11:24:19.730796+00:00 app[web.1]:     rv = self.handle_user_exception(e)
2017-08-17T11:24:19.730797+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
2017-08-17T11:24:19.730800+00:00 app[web.1]:     return cors_after_request(app.make_response(f(*args, **kwargs)))
2017-08-17T11:24:19.730801+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
2017-08-17T11:24:19.730802+00:00 app[web.1]:     reraise(exc_type, exc_value, tb)
2017-08-17T11:24:19.730803+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
2017-08-17T11:24:19.730804+00:00 app[web.1]:     rv = self.dispatch_request()
2017-08-17T11:24:19.730804+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
2017-08-17T11:24:19.730805+00:00 app[web.1]:     return self.view_functions[rule.endpoint](**req.view_args)
2017-08-17T11:24:19.730806+00:00 app[web.1]:   File "/app/app/api/helpers/permissions.py", line 43, in decorator
2017-08-17T11:24:19.730806+00:00 app[web.1]:     return fn(*args, **kwargs)
2017-08-17T11:24:19.730807+00:00 app[web.1]:   File "/app/.heroku/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 32, in wrapper
2017-08-17T11:24:19.730808+00:00 app[web.1]:     return func(*args, **kwargs)
2017-08-17T11:24:19.730809+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/views.py", line 84, in view
2017-08-17T11:24:19.730809+00:00 app[web.1]:     return self.dispatch_request(*args, **kwargs)
2017-08-17T11:24:19.730810+00:00 app[web.1]:   File "/app/.heroku/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 68, in dispatch_request
2017-08-17T11:24:19.730811+00:00 app[web.1]:     response = method(*args, **kwargs)
2017-08-17T11:24:19.730812+00:00 app[web.1]:   File "/app/.heroku/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 56, in wrapper
2017-08-17T11:24:19.730812+00:00 app[web.1]:     return func(*args, **kwargs)
2017-08-17T11:24:19.730813+00:00 app[web.1]:   File "/app/.heroku/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 206, in post
2017-08-17T11:24:19.730813+00:00 app[web.1]:     result = schema.dump(obj).data
2017-08-17T11:24:19.730814+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/marshmallow/schema.py", line 525, in dump
2017-08-17T11:24:19.730815+00:00 app[web.1]:     original_data=obj)
2017-08-17T11:24:19.730815+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/marshmallow/schema.py", line 842, in _invoke_dump_processors
2017-08-17T11:24:19.730816+00:00 app[web.1]:     data=data, many=many, original_data=original_data)
2017-08-17T11:24:19.730817+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/marshmallow/schema.py", line 955, in _invoke_processors
2017-08-17T11:24:19.730817+00:00 app[web.1]:     data = utils.if_none(processor(data), data)
2017-08-17T11:24:19.730818+00:00 app[web.1]:   File "/app/app/api/schema/orders.py", line 27, in generate_payment_url
2017-08-17T11:24:19.730819+00:00 app[web.1]:     data['payment_url'] = PayPalPaymentsManager.get_checkout_url(order)
2017-08-17T11:24:19.730820+00:00 app[web.1]:   File "/app/app/api/helpers/payment.py", line 190, in get_checkout_url
2017-08-17T11:24:19.730820+00:00 app[web.1]:     token = dict(urlparse.parse_qsl(response.text))['TOKEN']
2017-08-17T11:24:19.730821+00:00 app[web.1]: KeyError: 'TOKEN'

# Fixed code
def get_checkout_url(order, currency=None, credentials=None):
    if not credentials:
        credentials = PayPalPaymentsManager.get_credentials(order.event)

    if not credentials:
        raise Exception("PayPal credentials have not be set correctly")

    if current_app.config["TESTING"]:
        return credentials["CHECKOUT_URL"]

    currency = (
        order.event.payment_currency
        if not currency and order.event.payment_currency != ""
        else "USD"
    )
    data = {
        "USER": credentials["USER"],
        "PWD": credentials["PWD"],
        "SIGNATURE": credentials["SIGNATURE"],
        "SUBJECT": credentials["EMAIL"],
        "METHOD": "SetExpressCheckout",
        "VERSION": PayPalPaymentsManager.api_version,
        "PAYMENTREQUEST_0_PAYMENTACTION": "SALE",
        "PAYMENTREQUEST_0_AMT": order.amount,
        "PAYMENTREQUEST_0_CURRENCYCODE": currency,
        "RETURNURL": make_frontend_url(
            path="/orders/{identifier}/payment/success".format(
                identifier=order.identifier
            )
        ),
        "CANCELURL": make_frontend_url(
            path="/orders/{identifier}/payment/cancelled".format(
                identifier=order.identifier
            )
        ),
    }

    count = 1

    if type(order) is Order:
        for ticket_order in order.order_tickets:
            data["L_PAYMENTREQUEST_" + str(count) + "_NAMEm"] = ticket_order.ticket.name
            data["L_PAYMENTREQUEST_" + str(count) + "_QTYm"] = ticket_order.quantity
            data["L_PAYMENTREQUEST_" + str(count) + "_AMTm"] = ticket_order.ticket.price
            count += 1

    response = requests.post(credentials["SERVER"], data=data)
    if "TOKEN" not in dict(urlparse.parse_qsl(response.text)):
        raise Exception("PayPal Token could not be retrieved")
    token = dict(urlparse.parse_qsl(response.text))["TOKEN"]
    order.paypal_token = token
    save_to_db(order)
    return (
        credentials["CHECKOUT_URL"]
        + "?"
        + urlencode({"cmd": "_express-checkout", "token": token})
    )