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

            久久综合一区二区无码| 久久av无码专区亚洲av桃花岛| 久久99国产乱子伦精品免费| 国产精品久久久久久搜索| 99久久综合狠狠综合久久| 欧美一级久久久久久久大| 久久久久人妻精品一区| 精品免费久久久久国产一区 | 亚洲午夜久久久久妓女影院| 国产精品久久久亚洲| 久久久久亚洲精品天堂久久久久久| 国产精品久久久久久久久软件 | 久久人妻少妇嫩草AV蜜桃| 久久免费国产精品一区二区| 久久久久亚洲AV成人网人人网站| 日本一区精品久久久久影院| 2019久久久高清456| 久久久久久青草大香综合精品| 国产人久久人人人人爽| 久久久久久久波多野结衣高潮| 91精品国产91热久久久久福利| 久久婷婷五月综合色奶水99啪 | 久久久久国产亚洲AV麻豆| 99久久婷婷免费国产综合精品| 久久久国产打桩机| 亚洲精品成人久久久| 久久人妻少妇嫩草AV无码蜜桃| 国产69精品久久久久9999| 国产精品久久久久AV福利动漫| 亚洲综合伊人久久大杳蕉| 色狠狠久久综合网| 久久99九九国产免费看小说| 亚洲欧洲久久av| 中文字幕久久亚洲一区| 久久亚洲sm情趣捆绑调教| 日日狠狠久久偷偷色综合96蜜桃| 久久精品国产精品亚洲| 日韩电影久久久被窝网| 久久福利资源国产精品999| 久久久精品国产免大香伊 | 国产精品九九久久精品女同亚洲欧美日韩综合区 |