コード例 #1
0
    def subscribe_scan(self, data):
        """
        关注后,重新扫描关注二维码
        """
        rsp = {"sign": 1, "msg": ''}
        if "save_user_info" in self.__dict__:
            # 刷新存储有用户基本信息中的,关注来源
            open_id = data["FromUserName"]
            qr_scene_str = data["EventKey"]
            update_data = {"subscribe_scene": "ADD_SCENE_QR_CODE", "qr_scene_str": qr_scene_str}

            had_this_guy = dao_wxservice.get_user_base_info(self.appid, {"openid": open_id or ''})
            if had_this_guy:
                update_num = dao_wxservice.update_user_base_info_subScene_qrStr_by_openid(
                    self.appid, open_id, update_data)
            else:
                update_num = 0
            if not update_num and not had_this_guy:
                user_base_info = self.get_user_info({"Data": {"open_id": open_id}}, use_api=True)
                if user_base_info["sign"]:
                    user_base_info["wechat_appid"] = self.appid
                    user_base_info.update(update_data)
                    insert_id = dao_wxservice.save_user_base_info(user_base_info)
                    if not insert_id:
                        failed_data = {"appid": self.appid, "openid": open_id, "update_data": update_data}
                        send_log(f'update_user_base_info_subScene_qrStr_by_openid|{failed_data}')
                        rsp["sign"] = 0
                        rsp["msg"] = "subscribe_scan|update_error"
        return rsp
コード例 #2
0
    def do_subscribe(self, data):
        """用户关注事件处理"""
        open_id = data["FromUserName"]
        rsp = {"sign": 1, "msg": ''}
        if "save_user_info" in self.__dict__:
            # 存储用户基本信息
            # 1 获取
            user_base_info = self.get_user_info({"Data": {"open_id": open_id}})
            if user_base_info["sign"]:
                # 2 存储
                user_base_info["wechat_appid"] = self.appid
                send_log(
                    f"save_user_info in self.__dict__ after get user_base_info is {user_base_info} and sign is {user_base_info['sign']}"
                )
                insert_id = dao_wxservice.save_user_base_info(user_base_info)
                if not insert_id:
                    send_log(f"SAVE USER_INFO ERROR|{user_base_info}")

        # 关注事件回复
        if self.subscribe_txt:
            # 关注回复文字(客服消息 和直接回复两种模式,在微信方,都只能当作一次响应。为了图文,只好干掉客服消息回复,全部由直接回复)
            # c_data = {"touser": open_id, "msgtype": "text", "text": {"content": self.subscribe_txt}}
            # rsp_data = self.wechat_oap.send_custom_msg(c_data)
            # if rsp_data.json().get("errcode"):
            rsp = {"sign": 1, "msg": self.subscribe_txt, "reply_txt": 1}
        if self.subscribe_news:
            # 关注回复图文(优先于文字,所以非if:else, 而是覆盖| 或许可以给回复文字加个异步)
            rsp = {"sign": 1, "msg": '', "reply_news": 1}
        return rsp
コード例 #3
0
def update_hos_config(appid) -> dict:
    """更新HOS_CONFIG_DICT"""
    global HOS_CONFIG_DICT
    lib_config.HOS_CONFIG_DICT[appid] = get_hos_cfg.get_config(appid)
    HOS_CONFIG_DICT = lib_config.HOS_CONFIG_DICT
    send_log(f'HOS_CONFIG_DICT||{appid}||{HOS_CONFIG_DICT[appid]}')
    return HOS_CONFIG_DICT[appid]
コード例 #4
0
def do_auth(inputs: dict, test: bool = False) -> dict:
    """授权前置步骤"""
    fail = []
    log_info("GET INPUT", inputs)
    app_id = inputs.get("app_id")
    rsp = {"sign": 0, "msg": ''}
    if app_id:
        # 存入数据库占位, 授权完成后调取信息补位
        if inputs.get("pre_auth_code") or test:
            placeholder = {
                "pre_auth_code": inputs["pre_auth_code"],
                "appid": app_id,
                "nick_name": "_placeholder",
                "wechat_appid": "_placeholder"
            }
            save_rsp = dao_wxservice.save(placeholder)
            dao_wxapi.save(inputs["pre_auth_code"], app_id)
            send_log(
                "AuthorizationStart: placeholder: {}, save_rsp: {}".format(
                    str(placeholder), str(save_rsp)))
            rsp = save_rsp
    else:
        rsp["msg"] = "params loss: app_id"
        fail.append(rsp["msg"])
    return fail, rsp
コード例 #5
0
def send_text_cont(fromu, tou, cont, nonce):
    """send all text msg"""
    reply_xml = """
    <xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%d</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
    </xml>""" % (fromu, tou, int(time.time()), cont)
    encryper = access3.WXBizMsgCrypt(lib_config.TOKEN,
                                     lib_config.ENCODINGAESKEY,
                                     lib_config.WXAPPID)
    # ret, encrypt_xml = encryper.encrypt_msg(reply_msg=reply_xml, nonce=nonce)
    ret, encrypt_xml = encryper.EncryptMsg(reply_xml, nonce)
    send_text_log = {
        "ret": ret,
        "reply_xml": reply_xml,
        "encrypt_xml": encrypt_xml,
        "nonce": nonce,
        "fromu": fromu,
        "tou": tou
    }
    send_log(f"send_text_cont|{send_text_log}")
    return Response(encrypt_xml, mimetype='text/xml')
コード例 #6
0
def unauthorized(authorizer_appid):
    # 取消授权
    rsp_dict = {"sign": 0, "msg": ''}
    rsp_dict["sign"], auth_account_list = dao_wxapi.unauthorized(
        authorizer_appid)
    if not rsp_dict["sign"]:
        rsp_dict[
            "msg"] = "server busy, the authorization info will delete after minutes."
    send_log(
        "UnAuthorizationInfo|appid: {}, auth_account_list: {}, rsp_dict: {}".
        format(authorizer_appid, str(auth_account_list), str(rsp_dict)))
    return rsp_dict
コード例 #7
0
def get_cfg_db(appid) -> dict:
    """从数据库获取各项配置"""
    cfg_data = {}
    app_id = dao_wxservice.get_app_id_by_wechat_id(
        appid) or lib_config.MAP_TEMP_APPID.get(appid) or ''
    rep_data = api.get_hos_cfg(app_id) or {}
    send_log.send_log(f'GET_CFG_DB|{rep_data}')
    rep_data = {}  # TODO 核实无误后,再启用从数据库读取配置
    if rep_data:
        release = rep_data["data"]["release"]
        cfg_data = json.loads(release or "{}")

    return cfg_data
コード例 #8
0
 def Get_This_Guy(self, data):
     # 获取用药指导, 发送模板消息
     send_log(f'Get_This_Guy||{self.Get_This_Guy_values}')
     rsp = {"sign": 0, "msg": ""}
     touser = data.get("FromUserName")
     pagepath = self.Get_This_Guy_values.get("pagepath")
     had_user_info = "save_user_info" in self.__dict__
     referrer = ''
     format_dict = {
         "hos_name": self.nickname,
         "open_id": touser,
     }
     if had_user_info and "referrer" in pagepath:
         referrer = self.get_user_info({"Data": {"open_id": touser}}).get("qr_scene_str")
         format_dict["referrer"] = referrer or ''
     pagepath = pagepath.format(**format_dict)
     template_data = {
         "touser": touser,
         "template_id": self.Get_This_Guy_values.get("template_id"),
         "url": "",
         "miniprogram": {
             "appid": "wxacd37ff25cd2ed6a",
             "pagepath": pagepath,
         },
         "data": {
             "first": {
                 "value": self.Get_This_Guy_values.get("value")
             },
             "keyword1": {
                 "value": "{}".format(datetime.datetime.now().strftime("%Y-%m-%d"))
             },
             "keyword2": {
                 "value": self.Get_This_Guy_values.get("keyword2"),
                 "color": "#ff8828"
             },
             "keyword3": {
                 "value": ""
             },
             "remark": {
                 "value": self.Get_This_Guy_values.get("remark")
             }
         }
     }
     custom_msg = {"touser": touser, "msgtype": "text", "text": {"content": "点击下方通知,查看你的用药指导"}}
     self.wechat_oap.send_custom_msg(custom_msg)
     msg_data = self.wechat_oap.send_template_msg(template_data)
     rsp["msg"] = msg_data.get("msg")
     if not msg_data.get("status"):
         rsp["sign"] = 1
         track_Get_This_Guy("wx_Get_This_Guy_count", self.appid, touser)
     return rsp
コード例 #9
0
 def do_unsubscribe(self, data):
     """用户取消关注处理"""
     rsp = {"sign": 1, "msg": ''}
     open_id = data["FromUserName"]
     if "save_user_info" in self.__dict__:
         # 更改该用户状态为0
         update_num = dao_wxservice.update_user_base_info_status_by_openid(self.appid, open_id, {
             "status": 0,
             "subscribe": 0
         })
         if not update_num:
             failed_data = {"appid": self.appid, "openid": open_id, "update_data": {"status": 0, "subscribe": 0}}
             send_log(f'update_user_base_info_status_by_openid|{failed_data}')
             rsp["sign"] = 0
             rsp["msg"] = "do_unsubscribe|update_error"
     return rsp
コード例 #10
0
def do_authorization(data_dict):
    """授权事件处理"""
    if "AppId" in data_dict:
        try:
            appid = data_dict.get("AppId")  # 第三方平台Appid
            authorizer_appid = data_dict.get("AuthorizerAppid")  # 公众号appid
            pre_auth_code = data_dict.get("PreAuthCode")
            authorization_code = data_dict.get("AuthorizationCode")
            dao_wxapi.save("auth_code", authorization_code)
            dao_wxapi.save(authorization_code, pre_auth_code)

            com_access_token = dao_wxapi.read_data("com_access_token")
            if not com_access_token:
                send_log("com_access_token error", err=True)
            if data_dict.get("InfoType") != "component_verify_ticket":
                WechatOffAccPlatformMonitor.authorization_event(
                    data_dict.get("InfoType"), data_dict)
            if data_dict.get("InfoType") == "authorized":
                # 授权成功
                send_log("AuthorizedInfo: " + str(data_dict))
                rsp_dict = authorization.authorizer_access_token(
                    authorization_code)
                if rsp_dict.get("sign"):
                    rsp_dict["msg"] = "授权成功"
                else:
                    rsp_dict["msg"] = "授权失败"
                    log_error("授权失败|授权信息: {}".format(str(data_dict)))

            elif data_dict.get("InfoType") == "unauthorized":
                # 取消授权
                send_log("UnauthorizedInfo: " + str(data_dict))
                # server_account_info 和 appid_map 中状态置0。
                rsp_dict = authorization.unauthorized(authorizer_appid)
                if rsp_dict["sign"]:
                    rsp_dict["msg"] = "已取消授权"

            elif data_dict.get("InfoType") == "updateauthorized":
                # 更新授权
                send_log("UpdateauthorizedInfo: " + str(data_dict))
                rsp_dict = authorization.authorizer_access_token(
                    authorization_code, False)
                if rsp_dict["sign"]:
                    update_list = authorization.refresh_info()
        except Exception as e:
            send_log(e.__class__.__name__ + '|' + str(e), err=True)

    return 1
コード例 #11
0
def ticket():
    """微信公众号后台自动调用,每十分钟一次"""
    try:
        postdata, msg_signature, timestamp, nonce, auth_code, ex = get_paras()
        postdata = access.decryption(postdata, msg_signature, timestamp, nonce)
        data_dict = postdata.get("xml")
        ticket = data_dict.get("ComponentVerifyTicket")
        dao_wxapi.save("nonce", nonce)
        if ticket:
            dao_wxapi.save("ticket", ticket)

            # 使用ticket更新com_access_token
            authorization.com_access_token()

        # 授权处理
        sign = do_authorization(data_dict)  # 授权事件处理

    except Exception as e:
        send_log(e.__class__.__name__ + '|' + str(e), err=True)
    return Response('success')
コード例 #12
0
def authorizer_access_token(auth_code, set_map=True):
    # 通过com_access_token获取公众号/小程序接口调用凭据/令牌
    # 以及刷新凭据/刷新令牌
    rsp_dict = {"sign": 0, "msg": ''}
    com_access_token = dao_wxapi.read_data("com_access_token")
    auth_code = auth_code  # dao_wxapi.read_data("auth_code")
    data = {"component_appid": appid, "authorization_code": auth_code}
    url_authorizer_access_token = config.URL_AUTHORIZER_ACCESS_TOKEN.format(
        com_access_token)
    dict_data = request("POST", url_authorizer_access_token, data)
    send_log("AuthorizationAccountInfo:" + str(dict_data))
    auth_info_all = ''
    if "authorization_info" in dict_data:
        # 授权信息
        rsp_dict = do_authorizer_access_token(dict_data,
                                              auth_code,
                                              set_map=set_map)
    else:
        rsp_dict["msg"] = "微信服务器故障: authorizer_info not in response"

    return rsp_dict
コード例 #13
0
def track(event, propertie={}):
    # 打点埋点统计
    properties = json.dumps(propertie)
    created = time.time().as_integer_ratio()[0]
    data = {
        "event": event,
        "properties": properties,
        "created": created,
    }
    params = {"data": json.dumps([data])}
    url = config.URL_TRACK
    resp = requests.request("POST", url, data=params)
    js_resp = resp.json()
    err = False
    if js_resp.get("status") == 0 and js_resp.get("request_id"):
        err = False
    else:
        err = True
    send_log("track|params: {}, track_massage: {}".format(
        params["data"],
        js_resp.get("message") or ''),
             err=err)
コード例 #14
0
 def do_some(self, data: dict) -> dict:
     nonce = data.get("nonce")
     event_type = data.get("Event") or ''
     event_key = data.get("EventKey") or ''
     worker_key = event_key or event_type
     if "Get_This_Guy" in worker_key:
         worker_key = "Get_This_Guy"
     worker = self.get_worker(worker_key) or self.get_worker(self.sorter(worker_key, event_type))
     rsp = {"sign": 0, "msg": ""}
     err = False
     if not worker:
         rsp["msg"] = "不支持此功能"
         if self.nickname == "这样才好" and event_key and event_type != "view_miniprogram":
             err = True
         no_worker_log = {"hos_name": self.nickname, "event_type": event_type, "event_key": event_key, "data": data, "nonce": nonce}
         send_log(f'do_some|no_worker|{no_worker_log}', err=err)
     else:
         # 处理事件
         rsp = worker(data)
         worker_rsp_log = {"nonce": nonce, "worker_name": worker.__name__, "data": data, "rsp": rsp}
         send_log(f'do_some|worker_run|{worker_rsp_log}')
     return rsp
コード例 #15
0
def wx_event(appid: str, data: dict) -> dict:
    """事件处理"""
    try:
        nonce = data.get("nonce")
        rsp = {"sign": 0, "msg": ""}
        client_dict = get_maps("client_dict", {"fake_appid": config.DEBUG_LOG["fake_appid"]})
        client = client_dict.get(appid)
        if client:
            clienter = client(appid)
            if appid == "waa111asdw43f3b5":
                # 强制性修改特殊信息
                clienter.nickname = TEST_ZYClient(appid).nickname
                clienter.Get_This_Guy_values["template_id"] = TEST_ZYClient(appid).Get_This_Guy_values["template_id"]
                try:
                    clienter.Get_This_Guy_values["pagepath"] = client_dict.get(config.DEBUG_LOG["fake_appid"])(
                        config.DEBUG_LOG["fake_appid"]).Get_This_Guy_values["pagepath"]
                    send_log(f'CLIENTER_INFO||{clienter.config_data}')
                except Exception as e:
                    log_error(f'clienter.Get_This_Guy_values[pagepath] error {config.DEBUG_LOG["fake_appid"]}')
                clienter.thumb_media_id = TEST_ZYClient(appid).thumb_media_id
                if config.DEBUG_LOG["fake_appid"] != appid:
                    send_log(f'Get_This_Guy_values||{clienter.Get_This_Guy_values}')
            rsp = clienter.do_some(data)
        else:
            event = data.get("Event")
            no_client_log = {"nonce": nonce}
            send_log(f'wx_event|no_client|{no_client_log}')
            rsp["msg"] = f'{event} from_callback'
        if not rsp:
            rsp = {"sign": 0, "msg": "worker error."}
            worker_error_log = {"nonce": nonce}
            log_error(f'wx_event|worker_error|{worker_error_log}')
        return rsp
    except Exception as e:
        send_log(e.__class__.__name__ + str(e), err=True)
        return rsp
コード例 #16
0
def send_pic_cont(fromu, tou, nonce, appid):
    """send all text msg"""
    reply_xml = ''
    news_data = {
        'xml': {
            'ToUserName': '',
            'FromUserName': '',
            'CreateTime': '',
            'MsgType': 'news',
            'ArticleCount': '',
            'Articles': {
                'item': []
            }
        }
    }
    if appid in lib_config.HOS_CONFIG_DICT and "NEWS_DATA" in lib_config.HOS_CONFIG_DICT[
            appid]:
        NEWS_DATA = lib_config.HOS_CONFIG_DICT[appid]["NEWS_DATA"]

        news_data["xml"]["ToUserName"] = fromu
        news_data["xml"]["FromUserName"] = tou
        news_data["xml"]["CreateTime"] = int(time.time())
        news_data["xml"]["ArticleCount"] = len(NEWS_DATA)
        news_data["xml"]["Articles"]["item"] = NEWS_DATA

        reply_xml = xmltodict.unparse(news_data)

    elif tou == "gh_a46bnkejrve":
        reply_xml = """
        <xml>
            <ToUserName><![CDATA[{toUser}]]></ToUserName>
            <FromUserName><![CDATA[{fromUser}]]></FromUserName>
            <CreateTime>{crTime}</CreateTime>                                                                                                                                                   <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>2</ArticleCount>
            <Articles>
                <item>
                    <Title><![CDATA[{title1}]]></Title>
                    <Description><![CDATA[{description1}]]></Description>
                    <PicUrl><![CDATA[{picurl}]]></PicUrl>
                    <Url><![CDATA[{url1}]]></Url>
                </item>
                <item>
                    <Title><![CDATA[{title2}]]></Title>
                    <Description><![CDATA[{description2}]]></Description>
                    <PicUrl><![CDATA[{picur2}]]></PicUrl>
                    <Url><![CDATA[{url2}]]></Url>
                </item>
            </Articles>
        </xml>""".format(
            **{
                "toUser":
                fromu,
                "fromUser":
                tou,
                "crTime":
                int(time.time()),
                "title1":
                "标题1",
                "title2":
                "「用药指导」上线啦!10秒读懂怎么用",
                "description1":
                "",
                "description2":
                "",
                "picurl":
                "http://mmbiz.qpic.cn/mmbiz_jpg/YFhgtzRnDryjQHnTkmfHKO1J4OnaLv7sl0gdrtfyuihjngvhujskmYzP1er64A/0?wx_fmt=jpeg",
                "picur2":
                "http://mmbiz.qpic.cn/mmbiz_jpg/YFhgtzRnDrwlMKBRZYpMRcFiaqgdiacsjeftyuhnjskqHN1H1zNRh9QicaSMoTqXt3oian26GQyxNEB85Ssg/0?wx_fmt=jpeg",
                "url1":
                "https://mp.weixin.qq.com/s?__biz=MzUzMDg0NTA2Mg==&mid=100000005&idx=1&sn=c0cbwuendewncfdea42a26f67156&chksm=7a4addec4d3d54fa32c0b52b32b92be68fdf99c52ba50c8851a6833bc13f3d5ef78fa58a2d69#rd",
                "url2":
                "http://mp.weixin.qq.com/s?__biz=MzUzMDg0NTA2Mg==&mid=10000000ughijejwncvrb26985b0eb0b60e48c&chksm=7a4addec4d3d54faebfaae51e0c6e9507132c038dcf35443ecefaace77e46fa6d8ecda662ace#rd",
            })
    elif tou == "gh_6ba3asaeef0":
        reply_xml = """
        <xml>
            <ToUserName><![CDATA[{toUser}]]></ToUserName>
            <FromUserName><![CDATA[{fromUser}]]></FromUserName>
            <CreateTime>{crTime}</CreateTime>                                                                                                                                                   <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>3</ArticleCount>
            <Articles>
                <item>
                    <Title><![CDATA[{title1}]]></Title>
                    <Description><![CDATA[{description1}]]></Description>
                    <PicUrl><![CDATA[{picurl}]]></PicUrl>
                    <Url><![CDATA[{url1}]]></Url>
                </item>
                <item>
                    <Title><![CDATA[{title2}]]></Title>
                    <Description><![CDATA[{description2}]]></Description>
                    <PicUrl><![CDATA[{picur2}]]></PicUrl>
                    <Url><![CDATA[{url2}]]></Url>
                </item>
                <item>
                    <Title><![CDATA[{title3}]]></Title>
                    <Description><![CDATA[{description3}]]></Description>
                    <PicUrl><![CDATA[{picur3}]]></PicUrl>
                    <Url><![CDATA[{url3}]]></Url>
                </item>
            </Articles>
        </xml>""".format(
            **{
                "toUser":
                fromu,
                "fromUser":
                tou,
                "crTime":
                int(time.time()),
                "title1":
                "精致组织部落丨创新“互联网+医疗”,打造“指尖上的组织部落”——新版微信公众号上线啦",
                "title2":
                "请查收!你的专属「用药指导」",
                "title3":
                "住院费用明细,扫码全知道",
                "description1":
                "在手机上动动指尖,挂号、缴费、查看报告就能便捷完成,省去了排队等候、反复奔波的辛苦;",
                "description2":
                "平时去组织部落看病,我们听到医生说的最多话就是:遵医嘱、按时服药、规律服药、规律治疗、定期复查等。",
                "description3":
                "组织部落费用一直都是大家很关心的问题,我院全新上线了「扫腕带查清单」功能,只要扫一扫腕带上的二维码,所有费用一目了然。",
                "picurl":
                "http://mmbiz.qpic.cn/mmbiz_jpg/J9nmfvFevLzusUibk9fcdvfb52icgcTZE7VPx1UYaHMs8yIDDDc7rI8D0icrWOdkfQUg/0?wx_fmt=jpeg",
                "picur2":
                "http://mmbiz.qpic.cn/mmbiz_jpg/J9nmfvFevLzusUibk9TcbbdcpR9vXEaULkTuyeeZOxbR8HTP2WzM40Kic7al1fibVfUg/0?wx_fmt=jpeg",
                "picur3":
                "http://mmbiz.qpic.cn/mmbiz_jpg/J9nmfvFevLzusUibk9TcbqAYXdcwe2fgvb6sEJ2ZpoVPCURHdPEhPwnSIWKLwQf9SpFyA/0?wx_fmt=jpeg",
                "url1":
                "http://mp.weixin.qq.com/s?__biz=MzI5MjEyMTExOQ==&mid=506776731&idx=1&sn=c2bf0414cdsfer34fg175204c1b8968&chksm=77c653eb40b1dafd391f334ee1a8a35ab68bf78b321d97805839f7a1013e369e27c3601ea426#rd",
                "url2":
                "http://mp.weixin.qq.com/s?__biz=MzI5MjEyMTExOQ==&mid=506776731&idx=2&sn=5bbb93dvew3rvede4f15f65b&chksm=77c653eb40b1dafda1987feee0f1403979d5891adfedc4678a4ff47bab9ad41f316ad6319b6f#rd",
                "url3":
                "http://mp.weixin.qq.com/s?__biz=MzI5MjEyMTExOQ==&mid=506776731&idx=3&sn=16eadf39ewegbdve9105cc04d52b6&chksm=77c653eb40b1dafdcf778075e4e44d07365c3e68f36266cd3e1bf92beb4d38007f7dbcbeb5c6#rd",
            })
    encryper = access3.WXBizMsgCrypt(lib_config.TOKEN,
                                     lib_config.ENCODINGAESKEY,
                                     lib_config.WXAPPID)
    #ret, encrypt_xml = encryper.encrypt_msg(reply_msg=reply_xml, nonce=nonce)
    ret, encrypt_xml = encryper.EncryptMsg(reply_xml, nonce)
    log_dict = {
        "ret": ret,
        "reply_xml": reply_xml,
        "nonce": nonce,
        "fromu": fromu,
        "tou": tou
    }
    send_log(f'send_pic_cont|{log_dict}')
    return Response(encrypt_xml, mimetype='text/xml')
コード例 #17
0
def msg(appid):
    """接受用户消息和事件"""
    logger.info("msg_or_event: " + appid)
    postdata, msg_signature, timestamp, nonce, auth_code, ex = get_paras()
    postdata = access.decryption(postdata, msg_signature, timestamp, nonce)
    log_info("User Msg:" + json.dumps(postdata))

    if postdata:
        data_dict = postdata.get("xml")
        data_dict["nonce"] = nonce
        source_appid = data_dict.get("ToUserName")
        user_openid = data_dict.get("FromUserName")
        msg_id = data_dict.get("MsgId")
        msg_type = data_dict.get("MsgType")
        creat_time = data_dict.get("CreateTime")
        if appid != "wx570bc396a51b8ff8":
            try:
                auth_token_access = dao_wxapi.read_info(
                    appid)["authorizer_access_token"]
            except:
                log_error("get auth_token_access error: appid{}".format(appid))
                return Response('')
        response = {}
        if "MsgId" in data_dict and not msg_id:
            # 微信多次请求
            return Response("success")
        # 全网发布测试
        if msg_type == "event":
            rsp = wx_workers.wx_event(appid, data_dict)
            #if rsp["sign"] == 2:
            # sign == 2 时,对用户进行反馈
            if not rsp["sign"] and appid == "waa111asdw43f3b5":
                # 这样才好返回失败原因debug
                return send_text_cont(fromu=user_openid,
                                      tou=source_appid,
                                      cont=rsp["msg"],
                                      nonce=nonce)
            elif rsp.get("reply_news"):
                # 优先发送图文
                return send_pic_cont(fromu=user_openid,
                                     tou=source_appid,
                                     nonce=nonce,
                                     appid=appid)
            elif rsp.get("reply_txt"):
                return send_text_cont(fromu=user_openid,
                                      tou=source_appid,
                                      cont=rsp["msg"],
                                      nonce=nonce)

        elif msg_type == "text":
            msg_content = data_dict.get("Content")
            log_info('got the content %s' % msg_content)
            if msg_content == "TESTCOMPONENT_MSG_TYPE_TEXT":
                reply_cont = msg_content + "_callback"
                return send_text_cont(fromu=user_openid,
                                      tou=source_appid,
                                      cont=reply_cont,
                                      nonce=nonce)
            elif msg_content and msg_content.startswith('QUERY_AUTH_CODE'):
                # 测试
                query_auth_code = msg_content.split(':')[1]
                com_access_token = dao_wxapi.read_data("com_access_token")
                auth_code = query_auth_code
                if appid:
                    info = dao_wxapi.read_info(appid)
                    send_log(f'{appid}###info: {info}')
                    if "authorizer_access_token" in info:
                        authorizer_access_token = dao_wxapi.read_info(
                            appid)["authorizer_access_token"]
                        post_cont = auth_code + '_from_api'
                        gevent.spawn(
                            post_custom_text_msg, **{
                                "touser": user_openid,
                                "content": post_cont,
                                "stoken": authorizer_access_token
                            }).join()
                return send_bank_response()

        if msg_type == "text":
            msg_content = data_dict.get("Content")
            rsp_data_dict = postdata

            url = config.URL_MSGCUSTOM.format(auth_token_access)
            if "id" in msg_content or "ID" in msg_content or "同煤数据" in msg_content:
                # 便捷获取openid
                reply_cont = ''
                if "debug" in msg_content:
                    try:
                        debug_setting = msg_content.split("::")[-1]
                        debug_setting_dict = json.loads(debug_setting)
                        config.DEBUG_LOG["touser"] = user_openid
                        config.DEBUG_LOG["switch"] = debug_setting_dict.get(
                            "switch") or 0
                        config.DEBUG_LOG["log_key"] = debug_setting_dict.get(
                            "log_key") or 'WOW'
                        config.DEBUG_LOG[
                            "fake_appid"] = debug_setting_dict.get(
                                "fake_appid") or config.DEBUG_LOG["fake_appid"]
                        msg_list = [str(i) for i in config.DEBUG_LOG.values()]
                        msg_str = ','.join(msg_list)
                        reply_cont = msg_str
                    except:
                        reply_cont = """id,debug::{"log_key": "Authorization", "switch": 1}"""
                elif "app" in msg_content:
                    reply_cont = appid
                    if "source" in msg_content:
                        reply_cont = source_appid
                elif "学我" in msg_content or "follow" in msg_content:
                    reply_cont = msg_content
                elif "数据卡了" in msg_content and source_appid == "gh_1adc6e723b39":
                    reply_cont = "https://web.zusadeng.com/p-record?app_id=5dw 29ea2ea76d3529ad5"
                else:
                    reply_cont = user_openid
                return send_text_cont(fromu=user_openid,
                                      tou=source_appid,
                                      cont=reply_cont,
                                      nonce=nonce)
            logger.info("Send msg custom from {} to {}".format(
                user_openid, appid))
        elif msg_type == "voice":
            return send_bank_response(nonce=nonce)
        elif msg_type == "image":
            return send_bank_response(nonce=nonce)
        elif msg_type == "link":
            return send_bank_response(nonce=nonce)
    else:
        none_log = {
            "appid": appid,
            "msg_signature": msg_signature,
            "nonce": nonce,
            "auth_code": auth_code,
            "ex": ex
        }
        send_log(f"MSG|postdata is None|{none_log}", err=True)

    return Response('success')
コード例 #18
0
def send_bank_response(nonce=None):
    """send bank msg"""
    bank_log = {"nonce": nonce}
    send_log(f"send_bank_response|{bank_log}")
    return Response('')
コード例 #19
0
def do_refresh_info(info_dict_data: dict, old_info: dict = {}) -> dict:
    """
    刷新appid_map表信息(《左开台》&&《微信开放平台》的appid映射,以及各个appid为第三方平台的授权信息 )
    
    顺便刷新授权方的账号基本信息(有更改则刷新,无则跳过)
    头像、昵称、账号类型、认证类型、微信号、原始ID和二维码URL
    """
    rsp_dict = {"sign": 0, "msg": ''}
    authorizer_appid = info_dict_data.get("authorization_info").get(
        "authorizer_appid") if info_dict_data.get("authorization_info") else ''
    if "authorizer_info" in info_dict_data:
        auth_info_all = json.dumps(info_dict_data, ensure_ascii=False)
        auth_info = info_dict_data["authorizer_info"]
        nick_name = auth_info["nick_name"]
        service_type_info = int(auth_info["service_type_info"]["id"])
        user_name = auth_info["user_name"]
        principal_name = auth_info["principal_name"]
        qrcode_url = auth_info["qrcode_url"]
        expire_ts = 9999
    else:
        nick_name = ''  # auth_info["nick_name"]
        service_type_info = ''  # int(auth_info["service_type_info"]["id"])
        user_name = ''  # auth_info["user_name"]
        principal_name = ''  # auth_info["principal_name"]
        qrcode_url = ''  # auth_info["qrcode_url"]
        expire_ts = 0
        log_error("获取信息失败: info_dict_data: {}, ".format(str(info_dict_data)))

    logger.info("获得授权方账号信息|%s|%s", nick_name, principal_name)
    # 接入服务号到本服务器
    # 存储
    save_info_data = {
        "appid": authorizer_appid,
        "nick_name": nick_name,
        "principal_name": principal_name,
        "qrcode_url": qrcode_url,
    }
    if not authorizer_appid:
        save_info_data["appid"] = old_info["appid"]
    merge_info = {**old_info, **save_info_data}
    if old_info and merge_info != old_info:
        insert_id = dao_wxapi.update_base_info(**save_info_data)
        send_log(
            "AuthorizationRefresh|BaseInfoMerge|old_info: {}, save_info_data: {}, insert_id: {}"
            .format(str(old_info), str(save_info_data), str(insert_id)))
    elif not old_info:
        insert_id = dao_wxapi.update_base_info(**save_info_data)
    else:
        insert_id = True
    if insert_id:
        auth_info_data = {
            "wechat_appid": authorizer_appid,
            "nick_name": nick_name,
            "auth_info": auth_info_all,
        }
        insert_id2_dict = dao_wxservice.update_auth_info(auth_info_data)
        send_log(
            "AuthorizationRefresh|DetailInfo|auth_info_data: {}, insert_id2_dict: {}"
            .format(str(auth_info_data), str(insert_id2_dict)))
        if not insert_id2_dict.get("sign"):
            log_error(rsp_dict["msg"])
            rsp_dict[
                "msg"] = "update_auth_info error. auth_info_data: {}".format(
                    auth_info_data)
    else:
        insert_id2_dict = {"sign": 0, "msg": "save base info error."}
        rsp_dict = insert_id2_dict
    if insert_id and insert_id2_dict.get("sign"):
        # pre_auth_code, 一个预授权码,只能被一个公众号接入, 但blueprints中保证了每次都会新生成一个pre_auth_code
        rsp_dict["sign"] = 1

    return rsp_dict
コード例 #20
0
def do_authorizer_access_token(dict_data: dict,
                               auth_code: str,
                               set_map: bool = True,
                               test_data: dict = {}) -> dict:
    rsp_dict = {"sign": 0, "msg": ''}
    com_access_token = dao_wxapi.read_data("com_access_token")
    authorizer_appid = dict_data["authorization_info"]["authorizer_appid"]
    dao_wxapi.save("authorizer_appid", authorizer_appid)
    authorizer_access_token = dict_data["authorization_info"][
        "authorizer_access_token"]
    dao_wxapi.save("authorizer_access_token", authorizer_access_token)

    authorizer_refresh_token = dict_data["authorization_info"][
        "authorizer_refresh_token"]
    dao_wxapi.save("authorizer_refresh_token", authorizer_refresh_token)
    auth_ex = int(dict_data["authorization_info"]['expires_in'])

    # 顺便获取授权方的账号基本信息
    #头像、昵称、账号类型、认证类型、微信号、原始ID和二维码URL
    url_getinfo = config.URL_GETINFO.format(com_access_token)
    data_info = {
        "component_appid": appid,
        "authorizer_appid": authorizer_appid
    }
    info_dict_data = request("POST", url_getinfo, data_info)
    send_log("AuthorizationAccountInfoDetail:" + str(info_dict_data))
    auth_info_all = ''
    if ("authorizer_info" in info_dict_data) or test_data:
        if "authorizer_info" in test_data and "authorization_info" in test_data:
            info_dict_data = test_data
        auth_info_all = json.dumps(info_dict_data, ensure_ascii=False)
        auth_info = info_dict_data["authorizer_info"]
        nick_name = auth_info["nick_name"]
        service_type_info = int(auth_info["service_type_info"]["id"])
        verify_type_info = int(auth_info["verify_type_info"]["id"])
        user_name = auth_info["user_name"]
        principal_name = auth_info["principal_name"]
        qrcode_url = auth_info["qrcode_url"]
        expire_ts = int(time.time()) + auth_ex - 11 * 60
    else:
        nick_name = ''  # auth_info["nick_name"]
        service_type_info = ''  # int(auth_info["service_type_info"]["id"])
        verify_type_info = ''  # int(auth_info["verify_type_info"]["id"])
        user_name = ''  # auth_info["user_name"]
        principal_name = ''  # auth_info["principal_name"]
        qrcode_url = ''  # auth_info["qrcode_url"]
        expire_ts = 0
        log_error("获取信息失败: wxappid: {}, info_dict_data: {}".format(
            authorizer_appid, str(info_dict_data)))

    logger.info("获得授权方账号信息|%s|%s", nick_name, principal_name)
    if service_type_info != 2:  # 2 表示服务号
        logger.info("接入的公众号不是服务号|%s|%s", nick_name, principal_name)
    else:
        logger.info("接入的公众号是服务号|%s|%s", nick_name, principal_name)

    if verify_type_info == -1:
        logger.warning("接入的公众号未经认证|%s|%s", nick_name, principal_name)

    # 接入服务号到本服务器
    # 存储
    save_info_data = {
        "appid": authorizer_appid,
        "authorizer_access_token": authorizer_access_token,
        "authorizer_refresh_token": authorizer_refresh_token,
        "expires_ts": expire_ts,
        "nick_name": nick_name,
        "user_name": user_name,
        "principal_name": principal_name,
        "qrcode_url": qrcode_url,
    }
    insert_id = dao_wxapi.save(authorizer_appid, save_info_data)
    send_log("AuthorizationAccountSaveBaseInfo|insert_id: {}".format(
        str(insert_id)))
    if insert_id and set_map:
        # 基本信息插入成功,并且需要建立两方appid map
        pre_auth_code = dao_wxapi.read_data(auth_code) or ''
        log_info("get_pre_code_back: {}".format(auth_code))
        auth_info_data = {
            "pre_auth_code": pre_auth_code,
            "wechat_appid": authorizer_appid,
            "nick_name": nick_name,
            "auth_info": auth_info_all,
        }
        insert_id2_dict = dao_wxservice.update_auth_info(auth_info_data)
        send_log("AuthorizationAccountSaveInfoDetail|inser_dict: {}".format(
            str(insert_id2_dict)))
        if not insert_id2_dict.get("sign"):
            send_log("Authorized_Update_Map_Error")
            retry_appid = dao_wxapi.read_data(pre_auth_code) or pre_auth_code
            retry_auth_info_data = {
                "appid": retry_appid,
                "pre_auth_code": pre_auth_code,
                "wechat_appid": authorizer_appid,
                "nick_name": nick_name,
                "auth_info": auth_info_all,
            }
            send_log("Retry_Save: {}".format(str(retry_auth_info_data)),
                     err=True)
            if retry_appid and authorizer_appid and pre_auth_code:
                # 删除占位,重新写入
                del_data1 = dao_wxservice.get_auth_info(retry_appid, '')
                del_data2 = dao_wxservice.get_auth_info('', pre_auth_code)
                send_log("Del_Data: del_data1: {}, del_data2: {}".format(
                    str(del_data1), str(del_data2)),
                         err=True)
                dao_wxservice.real_delete_by(retry_appid, pre_auth_code)
                dao_wxservice.save(retry_auth_info_data)
        if not insert_id2_dict.get("sign"):
            log_error(rsp_dict["msg"])
            rsp_dict[
                "msg"] = "update_auth_info error. auth_info_data: {}".format(
                    auth_info_data)
    if insert_id:
        # pre_auth_code, 一个预授权码,只能被一个公众号接入, 但blueprints中保证了每次都会新生成一个pre_auth_code
        rsp_dict["sign"] = 1

    return rsp_dict
コード例 #21
0
    "wx89521qasdadqw": TMClient,
    "wx135021dewcad05d": WHClient,
    "wx12e2asf21cfsda": DPClient,
    "sa2wddcscsb31469": JNChildClient,
    "2dewecbd47a141ec": HNChildClient,
    "asdasdc621c661": PGComityClient,
    "wx2ad47e142abe2ededs": HeBUniversityClient,
    "qwdcwvcd1fcb3647": ZYMedicalClient,
    "wx7ae5c0qwdwcd40a8": ZYHealthClient,
    "wdf2e34frv438743b": GZh_University_Client,
}

lib_config.HOS_CONFIG_DICT = get_all_config(CLIENT_DICT)
HOS_CONFIG_DICT = lib_config.HOS_CONFIG_DICT
for i in HOS_CONFIG_DICT.items():
    send_log(f'HOS_CONFIG_DICT||{i}')


def update_hos_config(appid) -> dict:
    """更新HOS_CONFIG_DICT"""
    global HOS_CONFIG_DICT
    lib_config.HOS_CONFIG_DICT[appid] = get_hos_cfg.get_config(appid)
    HOS_CONFIG_DICT = lib_config.HOS_CONFIG_DICT
    send_log(f'HOS_CONFIG_DICT||{appid}||{HOS_CONFIG_DICT[appid]}')
    return HOS_CONFIG_DICT[appid]


"""
# 测试
test_client = CLIENT_DICT["wx89521qasdadqw"]("wx89521qasdadqw")
"""