Search code examples
pythoncurlurllib

Python 3 license checker with cURL error 404


Got a small python app that makes API requests for verification to gumroad, I'm trying to use urllib to do it however it is giving me a 404 error. The interesting thing is that the url works perfectly when using the requests package (import requests etc..) as opposed to urllib.

The cURL request I need to implement is as follows:

curl https://api.gumroad.com/v2/licenses/verify \
  -d "product_permalink=PRODUCT_PERMALINK" \
  -d "license_key=INSERT_LICENSE_KEY" \
  -X POST

It returns "success":true if the key is valid and some other stats.

Here is my code:

import json
import urllib.request

license_key = "yyyyyyyy-yyyyyyyy-yyyyyyyy-yyyyyyyy"
user_email = "xxxxx@xxxxx.com"

def licenseCheck(license_key, user_email, productID="xyzxy"):
    
    url_ = "https://api.gumroad.com/v2/licenses/verify"
    pf_permalink = productID
    params = json.dumps({'product_permalink=': pf_permalink, 'license_key=': license_key})
    data=params.encode()

    req = urllib.request.Request(url_, headers={'Content-Type':'application/json'})
    response = urllib.request.urlopen(req, data, timeout=10)
    get_response = json.loads(response.read())

    if get_response['success'] and get_response['email'].lower() == user_email.lower():
        status = True
    else:
        get_response = "Failed to verify the license."

    return status, get_response , license_key

print(licenseCheck(license_key, user_email))

The line where the program gives the 404 error is this:

response = urllib.request.urlopen(req, data, timeout = 10)

Solution

  • That happens because in your curl example you pass data as two POST parameters and in the python script you pass them as JSON body. Also, you need to think about error handling.

    import json
    from urllib import request, parse, error
    
    license_key = "yyyyyyyy-yyyyyyyy-yyyyyyyy-yyyyyyyy"
    user_email = "xxxxx@xxxxx.com"
    
    def licenseCheck(license_key, user_email, productID="xyzxy"):
        
        url_ = "https://api.gumroad.com/v2/licenses/verify"
        pf_permalink = productID
        params = {'product_permalink': pf_permalink, 'license_key': license_key}
        data=parse.urlencode(params).encode('ascii')
    
        req = request.Request(url_, data=data)
        try:
          response = request.urlopen(req)
          get_response = json.loads(response.read())
        except error.HTTPError as e: get_response = json.loads(e.read())
        
        status = False
        if get_response['success'] and get_response['email'].lower() == user_email.lower():
          status = True
        else:
          get_response = "Failed to verify the license."
    
        return status, get_response , license_key
    
    print(licenseCheck(license_key, user_email))