Giter VIP home page Giter VIP logo

python-shopee's Introduction

pyshopee v1.4.0

PyPI GitHub Depfu

Shopee Partners API - python implementation

This is Python implementation for the Shopee Partner REST API.

If you came here looking for the Shopee seller center, to shoping, then go here.

$ pip install pyshopee

Example for using pyshopee2 (Latest)

  • change pyshopee.Client to pyshopee.Client20
import pyshopee

client = pyshopee.Client20( shopid, partnerid, API_key )

# get_order_by_status (UNPAID/READY_TO_SHIP/SHIPPED/COMPLETED/CANCELLED/ALL)
resp = client.order.get_order_by_status(order_status="READY_TO_SHIP")
print(resp)


# shop authorize and cancel_authorize url
authorize_url = client.shop.authorize(redirect_url="https://shopee.tw")
print(authorize_url)

cancel_authorize_url = client.shop.cancel_authorize(redirect_url="https://shopee.tw")
print(cancel_authorize_url)

Example for using pyshopee (old)

import pyshopee

client = pyshopee.Client( shopid, partnerid, API_key )

# get_order_by_status (UNPAID/READY_TO_SHIP/SHIPPED/COMPLETED/CANCELLED/ALL)
resp = client.order.get_order_by_status(order_status="READY_TO_SHIP")
print(resp)


# shop authorize and cancel_authorize url
authorize_url = client.shop.authorize(redirect_url="https://shopee.tw")
print(authorize_url)

cancel_authorize_url = client.shop.cancel_authorize(redirect_url="https://shopee.tw")
print(cancel_authorize_url)

Features

  • Simple, reliable, and elegant.
  • No need to generate authentication and timestamps by yourself, the wrapper does it for you.
  • Module format functionality the same as shopee officail document.
  • Good Response exception handling !

6 main parts of implementation

1. Shop Management Module : Shop / ShopCategory

2. Orders Management Module : Orders

3. Logistics Management Module : Logistics

4. Products Management Module : Item / Image / Discount

5. RMA Management Module : Returns

6. Collection Management Module: toppicks

Installation

  1. pip install from pypi
$ pip install pyshopee
  1. clone the repository to your local folder
$ cd pyshopee
$ python setup.py install

Quick Start

Import pyshopee & get order by status

import pyshopee

client = pyshopee.Client( shopid, partnerid, API_key )

# get_order_by_status (UNPAID/READY_TO_SHIP/SHIPPED/COMPLETED/CANCELLED/ALL)
resp = client.order.get_order_by_status(order_status="READY_TO_SHIP")
print(resp)

Get order list

# get_order_list
resp = client.order.get_order_list(create_time_from = 1512117303, create_time_to=1512635703)
print(resp)

Get order detail

'''
ordersn_list , type: String[]    
The set of order IDs. You can specify, at most, 50 OrderIDs in this call.
'''
# get_order_detail
ordersn_list = [ '1712071633982A7','1712071632981JW','171207163097YCJ']
resp = client.order.get_order_detail(ordersn_list = ordersn_list )
print(resp)

Get order escrow detail

'''
ordersn , type:String [] 
Shopee's unique identifier for an order.
'''
# get_order_escrow_detail
ordersn = '1712071633982A7'
resp = client.order.get_order_escrow_detail(ordersn = ordersn)
print(resp)

Advance Details for others functions

# usage
client.[type].[function name]

[type]
  - Shop
  - ShopCategory
  - Orders
  - Logistics
  - Item
  - Image
  - Discount
  - Returns

Advance parameters you must want to know

Timeout

You can find the source code in client.py, and pyshopee have a timeout params in there. Hence, every execute funtion can add an extra timeout setting, depending on your choice.

def execute(self, uri, method, body=None):
    ''' defalut timeout value will be 10 seconds
    '''
    parameter = self._make_default_parameter()

    if body.get("timeout"):
        timeout = body.get("timeout")
        body.pop("timeout")
    else:
        timeout = 10 

    if body is not None:
        parameter.update(body)

    req = self._build_request(uri, method, parameter)
    prepped = req.prepare()
    
    s = Session()
    resp = s.send(prepped, timeout=timeout)
    resp = self._build_response(resp)
    return resp

For example, we can set the timeout as 20 seconds in the execute requests(default value is 10s).

ordersn = '1712071633982A7'
resp = client.order.get_order_escrow_detail(ordersn = ordersn, timeout=20)
print(resp)

Add Item Example

For more details on how to add item via pyshopee, please take a look on folder "example/add.py"

Developer Note

  • From Aug, 2018 ShopeePartnerAPI will change the original apply mechanism.
    Please replace with your valid parameter(shopid,partnerid,token etc.)before sumbitting the call.

  • To get started, please check the Developer Guide under Documentation - Overview - Developer Guide
    on how to become a developer and utilize Shopee OpenAPI services.

  • Apply Authority Route:

    1. Apply Developer Authority
    2. Develper Authentication
    3. Build New App's Token
    4. Developing and Testing
    5. Seller Authority

About testtools platform

  • The default parameters are dummies except the PartnerID and Partner Key dedicated to your APP.
    Please replace with your valid parameter(shopid etc.) before sumbitting the call.
  • The testtools is based on PRODUCTION environment, please apply your PRODUCTION credential and parameters The "Request" and "Sign" tab aim to assist developer on verifying the authentication signature of API calls

Note

Source code
https://github.com/JimCurryWang/pyshopee

pypi
https://pypi.org/project/pyshopee

Shopee Parter API Documentation
https://partner.test.shopeemobile.com/docs/

Registration for Shopee Partner API usage
https://docs.google.com/forms/d/e/1FAIpQLSeCSsRHQSoQvZccOSHIl5DZAPIkSnS4ivN0Z6rp6N7JIoofvQ/viewform?c=0&w=1

python-shopee's People

Contributors

henrique-miranda avatar jimcurrywang avatar jingzhaoyang avatar thammachet avatar tjengbudi avatar vinhluan avatar yuniiiichen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-shopee's Issues

Hi, I have some question about token cached.

Hi, I have a question about token cached. as we know, The access/refresh_token has an expiration date, do u use redis or other in token cached? such as if token has expired, program will listen to the expired information of Redis and then update the token with refresh_token.

Invalid Token when authorize URL

Hello, i'm a newbie and want to try to create app based on shopee api.

Can i get more explanation on this code?
client = pyshopee.Client( shopid, partnerid, API_key )

i fill the shop id, partnerid, API_KEY based on Sandbox and Test Shop Info on shopee open platform. Then i try to get auth_url with this code:

authorize_url = client.shop.authorize(redirect_url="https://myurl.com")
print(authorize_url)

Try to direct to authorize_url but it return like this:
{"error":"error_auth","msg":"Invalid token","request_id":"394de2e020be7f5074a488b3b27bbcce"}

Which part i got wrong? Thanks before

Feature - Support Unlist as New Upload Item Status - 19-06-25

The recent significant API updates

Support Unlist as New Upload Item Status

  • Optimized APIs: item.Add
  • New Request Field: status

Item.Add

Name Type Sample Required Description
status String NORMAL no Use this field to indicate the initial status of the new item. Value can be one of 'NORMAL' or 'UNLIST'.

Good news. Especially for beginners.

Hello. Good news

I use pyshopee2 on a daily basis to manage my products.
My day job has nothing to do with programming and I am at a beginner level.
I am doing my research one by one, and I am happy to report that ### I have reached a turning point in my career.eer.

I posed this question to chatGPT

I'm currently using an external API called pyshopee2 to work with the shopeeAPI.
How can I use this to change product prices?
Here is the page about pyshopee2 product.
https://github.com/JimCurryWang/python-shopee/blob/master/pyshopee2/product.py

AI then replied with this

We will explain how to use the pyshopee2 library you specified to work with the Shopee API to perform product price changes.
Please follow these steps

Install the pyshopee2 library using the pip install pyshopee2 command.

Create a Shopee developer account and obtain an API key; create an account on the Shopee Developers portal (https://developers.shopee.com/) and obtain an API key when you create your application.

Import the python script to use the python script to import the pyshopee2 library.

from pyshopee2 import ShopeeShop, PartnerConfig

Create a ShopeeShop object and connect it to the Shopee API. Use the following code to specify the API key and store ID.

config = PartnerConfig(partner_id=YOUR_PARTNER_ID, partner_key=YOUR_PARTNER_KEY)
shop = ShopeeShop(config, shopid=YOUR_SHOP_ID)

Change the price of an item, the product.py file has a method update_item_price that can be used to update the price.

item_id = YOUR_ITEM_ID
new_price = 1000 # new price

# Update the price of the item
shop.product.update_item_price(item_id, new_price)

In the above code, item_id is the ID of the item to be changed and new_price is the new price. by calling the update_item_price method, the price of the item can be changed.

In this way, the pyshopee2 library can be used to change the price of an item.

However, be sure to properly protect your API key and other authentication information, and be careful about security when using it.

Note that the version and specifications of the pyshopee2 library may change, so please refer to the official repositories and documentation for the latest information.

This is as wonderful as a posting from God to me.

I haven't checked out the pros and cons of the "I'm not sure if this is a good idea or not, but from a quick glance, it looks like it will work properly.

For those of you who are stumped as I am, chatGPT will be a powerful ally for you.

Thank you.

I can't change item stocks

I would like to ask a question about the my post.

I would like to reduce the inventory count of an item that is already on the market to 0.
The hope is not to delete the item, but only to set the inventory count to 0.

I have created a program in Python as follows, but it does not work.
What is the cause?
I am using "update_stock" in product at pyshopee2
Please let me know if there is another way to easier.

I would like to ask for your help.
Thanks.

for IDs in item_id : # IDs = item ID is assigned
  admin_SG.product.update_stock(item_id=IDs,stock_list=[{'normal_stock':0}])


def update_stock(self, **kwargs):
        """
        Update stock.

        :param kwargs:
        - item_id Required
        - stock_list Required
            - model_id
            - normal_stock Requested

        """
        return self.client.execute("product/update_stock", "POST", kwargs)

About Chat API permission request.

Hi,

In this issue isn't problem about this Lib but I want to ask is anyone have send request to use chat permission? I send it 3 times but shopee open platform is reject me every time I want a guide for request that permission in official docs is hard to understand it. Thank you.

PS. If anyone have community or group for discuss about shopee open platform please let me know I want to be a part of community. Thank you.

getting code for token request

Every time, when getting a code, the program will pop up firefox for authentication with username and password.
Then, use that code to get a token.
From API Docs, the coding has 10 minutes lifetime.
That means we have to request a new code every 10 mins.
How could it be automatic if we have to manually fill in username and password for every 10 mins in the browser?

Information that can be edited in individual items

Please let me know if I'm super new to this.
I am going to use pyshopee to modify my item information.
Can I update the following information?

Condition of the item: new or used
Brand name: ex)No Brand
Remove from the list when stock is gone.

I'm new to python itself and I don't know how to write code, so it would be great if you could post some examples.
Thanks.

Feature - Significant OpenAPI Updates - 19-06-03

Dear Developer,

Please see below for the recent significant API updates:

Variation Image
Optimized APIs: InitTierVariation, GetVariation

Category Tree L3 to L5
Optimized APIs: GetCategories, GetCategoriesByCountry, GetAttributes

Boost Item Listing
New APIs: BoostItem, GetBoostedItems

[TW] Credit Card Installment
New API: SetItemInstallmentTenures

Optimized API: GetShopInfo

New response field: installment_status

Optimized APIs: GetItemList & GetItemDetail

New response field: tenures

[TW] Support 12 Images for Shopee Mall
Optimized APIs: Item and image related APIs

[TW] Attributes Length Restriction Removal
Optimized APIs: item.Add & item.UpdateItem

GetAirwayBill Error Msg Optimization
Optimized API: GetAirwayBill

Return Buyer Cancel Reason
Optimized API: GetOrderDetail

[ID] Validate If Dropship is Enabled Before Returning Dropshipper Info
Optimized API: GetOrderDetail

[OpenPlatform] Allow Developer to Edit Contact Email to Receive Platform Email
OpenPlatform: User Profile

Can't upload image in version 2.0

Has anyone successfully uploaded an image in the media space? Shopee's API doc is currently vague and incomplete. I've tried posting with the image's URL and binary code (see sample code below). Even the api test tool is showing the same error message.

Code 1:

headers = {'Content-Type': 'application/json'}
url = "https://partner.test-stable.shopeemobile.com/api/v2/media_space/upload_image?partner_id=%s&shop_id=%s&timestamp=%s&access_token=%s"
body = {'image': 'https://cdn.shopify.com/s/files/1/0361/1738/1164/products/bcb5f0e09d312e2d849b3299ea2af01a.jpg?v=1619836687'}
response = requests.post(url, json=body, headers=headers)

Code 2:

headers = {'Content-Type': 'image/jpeg'}
url = "https://partner.test-stable.shopeemobile.com/api/v2/media_space/upload_image?partner_id=%s&shop_id=%s&timestamp=%s&access_token=%s"
body = {'media': open('test.jpg', 'rb')}
response = requests.post(url, files=body, headers=headers)

print(response)
{'error': 'prodct.error_param', 'message': "can't find image file", 'warning': '', 'request_id': '354d1e0b625c3db6f2c12e25196dcb1c'}

We want to include all mandatory attributes.

Hey everyone.

With the recent update, the required fields have changed depending on the category.
I would like to add attributes.

For example, for action figures in the Philippines (category no. 101386), "Brand" and "Bundle Set" are required.

My current settings are as follows: I can set the Brand, but I can't set the Bundle Set properly.
Please let me know the correct code.

            attributesPH = [{
                "attributes_id" : 0,
                "value" : "NoBrand",
                ********************* ← I want to know how to set up the {"Bundle Set" : "No",}
            }]

Thank you all for your help.

push mechanism

is this library support push notification shopee?
if yes any examplea about it. have a little research and found nothing?

if not, any plan to support it?

How to set a discount when listing an item

Hi,
I would like to set a discount on an item when I list it for sale.

product_data = {
"category_id": ,
"name": ,
"description": ,
"price": ,
"stock": ,
"weight": ,
"images": ,
"logistics":,
"condition":,
"item_sku":,
}

What param do I need to add?

AttributeError: 'Item' object has no attribute 'unlist'

I've been trying out this pyshopee lib that works great so far. It works well for me the retrieve listing from shopee.

When I want to try the unlist function, I stucked here, it looks with the following error.

-- my code --
client = pyshopee.Client( shopid, partnerid, API_key )
unlist_items = "{ [ "item_id" : 1679064428, "unlist" : True ] }"
client.item.unlist(unlist_items)


AttributeError: 'Item' object has no attribute 'unlist'

Could you provide a sample how this part should be coded or whatever?
Many thanks.

Error accessing pyshopee in Python 2.7.12

I have installed pyshopee in my machine. It has installed successfully without any error.
While import the pyshopee, Im getting below error.

Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import pyshopee
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/pyshopee/init.py", line 3, in
from .client import Client
File "/usr/local/lib/python2.7/dist-packages/pyshopee/client.py", line 40
class Client(object, metaclass=ClientMeta):
^
SyntaxError: invalid syntax

read time out

Hey Jim,

We are getting these errors, I know it might not relate to the library. But I am wondering if you are getting these as well?

Any idea why this is happening?

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 799, in perform_job
    rv = job.perform()
  File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 600, in perform
    self._result = self._execute()
  File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 606, in _execute
    return self.func(*self.args, **self.kwargs)
  File "/app/agilascout_api/clock_helpers/shopee_logistics.py", line 70, in sync_logistics_shopee
    logistics = logistic.get_logistic_message(shop_id, partner_id, secret_key, ordersn=row.order_id)
  File "/app/agilascout_api/shopee_client/logistic.py", line 6, in get_logistic_message
    return client.logistic.get_logistic_message(**kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/pyshopee/logistic.py", line 46, in get_logistic_message
    return self.client.execute("logistics/tracking", "POST", kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/pyshopee/client.py", line 140, in execute
    resp = s.send(prepped, timeout=10)
  File "/app/.heroku/python/lib/python3.6/site-packages/raven/breadcrumbs.py", line 341, in send
    resp = real_send(self, request, *args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/requests/adapters.py", line 529, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='partner.shopeemobile.com', port=443): Read timed out. (read timeout=10)

ConnectTimeout: How many requests per second are there?

Hi team,
I am developing a data pipeline to collect sale data from Shopee with python-shopee.
The problem is that the request is frequently timeout even I set the timeout up to 20-30s.
I search for the number of requests per second from Shopee API documents, but cannot find any info related to this.

Anyone have ideas to deal with this? It is about me or server side?

無法使用api2.0

王先生你好
非常感謝你為我們特地開發蝦皮api的供大家使用。

  1. 不過經過指令pip install pyshopee安裝的套件,在lib/site-packages沒有pyshopee2,請問我應該要另外把這個資料夾clone下來放還是我的安裝過程有誤呢?
  2. 我想請問pyshopee2和pyshopee的相依套件是一樣的嗎?因為我在requirements.txt看是空白的

謝謝

Hotfix - Server-side issue - JSONDecodeError

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

JSONDecodeError can happen when requests have an HTTP error code like 404 and try to parse the response as JSON

How to use the interface of SHOPEE 2.0

After "pip install pyshopee" is installed, it is still the interface of API 1.0. If I want to use the interface of SHOPEE 2.0, what should I do? thank you very much!

Hotfix - pyshopee.Client

Client object cannot be initialized. Cannot get second shop's info if that shop is not authorized.

Test Shops

Hello does this api works on test shops/ sandbox environment?

Thanks.

[Important] Obsolete Logistics API Termination - 19-07-24

#19 [Important] Obsolete Logistics API Termination

Dear Developer,

Given the needs to streamline our callflow of the core API modules, please note the following three obsolete logistics APIs will be officially terminated on Dec 30th, 2019:

logistics.GetTrackingNo: https://partner.shopeemobile.com/api/v1/logistics/tracking_number/get_mass

logistics.SetTrackingNo: https://partner.shopeemobile.com/api/v1/logistics/tracking_number/set_mass

logistics.SetLogisticStatus: https://partner.shopeemobile.com/api/v1/logistics/offline/set

Alternatively, we have already provided a complete set of APIs for order fulfillment and you can find the callflow instruction at: https://open.shopee.com/documents?module=63&type=2&id=54 ([New & Optional] Arrange Shipment & Get TrackingNo & Print AirwayBill)

This set of APIs are available in sandbox(UAT) and live environment thus you can start your development and testing anytime if you haven't implemented them yet.

If you have any concern, please let your Shopee OpenAPI counterpart know.

Thank you.

Feature - Significant OpenAPI Updates - 19-07-12

Dear Developer,

Please see below for the recent significant API updates:

  • New Features

Push Mechanism- Push Shopee Updates URL
More instruction details: https://open.shopee.com/documents?module=63&type=2&id=55

Push Mechanism- Push Banned Listings
More instruction details: https://open.shopee.com/documents?module=63&type=2&id=55

GetReturnDetails
New API

[TW]Support 2-tier Variation
Optimized APIs: item.InitTierVariation, item.AddTierVariation, item.GetVariations, item.UpdateTierVariationList, item.UpdateTierVariationIndex

[VN] Add Discount Restrictions
Optimized APIs: AddDiscount, AddDiscountItem, UpdateDiscount, UpdateDiscountItems

  • Bugs Fixed

[OpenPlatform]SG test shop encounters password error in sandbox environment

New OpenAPI Release

There have significant openAPI updates that seems not included in the latest version.

  • payment.GetPaymentList : fetch the supported payment method list by country

open platform 2.0

looks like today shopee update they platform api to v2.0
the v1.0 still can used. but is there any chance to support this new api?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.