Hey there, fellow developer! Ready to dive into the world of e-commerce integration? Today, we're tackling the Shopee API with Python. This guide will walk you through creating a robust integration that'll have you managing products, orders, and inventory like a pro. Let's get cracking!
Before we jump in, make sure you've got:
Quick tip: Set up a virtual environment to keep things tidy. Trust me, your future self will thank you!
First things first, let's get you authenticated:
import hmac import hashlib import time def sign(secret, payload): return hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest() timestamp = int(time.time()) payload = f"{your_partner_id}{timestamp}" signature = sign(your_partner_key, payload)
Let's create a base client to handle our API calls:
import requests class ShopeeClient: BASE_URL = "https://partner.shopeemobile.com/api/v2" def __init__(self, partner_id, partner_key, shop_id): self.partner_id = partner_id self.partner_key = partner_key self.shop_id = shop_id def make_request(self, endpoint, method="GET", params=None, data=None): timestamp = int(time.time()) url = f"{self.BASE_URL}{endpoint}" payload = f"{self.partner_id}{timestamp}{self.shop_id}" signature = sign(self.partner_key, payload) headers = { "Content-Type": "application/json", "Authorization": signature } response = requests.request(method, url, headers=headers, params=params, json=data) return response.json()
Now for the fun part! Let's implement some key features:
def get_product(self, item_id): return self.make_request("/product/get_item_base_info", params={"item_id": item_id}) def add_product(self, product_data): return self.make_request("/product/add_item", method="POST", data=product_data)
def get_orders(self, time_from, time_to): params = { "time_from": time_from, "time_to": time_to, "page_size": 100 } return self.make_request("/order/get_order_list", params=params) def update_order_status(self, order_sn, status): data = { "order_sn": order_sn, "status": status } return self.make_request("/order/handle_buyer_cancellation", method="POST", data=data)
def get_stock(self, item_id): return self.make_request("/product/get_item_base_info", params={"item_id": item_id}) def update_stock(self, item_id, stock): data = { "item_id": item_id, "stock": stock } return self.make_request("/product/update_stock", method="POST", data=data)
Let's add some resilience to our code:
import time from requests.exceptions import RequestException def make_request_with_retry(self, *args, **kwargs): max_retries = 3 for attempt in range(max_retries): try: response = self.make_request(*args, **kwargs) if response.get("error"): raise RequestException(response["error"]) return response except RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff
Here's a quick example of how you might process and store order data:
import sqlite3 def process_orders(self, orders): conn = sqlite3.connect('shopee_orders.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS orders (order_sn TEXT PRIMARY KEY, status TEXT, create_time INTEGER)''') for order in orders: c.execute("INSERT OR REPLACE INTO orders VALUES (?, ?, ?)", (order['order_sn'], order['order_status'], order['create_time'])) conn.commit() conn.close()
Don't forget to test your code! Here's a simple unit test example:
import unittest class TestShopeeClient(unittest.TestCase): def setUp(self): self.client = ShopeeClient("partner_id", "partner_key", "shop_id") def test_get_product(self): response = self.client.get_product("1234567") self.assertIn("item", response) self.assertEqual(response["item"]["item_id"], "1234567") if __name__ == '__main__': unittest.main()
To take your integration to the next level:
aiohttp
for better performance.And there you have it! You've just built a solid foundation for a Shopee API integration. Remember, this is just the beginning - there's always room to expand and improve. Keep exploring the Shopee API documentation for more features you can add.
Happy coding, and may your integration be ever scalable!