Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions examples/alipay/main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import json

import httpx

from openapi.providers.alipay import Client

from examples.config import config

settings = config['alipay-prod2']
client = Client(**settings, is_sandbox=False)
settings = config['alipay-test']
client = Client(**settings, is_sandbox=True)
# client.add_webhook(config['openapi_webhook'])


Expand All @@ -18,23 +20,24 @@
# data={'bill_type': 'trade', 'bill_date': '2023-05'}
))
request_url = f'{client.API_BASE_URL}?{params}'
print(request_url)
response = httpx.get(request_url)
print(response.json())
# print(request_url)
# response = httpx.get(request_url)
# print(response.json())
# pc-pay
pc_pay_params = client.build_query_params(client.build_params(
'alipay.trade.page.pay',
{
'subject': 'popmart-molly',
'out_trade_no': 'pc1234567',
'total_amount': '0.01',
'product_code': 'FAST_INSTANT_TRADE_PAY'
'out_trade_no': 'pc12345678',
'total_amount': '100',
'product_code': 'FAST_INSTANT_TRADE_PAY',
'extend_params': json.dumps({'hb_fq_seller_percent': '100'})
},
notify_url='http://47.94.172.250:9527/api/v1/pay/alipay/',
return_url='http://47.94.172.250:9527/api/v1/pay/alipay/'
))
pc_pay_url = f'{client.API_BASE_URL}?{pc_pay_params}'
# print(pc_pay_url)
print(pc_pay_url)

# mobile-pay
mobile_pay_params = client.build_query_params(client.build_params(
Expand Down
Empty file added examples/kwai/__init__.py
Empty file.
49 changes: 49 additions & 0 deletions examples/kwai/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from openapi.providers.kwai import Client, Token

from examples.config import config

client = Client(
config['kuaishou']['app_key'],
config['kuaishou']['secret'],
config['kuaishou']['sign_secret'],
config['kuaishou']['message_key']
)


if __name__ == '__main__':
# 快手消息解密
print(client.decrypt('2FXtJpaJ1ftNz39omFhoWQ=='))
print(client.decrypt('jbaDDoPZu/61uO/SMXT2s/y5Jq1+ISvE1QSo1kGE/p8jxJwkTNrIYDjvmtAQlwYUaDiYBSQR+hCwJWx299xZyubTYLDgmzL45dIchVAOyqiSnqKJLwnaXU1+W0lsRfKnvuBQvQhd6ftubauZU0RfvvgpEli/qZug0WPZMahHqq7pym/16x4GbzSMy4NzSevZCuVvYNIHCYeGYj+DkR18hiyUj08nHm/9y+70lGjcwBp7KjQ92XjUX0hqteTTgr7rvSJC00xA9gV2XafJAKo7cvTI0NT56ivyh2sM/Jt+XA2zlB8GpdL2zoTnSZKBXFaM+LhsE2kNHYvlZnjbonq3JvuXSIBPXnt9DdEJgEXXg5pKju3RKLGrTDSmB1rVy7r7YnyobQ/r0w8N4sIUs3FEVlB4fAds9slOsr5kY3YwQ2DRxNmiubbpjfjipW3H2jtMmRPToKP/2BChl+P9KIZ41X1Xykldz/2vFVo87C0S4FkzXsCfQrMm7t4a4nx8ktmHIME9BW2ashkdM/AAlxK9Rwe0+F7GFJ7xHICQUBI8hVM='))

# 授权获取 Token
# client.request(
# 'get', '/oauth2/access_token',
# params={
# 'app_id': client.app_id, 'grant_type': 'code',
# 'code': '',
# 'app_secret': client.secret
# }
# )

client._token = Token(access_token=config['kuaishou']['test']['access_token'])
# 获取订单详情
result = client.request(
'get', '/open/order/detail', action='open.order.detail',
params={
'oid': 2421300093168518
}
)
print(result)
# 解密
result = client.request(
'post', '/open/order/desensitise/batch', action='open.order.desensitise.batch',
data={
'batchDesensitiseList': [
{
'encryptedData': result.data['orderAddress']['encryptedMobile'],
'bizId': 2421300093168518
}
]
}
)
print(result)
4 changes: 4 additions & 0 deletions examples/tanmarket/field_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@
{
'fieldId': '138623',
'alias': '大航海营期'
},
{
'fieldId': '144541',
'alias': '3天Python营'
}
]

Expand Down
3 changes: 3 additions & 0 deletions examples/taobao/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2024/1/8
29 changes: 29 additions & 0 deletions examples/taobao/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from openapi.providers.taobao import Client, calculate_signature
from examples.config import config

app_key = config['taobao']['app_key']
secret = config['taobao']['secret']

d = {
'app_key': app_key,
'method': 'taobao.trade.fullinfo.get',
'v': '2.0',
'timestamp': '2024-01-09 00:00:03',
'partner_id': 'top-apitools',
'session': '6100a040fa611a381b3cd37eca8a1c31df1ff56c6970e642212108025244',
'format': 'json',
'sign_method': 'md5',
'fields': 'tid,type,status,payment,orders,promotion_details',
'tid': '3725362658812595205'
}
print(calculate_signature(d, secret))

client = Client(app_id=app_key, secret=secret)
r = client.request(
'get', 'taobao.trade.fullinfo.get',
data={
'fields': 'tid,type,status,payment,orders,promotion_details',
'tid': '3725362658812595205'
}
)
print(r)
68 changes: 0 additions & 68 deletions examples/xhs/main.py

This file was deleted.

File renamed without changes.
94 changes: 94 additions & 0 deletions examples/xiaohongshu/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from datetime import datetime

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.hashes import MD5, Hash
from openapi.providers.xhs import Client

from examples.config import config

# print(config)
client = Client(
app_id=config['xhs']['app_id'], secret=config['xhs']['secret'],
user_id=config['xhs']['user_id'], seller_id=config['xhs']['seller_id']
)
client.add_webhook(config['openapi_webhook'])
order_id = config['xhs']['test']['order_id']

info = config['xhs']['test']['info']
info['expires_at'] = datetime.fromtimestamp(info['expires_at'] / 1000)

# r = client.request(
# 'post', '/ark/open_api/v3/common_controller',
# action='oauth.getAccessToken',
# data={
# 'code': config['xhs']['code']
# }
# )
# print(r)

# r = client.request(
# 'post', '/ark/open_api/v3/common_controller',
# action='order.getOrderDetail',
# data={
# 'orderId': order_id
# }
# )
# address_id = r.data['openAddressId']
# print(r)

# r = client.request(
# 'post', '/ark/open_api/v3/common_controller',
# action='order.getOrderReceiverInfo',
# data={
# 'receiverQueries': {
# 'orderId': order_id,
# 'openAddressId': address_id
# }
# }
# )
# print(r)
# client.make_token(**info)

# r = client.request(
# 'post', '/ark/open_api/v3/common_controller',
# action='data.batchDecrypt',
# data={
# 'baseInfos': [
# {
# 'dataTag': order_id,
# 'encryptedData': r.data['receiverInfos'][0]['receiverName']
# },
# {
# 'dataTag': order_id,
# 'encryptedData': r.data['receiverInfos'][0]['receiverPhone']
# },
# ],
# 'actionType': 2, 'appUserId': ''
# }
# )
# print(r)


r = client.request(
'post', '/ark/open_api/v3/common_controller',
action='common.getCategories', data={'categoryId': '5a310e243f7d1712823ba480'}
)
print(r)


def calculate_signature(params, api_key):
data = f'{params["path"]}?app-key={params["app-key"]}&timestamp={params["timestamp"]}'
h = Hash(algorithm=MD5(), backend=default_backend())
h.update(f'{data}{api_key}'.encode('utf-8'))
return h.finalize().hex()


sign = calculate_signature(
params={
'path': '',
'app-key': client.app_id,
'timestamp': '17033916261',
},
api_key=client.secret
)
print(sign)
74 changes: 74 additions & 0 deletions openapi/providers/kwai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import json
import time
import hmac
import hashlib
import base64
from typing import Optional
from Crypto.Cipher import AES

from openapi.enums import IntegerChoices
from openapi.providers.base import BaseClient, BaseResult, Token


def calculate_signature(params, secret):
sign_params = {
key: params[key]
for key in sorted(['access_token', 'appkey', 'method', 'param', 'signMethod', 'timestamp', 'version'])
if params.get(key)
}
sign_params['signSecret'] = secret
return base64.b64encode(hmac.new(
secret.encode(),
'&'.join(f'{k}={v}' for k, v in sign_params.items()).encode(),
hashlib.sha256
).digest()).decode()


class Code(IntegerChoices):
SUCCESS = 1, '成功'


class Result(BaseResult):
result: Optional[int]
error: Optional[str]
error_msg: Optional[str]


class Client(BaseClient):
NAME = '快手'
API_VERSION = 1
API_BASE_URL = 'https://openapi.kwaixiaodian.com'

def __init__(self, app_id, secret, sign_secret, message_key):
super().__init__()
self.app_id = app_id
self.secret = secret
self.sign_secret = sign_secret
self.message_key = message_key
self.codes = Code
self._token = Optional[Token]

def request(self, method, endpoint, action=None, params=None, data=None, token_request=False):
public_params = {}
if (params is not None or data is not None) and token_request is False:
public_params.update(**{
'appkey': self.app_id, 'timestamp': str(int(time.time() * 1000)),
'version': self.API_VERSION, 'method': action, 'signMethod': 'HMAC_SHA256'
})
public_params['access_token'] = self._token.access_token
public_params['param'] = json.dumps(params or data)
public_params['sign'] = calculate_signature(public_params, self.sign_secret)

request_url = f'{self.API_BASE_URL}{endpoint}'
response = self._request(method, request_url, params=public_params, json=data)
print(response.status_code, response.json())
return Result(**response.json())

def decrypt(self, message):
block = AES.new(
base64.b64decode(self.message_key),
AES.MODE_CBC, iv=bytes(AES.block_size)
)
decrypt_data = block.decrypt(base64.b64decode(message))
length = len(decrypt_data)
return decrypt_data[:length - int(decrypt_data[length - 1])].decode()
Loading