Using Python, how do I make a request to the shopee API to get a list of products on offer with my affiliate link

720 Views Asked by At

Using Python, how do I make a request to the shopee API to get a list of products on offer with my affiliate link?

I've made several scripts, but they all have a signature issue or unsupported authentication attempt. Does anyone have a working example of how to do this?

Below are two code examples I made, but they don't work.

Query: productOfferV2 and shopeeOfferV2 code1:

import requests
import time
import hashlib

appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'

# Set the API endpoint URL
url = "https://open-api.affiliate.shopee.com.my/graphql"

payload = """
  {
  "query": "query Fetch($page:2){
    productOfferV2(
      listType: 0, 
      sortType: 2,
      page: $page,
      limit: 50
    ) {
      nodes {
        commissionRate
        commission
        price
        productLink
        offerLink
      }
    }
  }",
  "operationName": null,
  "variables":{
    "page":0
    } 
  }
  """
payload = payload.replace('\n', '').replace(':0', f':{2}')
timestamp = int(time.time())
factor = appID+str(timestamp)+payload+secret
signature = hashlib.sha256(factor.encode()).hexdigest()
# Set the request headers
headers = {
    'Content-type': 'application/json',
    'Authorization': f'SHA256 Credential={appID},Timestamp={timestamp},Signature={factor}'
}

# Send the POST request
response = requests.post(url, payload, headers=headers)

data = response.json()
print(data)

return  = error-invalid-signature-python

code2:

import requests
import json
import hmac
import hashlib

appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'

query = '''query { productOfferV2(item_id: ALL) { 
  offers {
    shop_id
    item_price
    discount_price
    offer_id
    shop_location
    shop_name
  }
}
}'''

def generate_signature(query, secret):
    signature = hmac.new(secret.encode(), query.encode(), hashlib.sha256).hexdigest()
    return signature

signature = generate_signature(query, secret)

url = 'https://open-api.affiliate.shopee.com.my/graphql'

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer ' + appID + ':' + signature
}

payload = {
    'query': query
}

response = requests.post(url, data=json.dumps(payload), headers=headers)

data = response.json()

print(data)
0

There are 0 best solutions below