Hey there, fellow developer! Ready to dive into the world of e-commerce API integration? Today, we're tackling the Shopee API with Ruby. If you're looking to supercharge your e-commerce business or build some killer tools for Shopee sellers, you're in the right place. Let's get our hands dirty!
Before we jump in, make sure you've got:
httparty
in this guide)Got all that? Great! Let's roll.
First things first, we need to get authenticated. Shopee uses a combination of API key and signature for auth. Here's how to set it up:
require 'httparty' require 'openssl' class ShopeeClient BASE_URL = 'https://partner.shopeemobile.com/api/v2' def initialize(partner_id, partner_key, shop_id) @partner_id = partner_id @partner_key = partner_key @shop_id = shop_id end def generate_signature(path, timestamp) base_string = "#{@partner_id}#{path}#{timestamp}#{@partner_key}#{@shop_id}" OpenSSL::HMAC.hexdigest('SHA256', @partner_key, base_string) end end
Now that we're authenticated, let's make our first API call:
def get_shop_info timestamp = Time.now.to_i path = '/shop/get_shop_info' signature = generate_signature(path, timestamp) response = HTTParty.get( "#{BASE_URL}#{path}", query: { partner_id: @partner_id, timestamp: timestamp, sign: signature, shop_id: @shop_id } ) JSON.parse(response.body) end
Shopee's API is vast, but here are some endpoints you'll likely use often:
/product/add_item
, /product/get_item_list
/order/get_order_list
, /order/get_order_detail
/logistics/get_shipping_parameter
, /logistics/ship_order
Implement these similarly to our get_shop_info
method.
Shopee's API has rate limits, so let's add some retry logic:
def make_request(method, path, params = {}) retries = 0 begin # Your request logic here rescue => e retries += 1 if retries < 3 sleep(2 ** retries) retry else raise e end end end
Once you've got your data, you'll probably want to store it. Here's a quick example using ActiveRecord:
class Product < ActiveRecord::Base def self.create_from_shopee(shopee_product) create( shopee_id: shopee_product['item_id'], name: shopee_product['item_name'], price: shopee_product['price'] ) end end
Shopee can send you real-time updates. Set up a webhook endpoint in your app:
post '/shopee_webhook' do payload = JSON.parse(request.body.read) # Process the webhook payload status 200 end
Don't forget to test! Here's a simple RSpec example:
RSpec.describe ShopeeClient do it "fetches shop info successfully" do client = ShopeeClient.new(partner_id, partner_key, shop_id) result = client.get_shop_info expect(result).to have_key('shop_name') end end
To keep your integration speedy:
And there you have it! You're now armed with the basics of integrating the Shopee API with Ruby. Remember, this is just the beginning. As you build more complex integrations, you'll discover new challenges and opportunities. Keep exploring, keep coding, and most importantly, have fun with it!
Happy coding, and may your e-commerce ventures be ever prosperous! 🚀💎