最近在对接管家婆,文档上只有 java php .net 的例子,写了一个python的例子,里面部分数据按需填写。
加解密代码借鉴于知乎
python里面json对象转字符串,分号和逗号默认会有空格,会导致加密和签名不通过
2020-12-16 增加部分接口调用代码

import base64
import copy
import hashlib
import requests
import time
import jsonfrom Crypto.Cipher import AESclass GuanjiapoOpenApiRequest:class GuanjiapoOpenApiException(Exception):passDEFAULT_APP_KEY = {'app_key': '',}DEFAULT_SIGN_KEY = {'sign_key': '',}DEFAULT_KEY = {'key': '',}DEFAULT_IV = {'iv': '',}GUANJIAPO_OPEN_API_URL = {'get_authcode': 'http://apigateway.wsgjp.com.cn/api/login','get_token': 'http://apigateway.wsgjp.com.cn/api/token',}def __init__(self, key, iv):self.key = key.encode('utf-8')self.iv = iv.encode('utf-8')def pkcs7padding(self, text):"""明文使用PKCS7填充 """bs = 16length = len(text)bytes_length = len(text.encode('utf-8'))padding_size = length if (bytes_length == length) else bytes_lengthpadding = bs - padding_size % bspadding_text = chr(padding) * paddingreturn text + padding_textdef aes_encrypt(self, content):""" AES加密 """cipher = AES.new(self.key, AES.MODE_CBC, self.iv)# 处理明文content_padding = self.pkcs7padding(content)# 加密encrypt_bytes = cipher.encrypt(content_padding.encode('utf-8'))# 重新编码result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')return resultdef aes_decrypt(self, content):"""AES解密 """cipher = AES.new(self.key, AES.MODE_CBC, self.iv)content = base64.b64decode(content)text = cipher.decrypt(content).decode('utf-8')return text@classmethoddef str_md5(cls, data):"""md5加密"""m = hashlib.md5(data.encode('utf-8'))return (m.hexdigest().upper())@classmethoddef get_authcode(cls):"""通过接口获取授权认证码"""url = cls.GUANJIAPO_OPEN_API_URL['get_authcode']app_key = GuanjiapoOpenApiRequest.DEFAULT_APP_KEY['app_key']key = GuanjiapoOpenApiRequest.DEFAULT_KEY['key']iv = GuanjiapoOpenApiRequest.DEFAULT_IV['iv']ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())p_json = {'CompanyName': '公司名','UserId': '用户名','Password': '密码','TimeStamp': ts,}aes_data = GuanjiapoOpenApiRequest(key=key, iv=iv)p = aes_data.aes_encrypt(json.dumps(p_json, separators=(',', ':'), ensure_ascii=False))sign_key = cls.DEFAULT_SIGN_KEY['sign_key']sign_json = {"appkey": app_key,"p": p,"signkey": sign_key,}sha256 = hashlib.sha256()sha256.update(json.dumps(sign_json, separators=(',', ':'), ensure_ascii=False).encode('utf-8'))sign_key = sha256.hexdigest()post_data = {'appkey': app_key,'p': p,'sign': sign_key,}res = requests.post(url, data=post_data)return res@classmethoddef get_token(cls, p_json=None):"""根据 authcode 获取token"""url = GuanjiapoOpenApiRequest.GUANJIAPO_OPEN_API_URL['get_token']app_key = GuanjiapoOpenApiRequest.DEFAULT_APP_KEY['app_key']key = GuanjiapoOpenApiRequest.DEFAULT_KEY['key']iv = GuanjiapoOpenApiRequest.DEFAULT_IV['iv']ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())res = GuanjiapoOpenApiRequest.get_authcode()res_json = res.json()auth_code = res_json['response']['authcode']p_json = p_json or {'TimeStamp': ts,'GrantType': 'auth_token','AuthParam': auth_code,}aes_data = GuanjiapoOpenApiRequest(key=key, iv=iv)p = aes_data.aes_encrypt(json.dumps(p_json, separators=(',', ':'), ensure_ascii=False))sign_key = cls.DEFAULT_SIGN_KEY['sign_key']sign_json = {"appkey": app_key,"p": p,"signkey": sign_key,}sha256 = hashlib.sha256()sha256.update(json.dumps(sign_json, separators=(',', ':'), ensure_ascii=False).encode('utf-8'))sign_key = sha256.hexdigest()post_data = {'appkey': app_key,'p': p,'sign': sign_key,}res = requests.post(url, data=post_data)res_json = res.json()response = res_json['response']['response']aes_data = GuanjiapoOpenApiRequest(key=key, iv=iv)decrypt_str = aes_data.aes_decrypt(response)decrypt_str = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', decrypt_str)res = json.loads(decrypt_str)# return res['auth_token']  # 因为 refresh_token() 还需要调用,所以不能直接返回 tokenreturn res@classmethoddef refresh_token(cls):"""根据 refresh_token 刷新token"""res = GuanjiapoOpenApiRequest.get_token()refresh_token = res['refresh_token']ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())p_json = {'TimeStamp': ts,'GrantType': 'refresh_token','AuthParam': refresh_token,}ress = GuanjiapoOpenApiRequest.get_token(p_json)return ress@classmethoddef request_wrapper(cls, method, data) -> requests.Response:"""请求封装"""url = cls.GUANJIAPO_OPEN_API_URL['baseUrl']app_key = cls.DEFAULT_APP_KEY['app_key']sign_key = cls.DEFAULT_SIGN_KEY['sign_key']ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())token = GuanjiapoOpenApiRequest.get_token()['auth_token']add_list = []sign_json = copy.deepcopy(data)sign_json.update({'method': method,'appkey': app_key,'timestamp': ts,'token': token,})key_sort_list = [key for key in sign_json]key_sort_list.sort()for key in key_sort_list:value = sign_json[key]if value or value == 0:  # 去掉空字符串、[]、{}add_list.append(key + str(value))sign_str = ''.join(add_list) + sign_keysign = GuanjiapoOpenApiRequest.str_md5(sign_str)json_data = copy.deepcopy(data)json_data.update({'appkey': app_key,'method': method,'timestamp': ts,'token': token,'sign': sign,})res = requests.post(url=url, data=json_data, verify=False)return res@classmethoddef beefun_selfbuiltmall_queryproductinfo(cls):"""商品详情查询"""method = 'beefun.selfbuiltmall.queryproductinfo'# method = 'zyx.selfbuiltmall.queryproductinfo'data = {'pagesize': 50,'pageno': 1,'ptypeids': [],'pricetype': 0,'begintime': '2020-01-01 00:00:00','endtime': '2021-01-01 00:00:00',}res = GuanjiapoOpenApiRequest.request_wrapper(method=method, data=data)return res@classmethoddef zyx_selfbuiltmall_addsaleorder(cls):method = 'zyx.selfbuiltmall.addsaleorder'ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())# ts = "2020-10-10 16:57:22"data = {"shopkey": "3d37a7aa-ea05-4340-9291-1c09a960127c","tradeid": "DD00000000002","payno": "1234567890","tradestatus": "0","buyermessage": "","sellermemo": "bbeizhu","tradecreatetime": ts,"tradepaiedtime": ts,"tradefinishtime": ts,"trademodifiedtime": ts,"steptradedeliverytime": ts,"tradetype": "0","shippingtype": "1","steptradestatus": "0","refundstatus": "0","invoicetitle": "lansemomoda","freightcode": "SF","freightbillno": "DH001","sellerflag": "0","tradetotal": "176","total": "100","paiedtotal": "0","preferentialtotal": "77","mallfee": "0","customerfreightfee": "9","buyerpayment": "0","expressagencyfee": "0","taxtotal": "0","taxamount": "0","taxfee": "0","orderdetails": '[{"BarCode":"barcode","comboId":0,"IsGift":false,"Oid":"DD00000000001001","OutId":"SJBM_111","PicUrl":null,"PlatformPropertiesName":"cccccccc","preferentialtotal":50.0,"Price":70.889,"ProductName":"测试商品","PtypeId":"110890-9001","Qty":2.0,"refundQty":0.0,"RefundStatus":0,"refundTotal":0.0,"SkuId":"110890-9001","TradeOriginalPrice":120.0},''{"BarCode":"barcode2","comboId":0,"IsGift":false,"Oid":"DD00000000001002","OutId":"SJBM_222","PicUrl":null,"PlatformPropertiesName":"qqqqq","preferentialtotal":28.0,"Price":30.0,"ProductName":"测试商品","PtypeId":"987654321001","Qty":2.0,"refundQty":0.0,"RefundStatus":0,"refundTotal":0.0,"SkuId":"1111111111111111111111111111111112","TradeOriginalPrice":58.0}]',"eshopbuyer": '{"CustomerAllAddress":null,"CustomerEmail":null,"CustomerPayAccount":null,"CustomerReceiver":"苍茫北望","CustomerReceiverAddress":"ruanjianyuan","CustomerReceiverCity":"chengdu","CustomerReceiverCountry":"china","CustomerReceiverDistrict":"gaoxin","CustomerReceiverMobile":"12345678911","CustomerReceiverPhone":"12345678","CustomerReceiverProvince":"sichuan","CustomerReceiverZipcode":"123456","CustomerShopAccount":"zzzz","IdCard":null,"Profileid":0}',"method": "zyx.selfbuiltmall.addsaleorder","appkey": "68943923115886070418838901844741","timestamp": ts,"token": "nF1WXGcp27iiTJwC2P2GuysuJuGmtCE2FGBH7K1E"}res = GuanjiapoOpenApiRequest.request_wrapper(method=method, data=data)return resif __name__ == '__main__':r = GuanjiapoOpenApiRequest.zyx_selfbuiltmall_addsaleorder()res_json = r.json()print(json.dumps(res_json, ensure_ascii=False, indent=4))

python-管家婆-接口获取授权认证码、利用授权认证码获取token信息、刷新token、部分接口调用相关推荐

  1. ajax 获取用户ip地址,利用jQuery实现Ajax获取当前IP地区位置代码

    特效描述:利用jQuery实现 Ajax 获取当前IP 地区位置代码.利用jQuery实现Ajax获取当前IP和地区位置代码 代码结构 1. 引入JS 2. HTML代码 AJAX检测ip和地区 $( ...

  2. IdentityServer4 获取Token及刷新Token

    一.获取Token 使用PostMan,调用接口:http://192.168.31.132:7000/connect/token client_id:appClient client_secret: ...

  3. python 根据地址求经纬度 谷歌_利用google的API获取世界城市经纬度(python实现)

    google API 需要 --. #-*- coding: utf8 -*- from xml.dom import minidom import urllib2, urllib #这个KEY本来是 ...

  4. jq 通过标签名称获取标签_怎样利用tag标签来获取长尾关键词排名

    一.思路和原理 以往的建站实践中,tag标签的功能往往被无限缩小,站长们都陷入了一种思维定势之中,忘记了tag标签页同样也是网站的重要内页(由于tag页往往也是由众多的带有此tag关键词的内页所链接, ...

  5. python爬取百度地图数据_Python利用百度地图爬取商家信息

    import requests import json import pandas as pd def request_hospital_data(): ak="换成自己的 AK" ...

  6. 【49.Auth2.0认证与授权过程-微博开放平台认证授权过程-百度开放平台认证授权过程-社交登录实现(微博授权)-分布式Session问题与解决方案-SpringSession整合-Redis】

    一.知识回顾 [0.三高商城系统的专题专栏都帮你整理好了,请点击这里!] [1-系统架构演进过程] [2-微服务系统架构需求] [3-高性能.高并发.高可用的三高商城系统项目介绍] [4-Linux云 ...

  7. Spring Security Oauth2 认证(获取token/刷新token)流程

    文章原作者链接地址:https://blog.csdn.net/gangsijay888/article/details/81977796 记下来以便以后查看 1.本文介绍的认证流程范围 本文主要对从 ...

  8. 玩转Spring Cloud Security OAuth2身份认证扩展——电话号码+验证码认证

    在程序的认证过程中,除了常规的用户名和密码方式(可以参考深入理解Spring Cloud Security OAuth2身份认证),也经常会出现电话号码+密码的方式:电话号码+验证码的方式:或者第三方 ...

  9. 无痕刷新token-无需提供刷新token接口方式

    一,提供一个login接口获取token: 1,通过jwt的方式生成token: private static SignatureAlgorithm signatureAlgorithm = Sign ...

  10. 刷新token重新请求接口

    我这里的token是调用接口,用一个refreshToken调用接口换回来新的token,然后再拿着新的token去请求接口,通过调用接口返回的code状态码来判断是否需要刷新token 在能获取到t ...

最新文章

  1. 程序 算法与数据结构
  2. FFmpeg for ios架构:中级
  3. php框架 css文件引用,yii框架中怎么引入css文件
  4. SAP CRM和C4C的客户主数据修改历史记录查询
  5. 这几张图告诉你化学到底有多神奇!看完瞬间觉得智商都提高了!
  6. java+向前进一_Java 线程基础
  7. pip不是内部或外部命令,也不是可运行的程序 或批处理文件--解决办法
  8. 通过java反射实现简单的关于MongoDB的对象关系映射(ORM).
  9. C++中Future和Promise的一种简单实现
  10. 基于容器的虚拟化资源调度系统架构设计 | 原力计划
  11. win11系统怎么样 Windows11系统好用吗
  12. Q142:PBRT-V3,交点处各种微分的求解(三角形,3.6章节)
  13. android ios av tv,无需Apple TV的AirPlay镜像的顶级4解决方案您应该知道
  14. 下载离线地图数据(支持谷歌、百度、高德等所有地图源)
  15. DB数据库密码怎么破啊~~~求高手帮忙解决下~
  16. 腾讯系互联网券商富途证券将赴美IPO,最高融资3亿美元
  17. 按降序显示奇数python_程序在Python中分别以升序和降序对所有偶数和奇数进行排序...
  18. 化工厂人员定位如何实现,主要有哪些功能?
  19. 苹果ios超级签名源码包java版带分发页面支持安卓合并部署教程
  20. 调度失败:执行器地址为空

热门文章

  1. 2023.6.25每日一题
  2. DevOps 工程师成长日记系列一:必备知识与技能组合
  3. linux 创建文件命令总结
  4. iphone 5s设置方法
  5. ASEMI代理长电可控硅BT134的工作原理,BT134的应用领域
  6. css样式顶掉important和important的使用注意点
  7. 张国华:有了互联网+大数据,智慧城市也不能走计划经济的道路
  8. 用UItraISO做U盘的启动盘(图文教程)
  9. Go语言 正则表达式
  10. 【uEditor】引入富文本编辑器uEditor时,上传图片失败的原因