djangopython-3.xpostpython-requestspayu

Python requests POST don't contain all sended data


I'm trying to create new order on PayU, via their REST api. I'm sending "get access token", and i have correct answer. Then i send 'create new order', aaaaand i ve got 103 error, error syntax.

I was trying on https://webhook.site/ , and realized why syntax is bad - i have no values in list.

Code of sending POST, when creating new order:

data = {
    "notifyUrl": "https://your.eshop.com/notify",
    "customerIp": "127.0.0.1",
    "merchantPosId": "00000",
    "description": "RTV market",
    "currencyCode": "PLN",
    "totalAmount": "15000",
    "products": [{
                "name": "Wireless mouse",
                "unitPrice": "15000",
                "quantity": "1"}]}

headers = {
"Content-Type": "application/json",
"Authorization": str('Bearer ' + access_token).encode()}

r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
                   data=payload,
                   headers=headers)
return JsonResponse(r.json())

Webhooc show what i have posted:

customerIp=127.0.0.1&notifyUrl=https%3A%2F%2Fyour.eshop.com%2Fnotify&currencyCode=PLN&products=name&products=unitPrice&products=quantity&description=RTV+market&merchantPosId=00000&totalAmount=15000

There is no values of 'name', 'unitprice' and 'quantity'. PayU confirmed thats the only problem.

Why? What is wrong?

Sending simple POST request to get a token is always successful.


Solution

  • If you want to send JSON, use the json argument of post():

    r = requests.post('https://webhook.site/9046f3b6-87c4-4be3-8544-8a3454412a55',
                       json=payload,  # Use the json argument
                       headers=headers)
    

    Otherwise the data will be sent as form-encoded data, which I guess isn't what you want, given you're expecting to send the nested products list.

    When you use the json argument, the content type is automatically set to application/json so you don't have to set it yourself.

    headers = {
        # Content-Type not required
        "Authorization": str('Bearer ' + access_token).encode()
    }
    

    Further info on using requests to send JSON here