def pushtoken(pushtoken, os, event_type, trans_id, content, title='The Yub', data={}, uid=0, badge=1): """根据token推送 pushtoken: 推送token os: 操作系统 event_type: 事件类型 trans_id: 交易id content: 显示内容 title: 标题,只针对android用户 data: 自定义报文,dict对象 uid: 用户uid badge: APP右上角显示未阅读数 """ if not pushtoken or not os: log_info('[Push][PushError] pushtoken => %s, os => %s' % (pushtoken, os)) return from parse_rest.connection import register from parse_rest.installation import Push as ParsePush parse_app_id = current_app.config['PARSE_APP_ID'] parse_app_key = current_app.config['PARSE_APP_KEY'] register(parse_app_id, parse_app_key) where = {'objectId':pushtoken} push_params = {'badge':badge, 'uid':uid, 'data':data, 'sound':'default', 'event_type':event_type, 'trans_id':trans_id, 'alert':content, 'deviceType':os} ParsePush.alert(push_params, where=where)
def get_sign(self, params): """生成sign """ stringA = self.key_value_url(params) stringSignTemp = stringA + '&key=' + current_app.config['APIKEY'] # APIKEY, API密钥,需要在商户后台设置 log_info("stringSignTemp ==> %s" % stringSignTemp) sign = (md5(stringSignTemp).hexdigest()).upper() params['sign'] = sign log_info("sign ==> %s" % sign)
def get_sign(self, params): """生成sign """ stringA = self.key_value_url(params) stringSignTemp = stringA + '&key=' + current_app.config[ 'APIKEY'] # APIKEY, API密钥,需要在商户后台设置 log_info("stringSignTemp ==> %s" % stringSignTemp) sign = (md5(stringSignTemp).hexdigest()).upper() params['sign'] = sign log_info("sign ==> %s" % sign)
def verify(self): """验证签名""" self.xml_json.pop('sign') self.get_sign(self.xml_json) if self.sign != self.xml_json['sign']: log_info("signValue:%s != sing:%s" % (self.xml_json['sign'], self.sign)) return False return True
def get_req_xml(self): """拼接XML """ self.get_sign(self.params) xml = "<xml>" for k, v in self.params.items(): v = v.encode('utf8') k = k.encode('utf8') xml += '<' + k + '>' + v + '</' + k + '>' xml += "</xml>" log_info(xml) return xml
def _send_msg(self, params): '''Push API for all kinds of message and notification, dict params restore all parameters''' try: api_post = urllib2.urlopen(data=urllib.urlencode(params), url=API_URL, timeout=5) if api_post: log_debug(api_post.read()) except Exception, e: #print e, e.read() log_info("[JpushError] %s" % e)
def key_value_url(self, value): """将将键值对转为 key1=value1&key2=value2 """ key_az = sorted(value.keys()) pair_array = [] for k in key_az: v = value.get(k, '').strip() v = v.encode('utf8') k = k.encode('utf8') log_info('%s => %s' % (k, v)) pair_array.append('%s=%s' % (k, v)) tmp = '&'.join(pair_array) log_info("key_value_url ==> %s " % tmp) return tmp
def key_value_url(self, value): """将将键值对转为 key1=value1&key2=value2 """ key_az = sorted(value.keys()) pair_array = [] for k in key_az: v = value.get(k, '').strip() v = v.encode('utf8') k = k.encode('utf8') log_info('%s => %s' % (k,v)) pair_array.append('%s=%s' % (k, v)) tmp = '&'.join(pair_array) log_info("key_value_url ==> %s " %tmp) return tmp
def get_prepay_id(self): """ 请求获取prepay_id """ xml = self.get_req_xml() headers = {'Content-Type': 'application/xml'} r = requests.post(self.url, data=xml, headers=headers) log_info(r.text) log_info("++++++++++++++++++++++++++") re_xml = ElementTree.fromstring(r.text.encode('utf8')) xml_status = re_xml.getiterator('result_code')[0].text log_info("result_code ==> %s" % xml_status) if xml_status != 'SUCCESS': self.error = u"连接微信出错啦!" return prepay_id = re_xml.getiterator('prepay_id')[0].text self.params['prepay_id'] = prepay_id self.params['package'] = 'Sign=WXPay' self.params['timestamp'] = str(int(time.time()))
class JSONService(object): """json服务""" def __init__(self, url, params=None, method='GET', timeout=10, cookie_jar=None, json_type='me', headers=[('language', 'en')]): self.url = url self.params = params self.method = method self.timeout = timeout self.cookie_jar = cookie_jar self.json_type = json_type self.headers = headers self.res = None self.json = {} self.ret = None self.msg = None self.data = None self.set_cookie = '' self.encoding = None def call_service(self): """调用远程服务""" try: encode_data = None if self.params is not None: if self.method == 'GET': self.url += '?' + urlencode(self.params) log_debug(self.url) elif self.method == 'POST': encode_data = urlencode(self.params) opener = urllib2.build_opener() opener.addheaders = self.headers if self.cookie_jar is not None: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar)) res_obj = opener.open(self.url, data=encode_data, timeout=self.timeout) self.set_cookie = res_obj.info().getheader('Set-Cookie') self.res = res_obj.read() # encoding self.encoding = guess_json_utf(self.res) if self.encoding: self.res = self.res.decode(self.encoding) self.json = json.loads(self.res) self.ret = self.json.get('ret') self.msg = self.json.get('msg') self.data = self.json.get('data') except Exception, e: #log_error('[JSONService] url:%s, response:%s, expetion:%s' % (self.url, self.res, e)) return False if self.ret != 0 and self.json_type == 'me': log_info('[JSONService] url:%s, response:%s' % (self.url, self.res)) return False #log_debug('[JSONService] success url:%s, response:%s' % (self.url, self.res)) return True