• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            Benjamin

            靜以修身,儉以養德,非澹薄無以明志,非寧靜無以致遠。
            隨筆 - 397, 文章 - 0, 評論 - 196, 引用 - 0
            數據加載中……

            python服務器 實現app微信支付:支付異步通知

            # -*- coding: utf-8 -*-
            import tornado.httpserver
            import tornado.ioloop
            import tornado.options
            import tornado.web
            import pymysql
            import json
            import xmltodict
            from hashlib import md5
            from tornado.options import define, options
            ####################微信支付異步回調消息########################
            WEIXIN_KEY = '8mdRLb1yeesYssfasdfsadfassdaV'
            def generate_sign(params):
                """
                生成md5簽名的參數
                """
                if 'sign' in params:
                    params.pop('sign')
                src = '&'.join(['%s=%s' % (k, v) for k, v in sorted(params.items())]) + '&key=%s' % WEIXIN_KEY
                return md5(src.encode('utf-8')).hexdigest().upper()
            def validate_sign(resp_dict):
                """
                驗證微信返回的簽名
                """
                if 'sign' not in resp_dict:
                    return False
                wx_sign = resp_dict['sign']
                sign = generate_sign(resp_dict)
                if sign == wx_sign:
                    return True
                return False
            def handle_wx_response_xml(params):
                """
                處理微信支付返回的xml格式數據
                """
                try:
                    resp_dict = xmltodict.parse(params)['xml']
                    if not resp_dict or len(resp_dict) < 1:
                        print('resp_dict is zero+++++++++')
                        return None
                    return_code = resp_dict.get('return_code')
                    if return_code == 'SUCCESS':  # 僅僅判斷通信標識成功,非交易標識成功,交易需判斷result_code
                        if validate_sign(resp_dict):
                            print('驗證成功!!!')
                            return resp_dict
                   
                except Exception as e:
                    print(e)
                    return None
                return None
            def weixinpay_call_back(request):
                """
                微信支付回調
                :param request: 回調參數
                :return:
                """
                args = str(request.body,'utf-8')
                if args is None:
                    return None
                print(args)
                # 驗證平臺簽名
                resp_dict = handle_wx_response_xml(args)
                if resp_dict is None:
                    print('簽名驗證失敗!!!')
                    return None
                return resp_dict
            def weixinpay_response_xml(params):
                """
                生成交易成功返回信息
                """
                def generate_response_data(resp_dict):
                    """
                    字典轉xml
                    """
                    return xmltodict.unparse({'xml': resp_dict}, pretty=True, full_document=False).encode('utf-8')
                return_info = {
                    'return_code': params,
                    'return_msg': 'OK'
                }
                return generate_response_data(return_info)
            def weixinpay_sucess_db(dicts):
                """微信支付成功后數據庫日志操作"""
                if isinstance(dicts,dict):
                    trade_status = dicts['result_code']  # 業務結果  SUCCESS/FAIL
                    trade_no = dicts['out_trade_no']  # 商戶訂單號
                    if trade_status == "SUCCESS":
                        appid = dicts['appid']  # 應用ID
                        bank_type = dicts['bank_type']  # 付款銀行
                        cash_fee = dicts['cash_fee']  # 現金支付金額(分)
                        device_info = dicts['device_info']  # 微信支付分配的終端設備號
                        fee_type = dicts['fee_type']  # 貨幣種類
                        gmt_create = dicts['time_end']  # 支付完成時間
                        total_amount = int(dicts['total_fee']) / 100  # 總金額(單位由分轉元)
                        trade_type = dicts['trade_type']  # 交易類型
                        out_trade_no = dicts['transaction_id']  # 微信支付訂單號
                        seller_id = dicts['mch_id']  # 商戶號
                        openid = dicts['openid']  # 用戶標識
                        update_sql = ''' update weixin_trade set trade_status='{trade_status}', appid='{appid}', ''' + \
                        '''seller_id='{seller_id}', openid='{openid}', total_amount='{total_amount}',''' +  \
                        '''out_trade_no='{out_trade_no}', gmt_create='{gmt_create}', '''+ \
                        '''device_info='{device_info}', trade_type='{trade_type}', bank_type='{bank_type}', ''' + \
                        '''fee_type='{fee_type}', cash_fee='{cash_fee}' where trade_no='{trade_no}' '''
                        update_sql = update_sql.format(
                            trade_status=trade_status,
                            appid=appid,
                            seller_id=seller_id,
                            openid=openid,
                            total_amount=total_amount,
                            out_trade_no=out_trade_no,
                            gmt_create=gmt_create,
                            device_info=device_info,
                            trade_type=trade_type,
                            bank_type=bank_type,
                            fee_type=fee_type,
                            cash_fee=cash_fee,
                            trade_no=trade_no)
                        print(update_sql)
                        #寫數據庫
                        
            def weixin_rollback(request):
                """
                【API】: 微信寶支付結果回調接口,供微信服務端調用
                """
                try:
                    # 支付異步回調驗證
                    data = weixinpay_call_back(request)
                    if data:
                        print('微信支付返回====={0}'.format(data))
                        res = "success"
                        trade_status = data['result_code']  # 業務結果  SUCCESS/FAIL
                        out_trade_no = data['out_trade_no']  # 商戶訂單號
                        if trade_status == "SUCCESS":
                            weixinpay_sucess_db(data)
                            device_info = data['device_info']  # 微信支付分配的終端設備號
                            # 如果狀態是支付成功則發放物品
                            hall = KBEngine.globalData["Halls"]
                            if hall:
                                player_data = hall.GetPlayerByDbId(int(device_info))
                                if player_data:
                                    player = player_data.entityCall
                                    if player:
                                        print('微信發放獎品到客戶端,訂單號======%s' % out_trade_no)
                                        player.GmBkCmd({'cmd':'PayReward','Order_id':out_trade_no})
                                    else:
                                        print('找不到玩家++++++++')
                        else:
                            res = "error: pay failed! "
                            status = 0
                            err_code = data['err_code']  # 錯誤代碼
                            err_code_des = data['err_code_des']  # 錯誤代碼描述
                    else:
                        res = "error: verify failed! "
                except Exception as e:
                    print(e)
                    res='err:exception==='
                finally:
                    return weixinpay_response_xml(res)
            class WeChatPayNotify(tornado.web.RequestHandler):
                """微信支付回調"""
                def post(self):
                    """
                    【API】: 微信寶支付結果回調接口,供微信服務端調用
                    """
                    self.write(weixin_rollback(self.request))
            class WeChatPay(tornado.web.RequestHandler):
                def post(self):
                    to_client={}
                    for k,v in self.request.arguments.items():
                        to_client[k] = str(v[0],encoding='utf-8')
                    pid = to_client.pop('pid')
                    if isinstance(pid,str):
                        pid = int(pid)
                    self.write('')

            posted on 2020-12-05 15:34 Benjamin 閱讀(324) 評論(0)  編輯 收藏 引用 所屬分類: python

            无码精品久久久天天影视| 久久综合久久综合九色| 久久九九兔免费精品6| 亚洲午夜久久久久久久久电影网| 影音先锋女人AV鲁色资源网久久| 一本一本久久aa综合精品| 久久er国产精品免费观看2| 日韩影院久久| 久久99精品国产99久久6男男| 久久久青草青青国产亚洲免观| 久久精品国产AV一区二区三区| 青青草原综合久久| 久久久久亚洲AV片无码下载蜜桃| 久久国产亚洲精品无码| 香港aa三级久久三级老师2021国产三级精品三级在 | 蜜臀av性久久久久蜜臀aⅴ| 国产精品天天影视久久综合网| 亚洲国产小视频精品久久久三级 | 久久国产成人| 久久久国产精品亚洲一区| 亚洲一区精品伊人久久伊人| 久久这里只有精品首页| 久久国产精品77777| 狠狠色噜噜色狠狠狠综合久久| 精品久久久久久无码中文字幕| 国产精品久久久久jk制服| 色综合久久久久久久久五月| 久久99久久99精品免视看动漫| 久久精品国产一区二区电影| 色综合久久综合网观看| av无码久久久久不卡免费网站| 伊人久久综合成人网| 久久夜色精品国产噜噜亚洲a| 久久久久香蕉视频| 久久亚洲高清综合| 久久久久久亚洲精品不卡| 久久人人爽人人爽人人片AV麻豆 | 久久成人国产精品免费软件| 亚洲人成无码网站久久99热国产| 色综合久久88色综合天天 | 无码任你躁久久久久久|