调用第三方服务API的SDK编写思路
思路
- 通过将SDK方法中返回的数据划分为正常返回数据以及错误返回的数据两部分,让调用者更简单的对接口调用错误进行处理。
- 将SDK调用第三方服务接口的流程划分为: 数据准备,http请求,结果处理三部分,以重用代码。
例子
以聚合数据手机话费充值SDK编写为例, 手机话费充值API
# encoding=utf-8 from urlparse import urljoin from hashlib import md5 from datetime import datetime from random import sample import requests import pytz class APIError(object): def __init__(self, code, msg): self.code = code self.message = msg class JuhePhoneChargeApi(object): API_PREFIX = 'https://op.juhe.cn/ofpay/mobile/' def __init__(self, openid, key, api_entry=None): self._key = key self._openid = openid self._api_entry = api_entry or self.API_PREFIX def telcheck(self, phoneno, cardnum): params = {'phoneno': phoneno, 'cardnum': cardnum} return self._get(path='telcheck', params=params) def telquery(self, phoneno, cardnum): params = { 'phoneno': phoneno, 'cardnum': cardnum, } return self._get(path='telquery', params=params) def onlineorder(self, phoneno, cardnum, orderid): params = { 'phoneno': phoneno, 'cardnum': cardnum, 'orderid': orderid or self.create_orderid(), } params.update({'sign': self._create_sign(**params)}) return self._get(path='onlineorder', params=params) def ordersta(self, orderid): params = {'orderid': orderid} return self._get(path='orderid', params=params) def create_orderid(self): return ''.join(( datetime.now(tz=pytz.timezone('Asia/Shanghai')).strftime('%Y%m%d%H%M%S%f'), self._create_code(12))) def _process_response(self, rsp): """ 对第三方接口返回数据做同一处理, :param rsp: :return: 接口正常返回值, 错误对象 """ if rsp.status_code != 200: return None, APIError(rsp.status_code, 'http error') try: content = rsp.json() except: return None, APIError(99999, 'invalid rsp') if 'error_code' in content and content['error_code'] != 0: return None, APIError(content['error_code'], content['reason']) return content['result'], None def _get(self, path, params=None): if not params: params = {} headers = {'Content-type': 'application/json'} params.update({'key': self._key}) rsp = requests.get(urljoin(self._api_entry, path), params=params, headers=headers) return self._process_response(rsp) def _create_sign(self, phoneno, cardnum, orderid=None): obj_str = ''.join(( self._openid, self._key, phoneno, str(cardnum), orderid or self.create_orderid())) m = md5() m.update(obj_str) return m.hexdigest() def _create_code(self, number_len): ELEMENT = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' return ''.join(sample(ELEMENT, number_len))
文/Ljian1992(简书作者)
原文链接:http://www.jianshu.com/p/08f783dea4d9
原文链接:http://www.jianshu.com/p/08f783dea4d9
相关推荐
liusarazhang 2020-08-16
magic00 2020-08-03
Keepgoing 2020-08-03
孝平 2020-07-18
futurechallenger 2020-07-10
lyccsu 2020-07-08
xjp 2020-06-28
BigCowPeking 2020-06-28
QCkiss 2020-06-21
CallMeV 2020-06-08
绿豆饼 2020-06-03
yourFriend 2020-05-28
playis 2020-05-27
82599532 2020-05-26
Hannah 2020-05-26
csdnYF 2020-05-16
过时不侯的温暖 2020-05-08
wmd看海 2020-05-01
xiaoxiangyu 2020-04-29