• <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

            靜以修身,儉以養(yǎng)德,非澹薄無以明志,非寧靜無以致遠。
            隨筆 - 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']  # 業(yè)務結果  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']  # 業(yè)務結果  SUCCESS/FAIL
                        out_trade_no = data['out_trade_no']  # 商戶訂單號
                        if trade_status == "SUCCESS":
                            weixinpay_sucess_db(data)
                            device_info = data['device_info']  # 微信支付分配的終端設備號
                            # 如果狀態(tài)是支付成功則發(fā)放物品
                            hall = KBEngine.globalData["Halls"]
                            if hall:
                                player_data = hall.GetPlayerByDbId(int(device_info))
                                if player_data:
                                    player = player_data.entityCall
                                    if player:
                                        print('微信發(fā)放獎品到客戶端,訂單號======%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 閱讀(326) 評論(0)  編輯 收藏 引用 所屬分類: python

            99久久国产主播综合精品| 国产精品一区二区久久精品| 美女写真久久影院| 成人午夜精品久久久久久久小说| 久久精品国产99国产电影网| 久久久久亚洲精品天堂久久久久久| 区亚洲欧美一级久久精品亚洲精品成人网久久久久 | 久久久久久亚洲精品无码| 精品免费久久久久久久| 免费观看成人久久网免费观看| 99久久国产亚洲综合精品| 久久国产亚洲高清观看| 久久久久亚洲精品男人的天堂| 久久99精品久久只有精品 | 国产精品美女久久久网AV| 亚洲日本久久久午夜精品| 99久久99这里只有免费费精品 | 久久国产午夜精品一区二区三区| 大香伊人久久精品一区二区| 99久久精品免费看国产一区二区三区 | 久久婷婷五月综合色奶水99啪| 久久久精品国产亚洲成人满18免费网站| 热re99久久精品国99热| 亚洲va久久久久| 热综合一本伊人久久精品| 中文字幕成人精品久久不卡| 国内精品久久久久影院日本 | 日本WV一本一道久久香蕉| 狠狠人妻久久久久久综合| 国产精品久久久天天影视| 偷偷做久久久久网站| 亚洲欧洲中文日韩久久AV乱码| 亚洲国产精品婷婷久久| 欧美综合天天夜夜久久| 青青青青久久精品国产| 国产精品美女久久久m| 精品无码久久久久久午夜| 人妻精品久久无码区| 亚洲精品乱码久久久久久| 色欲久久久天天天综合网精品| 亚洲伊人久久精品影院|