djangocurlopayo

Integrating Sagepay (Opayo) with Django - How to create a merchant session key


I am trying to integrate Opayo (SagePay) with Django and I am having problems generation the merchant session key (MSK).

From sagepays docs they say to use the below curl request and that I should receive the key in the response

curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU="  \
-H "Content-type: application/json" \
-X POST \
-d '{
  "vendorName": "sandbox"
}'

I have tried to implement this in my Django view with the following code but I receive a 422 response (Unprocessable Entity response).

import requests

def BasketView(request): 
    headers = {
        "Authorization": "Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
        "Content-type": "application/json",
    }
    data = {"vendorName": "sandbox"}

    r = requests.post("https://pi-test.sagepay.com/api/v1/merchant-session-keys", headers=headers, params=data)
    print(r)

Any ideas where I may be going wrong with this?


Solution

  • You are passing the wrong parameter to requests.post() you should use jsoninstead of params:

    r = requests.post(
        "https://pi-test.sagepay.com/api/v1/merchant-session-keys",
        headers=headers,
        json=data
    )
    

    By doing so, there is no need to specify the Content-Type header, it is added automatically.