def authHandler(*args, **kwargs): try: token = request.headers.get(RequestHeader.AUTH.value) if token: jwt.decode( token, Container.config.getProperty("jwt.secret-key", "123456"), options=JWT_OPTIONS ) else: raise BusinessException(ResponseCode.AUTH_ERROR, None) except Exception as e: logger.error(e) raise BusinessException(ResponseCode.AUTH_ERROR, e) return fn(*args, **kwargs)
def formHandler(*args, **kwargs): params = {} if request.form: for item in request.form: params[item] = request.form.get(item) if param_infos: for key, param_info in param_infos.items(): if params: value = params[key] for item in param_info['verifies']: item(value, ResponseCode.PARAM_ERROR) else: raise BusinessException(ResponseCode.PARAM_ERROR, None) if params: kwargs = {**kwargs, **params} return fn(*args, **kwargs)
def argsHandler(*args, **kwargs): thread_local.id = threading.currentThread().ident params = {} if request.args: for item in request.args: params[item] = request.args.get(item) if param_infos: for key, param_info in param_infos.items(): if params: value = params[key] for item in param_info['verifies']: item(value, ResponseCode.PARAM_ERROR) else: raise BusinessException(ResponseCode.PARAM_ERROR, None) if params: kwargs = {**kwargs, **params} return fn(*args, **kwargs)
def non_blank(param, response_code): if param == None or len(param) == 0: raise BusinessException(response_code, None)
def equals(objA, objB, response_code): if objA != objB: raise BusinessException(response_code, None)
def order_wx_refund(db_model, env, orderDict: dict = {}): """ 商城退款接口 @params: appid @params: mch_id @params: nonce_str @params: sign @params: out_trade_no @params: out_refund_no @params: total_fee(单位为分) @params: refund_fee(单位为分) @(optional)params: sign_type @(optional)params: notify_url(退款回调地址) @(optional)params: mchReserved(保留域) @(optional)params: refund_desc() """ if not orderDict: raise BusinessException(code.CODE_FAIL, strings.ORDER_PARAMS_NONE) # 调用微信退款的接口 # env = pay_config.get('env') os.environ['ENV'] = env nonce_str = random_str() wechat_dict = BaseConfig.get('WECHAT_PARAM') mch_reserved_dict = json.loads(orderDict.get('mchReserved')) if 'after_sales_no' in mch_reserved_dict.keys(): as_no = mch_reserved_dict.get('after_sales_no') order_dict = db_model.table('mall_after_sales').select( ['order_no']).where(['after_sales_no={}'.format(as_no)]).get_one() order_id = order_dict.get('order_no') else: order_id = mch_reserved_dict.get('order_no', None) if order_id is None: msg = 'order_no为空' raise BusinessException(code.CODE_FAIL, msg) mch_rsa = sign_generate_service.SignRSA(**mch_reserved_dict) ordered_item = mch_rsa.get_ordered_data(mch_reserved_dict) mch_reserved_str = mch_rsa.encode_for_mch_reserved(ordered_item) # 对保留域进行Base64 加密 mch_encode_str = base64.b64encode(bytes(mch_reserved_str, encoding="utf8")) notify_url = wechat_dict.get('refund_notify_url') + '/' + str( mch_encode_str, encoding="utf8") refund_amt = orderDict.get('refundAmt', 0) if isinstance(refund_amt, decimal.Decimal): refund_amt = str(int(refund_amt * 100)) txn_amt = orderDict.get('txnAmt') if isinstance(txn_amt, decimal.Decimal): txn_amt = str(int(txn_amt * 100)) refund_dict = { 'appid': BaseConfig.get('WXCONFIG').get('program').get('appid'), 'mch_id': wechat_dict.get('pay_mer_id'), 'nonce_str': nonce_str, 'out_trade_no': order_id, 'out_refund_no': orderDict.get('out_refund_no', ''), 'total_fee': str(txn_amt), 'refund_fee': str(refund_amt), 'refund_desc': orderDict.get('refund_desc'), 'notify_url': notify_url, } sign_rsa = sign_generate_service.SignRSA(**refund_dict) refund_dict['sign'] = sign_rsa.generate_wechat_sign() print("向微信发起退款申请,退款参数为:{}".format(refund_dict)) refund_str = bytes.decode( dicttoxml(refund_dict, root=False, attr_type=False)) refund_xml_str = '<xml>' + refund_str + '</xml>' post_url = wechat_dict.get('refund_url') headers = {'Content-Type': 'application/xml'} # 把参数转义成xml try: current_path = os.path.dirname( os.path.dirname(os.path.dirname(__file__))) ssh_keys_path = os.path.join(current_path, "config/") print(ssh_keys_path) api_client_cert = os.path.join(ssh_keys_path, 'apiclient_cert.pem') api_client_key = os.path.join(ssh_keys_path, 'apiclient_key.pem') res = requests.post(post_url, refund_xml_str.encode('utf-8'), headers=headers, cert=(api_client_cert, api_client_key), verify=True) print(res.content) except BusinessException as ex: raise BusinessException(ex.code, ex.msg) if str(res.status_code) == '200': res_content = res.content res_str = xmltodict.parse(res_content, encoding='utf-8') resp_dict = json.loads(json.dumps(res_str)) if resp_dict.get('xml').get('return_code') == 'FAIL': err_code = resp_dict.get('err_code') resp_msg = resp_dict.get('return_msg') raise BusinessException(err_code, resp_msg) if resp_dict['xml']['return_code'] == 'SUCCESS': refund_data_dict = { # 'refundState': resp_dict.get('result_code', ''), 'result_code': resp_dict.get('xml').get('return_code'), 'refund_id': resp_dict.get('xml').get('refund_id') } # refund_data_str = cmb_refund_data.get('refundState', '') refund_data_str = json.dumps(refund_data_dict) print("refund_data_str====={}".format(refund_data_str)) return refund_data_str
def order_wechat_pay(db_model, pay_config: dict= {}): """ 商城支付接口 @params: version @params: encoding @params: merId @params: sign @params: signMethod @params: orderId @params: subAppId @params: tradeType @params: tradeScene @params: userId @params: body @params:notifyUrl @params:txnAmt (单位为分) @params:spbillCreateIp @params: openId @params: subOpenId @(optional)params: deviceInfo @(optional)params: limitPay @(optional)params: currencyCode @(optional)params: sceneInfo @(optional)params: identity @(optional)params: policyNo @(optional)params: region @(optional)params: goodsDetail @(optional)params: goodsTag @(optional)params: attach @(optional)params: mchReserver @(optional)params: payValidTime """ if not pay_config: raise BusinessException(code.CODE_FAIL, strings.ORDER_PARAMS_NONE) txn_amt = pay_config.get('txnAmt') if isinstance(txn_amt, decimal.Decimal): txn_amt = str(int(txn_amt * 100)) # 调用微信支付接口 env = pay_config.get('env') os.environ['ENV'] = env nonce_str = random_str() wechat_dict = BaseConfig.get('WECHAT_PARAM') pay_dict = { 'appid': BaseConfig.get('WXCONFIG').get('program').get('appid'), 'mch_id': wechat_dict.get('pay_mer_id'), 'nonce_str': nonce_str, 'body': pay_config.get('body'), 'out_trade_no': pay_config.get('orderId'), 'total_fee': str(txn_amt), 'spbill_create_ip': pay_config.get('spbillCreateIp', ''), 'notify_url': wechat_dict.get('pay_notify_url', ''), 'trade_type': pay_config.get('tradeType', 'JSAPI'), 'openid': pay_config.get('subOpenId', '') } # sign_rsa = sign_generate_service.SignRSA(**pay_dict) # sign_info = sign_rsa.sign_with_wechat_key() sign_info = generate_sign(pay_dict) pay_dict['sign'] = sign_info print(pay_dict) pay_str = bytes.decode(dicttoxml(pay_dict, root=False, attr_type=False)) pay_xml_str = '<xml>' + pay_str + '</xml>' post_url = wechat_dict.get('pay_url') headers = {'Content-Type': 'application/xml'} # 把参数转义成xml try: print("订单:{}向微信发起付款请求,请求内容为:{}".format(pay_config.get('orderId', ''), pay_xml_str)) res = requests.post(post_url, pay_xml_str.encode('utf-8'), headers=headers) print(res.content) except BusinessException as ex: raise BusinessException(ex.code, ex.msg) if str(res.status_code) == '200': res_content = res.content res_str = xmltodict.parse(res_content, encoding='utf-8') # res_str = res_content.decode('utf-8') resp_dict = json.loads(json.dumps(res_str)) if resp_dict.get('respCode') == 'FAIL': err_code = resp_dict.get('errCode') resp_msg = resp_dict.get('respMsg') raise BusinessException(err_code, resp_msg) if resp_dict['xml']['return_code'] == 'SUCCESS': prepay_id = resp_dict['xml']['prepay_id'] # 时间戳 timeStamp = str(int(time.time())) # 5. 五个参数 data = { "appId": BaseConfig.get('WXCONFIG').get('program').get('appid'), "nonceStr": nonce_str, "package": "prepay_id=" + prepay_id, "signType": 'MD5', "timeStamp": timeStamp, } # 6. paySign签名 paySign = generate_sign(data) data["paySign"] = paySign # 加入签名 print(data) # 7. 传给前端的签名后的参数 return json.dumps(data)