Пример #1
0
    def get(self, error_key):
        if self.args.get("verify") != "senguoph":
            return self.write("<h1>HTTP 403</h1>")

        # 错误信息
        server_error = "Ph_Server_Error:%s" % error_key
        if redis.exists(server_error):
            try:
                error_msg = json.loads(redis.get(server_error).decode("utf-8"))
            except:
                error_msg = redis.get(redis.get(server_error))
        else:
            error_msg = '错误信息已失效'

        # 剩余时间
        try:
            time_left = int(redis.ttl(server_error) / (60 * 60))
        except:
            time_left = 0

        # 出错次数
        server_error_times = "Ph_Server_Error_Times:%s" % error_key
        try:
            times = redis.get(server_error_times) or 1
        except:
            times = 1

        # 封面
        error_cover_img = redis.get("Ph_Server_Error_Cover")
        if not error_cover_img:
            error_cover_img = "https://picsum.photos/500/300/?random"

        return self.render("server_error.html", error_msg=error_msg,
                           time_left=time_left, times=times, error_cover_img=error_cover_img)
Пример #2
0
 def getAppauthToken(cls, admin_id=None):
     if admin_id:
         ali_app_auth_token = "ali_app_auth_token:%s" % admin_id
         ali_app_refresh_token = "ali_app_refresh_token:%s" % admin_id
     else:
         ali_app_auth_token = "ali_app_auth_token_senguo"
         ali_app_refresh_token = "ali_app_refresh_token_senguo"
     if redis.get(ali_app_auth_token
                  ) and redis.ttl(ali_app_auth_token) > 3600 * 24 * 30:
         ali_auth_token = redis.get(ali_app_auth_token).decode('utf-8')
     elif redis.get(ali_app_refresh_token):
         ali_refresh_token = redis.get(ali_app_refresh_token).decode(
             'utf-8')
         if_success, ret_dict = cls.get_ali_auth_token(
             "refresh_token", ali_refresh_token)
         if if_success:
             ali_auth_token = ret_dict["app_auth_token"]
             redis.set(ali_app_auth_token, ali_auth_token,
                       ret_dict["expires_in"])
             redis.set(ali_app_refresh_token, ret_dict["app_refresh_token"],
                       ret_dict["re_expires_in"])
         else:
             ali_auth_token = None
     else:
         ali_auth_token = None
     return ali_auth_token
Пример #3
0
 def get_pwd_token(cls, session, id):
     user_pwd_token_key='user_pwd_token:%d'%id
     if redis.get(user_pwd_token_key):
         token = redis.get(user_pwd_token_key).decode()
     else:
         try:
             token = session.query(Accountinfo.password).filter_by(id=id).scalar()[24:48]
         except:
             token = ""
     return token
Пример #4
0
def check_msg_token(phone, code, use):
    h = "cf_verify_code:{}:{}".format(use, phone)
    old_code = redis.get(h)
    redis.delete(h)
    if old_code and old_code.decode("utf-8") == str(code):
        return True
    else:
        return False
Пример #5
0
 def make_scene_id_len8():
     '''8位随机数'''
     import random
     while 1:
         scene_id = random.randint(10000000,99999999)
         if not redis.get('pf_scene_openid:%s' % scene_id):
             break
     return scene_id
Пример #6
0
 def get_client_access_token(cls):  # 微信接口调用所需要的access_token,不需要用户授权
     access_token = redis.get('pf_access_token')
     if access_token:
         return access_token.decode('utf-8')
     else:
         data = json.loads(urllib.request.urlopen(cls.client_access_token_url).read().decode("utf-8"))
         if 'access_token' in data:
             access_token = data['access_token']
             redis.set("pf_access_token",access_token,3600)
             return access_token
         else:
             return None
Пример #7
0
    def bind_wx(self):
        """绑定微信"""
        scene_id = self.args['scene_id']

        wx_userinfo = pf_redis.get('pf_scene_openid:%s' % scene_id)
        if not wx_userinfo:
            return self.send_success(done=False)
        wx_userinfo = json.loads(wx_userinfo.decode())
        wx_unionid = wx_userinfo["unionid"]

        # 绑定微信
        if len(str(scene_id)) == 8:
            bind_key = "ph_scene_bind_account:%s" % scene_id
            bind_user_id = redis.get(bind_key) or -1
            user = models.AccountInfo.get_by_id(self.session, bind_user_id)

            # scene_id 不对或者 Redis 的 key 过期了
            if not user or not user.passport_id:
                return self.send_fail("请刷新页面后重试")

            success, errmsg = AuthFunc.update_passportinfo(
                user.passport_id, "wx_unionid", wx_unionid)
            if not success:
                if errmsg == "NOT EXIST":
                    return self.send_fail("账户不存在,请联系森果客服 400-027-0135")
                elif errmsg == "SAME VALUE":
                    # 重复绑定是为了取微信信息
                    pass
                elif errmsg == "ALREADY BIND":
                    return self.send_fail("该微信已被其他账户绑定")
                else:
                    return self.send_fail("绑定失败,请联系森果客服 400-027-0135")

            redis.delete(bind_key)
        else:
            return self.send_fail("scene_id 无效")

        pf_redis.delete('pf_scene_openid:%s' % scene_id)
        redis.delete("ph_scene_bind_account:%s" % scene_id)

        # 更新微信信息
        AuthFunc.update_through_wx(self.session,
                                   wx_userinfo,
                                   user,
                                   action="bind")
        return self.send_success(done=True)
Пример #8
0
 def send_server_error(cls, slave_session, request_uri, **kwargs):
     """服务器出现500错误时发送模板消息提醒
         服务器错误使用redis缓存72小时
         错误字典使用错误内容生成的md5值做key
         查看路径使用key参数用于查看不同的错误
     """
     import traceback
     import time
     import json
     from urllib import parse
     from handlers.base.pub_func import UrlShorten
     from dal.db_configs import redis
     server_error_messsage = traceback.format_exception(*kwargs["exc_info"])
     intro = '采购助手服务器500报错'
     content = '出错地址 ' + str(request_uri)
     time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     describe = '请尽快检查错误并修正'
     hour_now = int(datetime.datetime.now().strftime('%H'))
     timestamp = int(time.time())
     to_users = [104, 105, 156, 1085]
     acs = slave_session.query(models.Accountinfo.wx_openid).filter(
         models.Accountinfo.id.in_(to_users)).all()
     server_error_messsage = json.dumps(server_error_messsage)
     errror_key = UrlShorten.get_hex(server_error_messsage)
     server_error = "Server_Error:%s" % errror_key
     server_error_times = "Server_Error_Times:%s" % errror_key
     if redis.get(server_error):
         redis.incr(server_error_times)
     else:
         redis.set(server_error, server_error_messsage, 72 * 60 * 60)
         redis.set(server_error_times, 1, 72 * 60 * 60)
         for account in acs:
             try:
                 if hour_now in [4, 5, 6, 7]:
                     countdown = (9 - hour_now) * 3600 - 1800
                 else:
                     countdown = 0
                 # 暂时使用的
                 cls.send_servererror_msg(
                     account[0], "https://pf.senguo.cc/super/servererror/" +
                     str(errror_key), intro, content, time_now, describe)
             except:
                 pass
Пример #9
0
 def post(self):
     return self.write(redis.get("carrefour_update_info"))
Пример #10
0
    def resolve_openid(self,account_info,code,shop_admin,oauth_type):
        openid = account_info.wx_openid
        # 微信浏览器下,如果用户表中现存的openid不正确则重新获取并更新;正确则直接使用,不再重新获取
        if not openid or openid[:6] != OPENID_BEGIN :
            if len(code)<=2:
                # 商户绑定了认证服务号,返回基础授权链接(静默授权)
                if oauth_type==1:
                    path = APP_OAUTH_CALLBACK_URL + self.link
                    url = WxOauth2.createOauthUrlForCode(path,"snsapi_base","123")
                    return 1,url
                # 商户未绑定认证服务号,返回userinfo授权链接
                else:
                    path = APP_OAUTH_CALLBACK_URL + self.link
                    url = WxOauth2.createOauthUrlForCode(path,"snsapi_userinfo","STATE")
                    return 1,url
            else:
                # 根据code得到openid先
                wx_openid,access_token = WxOauth2.getOpenidByAppsecret(code)
                if wx_openid:
                    account_info.wx_openid=wx_openid
                    # 如果商户未绑定认证服务号,通过森果服务号userinfo接口更新用户信息
                    # 如果用户绑定了自己的认证服务号,则不走森果userinfo授权(只走下面的静默授权)
                    if oauth_type!=1:
                        # 根据授权接口里面得到的access_token和openid,得到其他的用户信息
                        wx_userinfo=WxOauth2.getWxInfo_SNS(wx_openid,access_token)
                        if wx_userinfo:
                            self.update_account_from_wxinfo(account_info,wx_userinfo)
                    # 根据基础支持接口的access_token和openid得到union_id
                    access_token = WxOauth2.get_client_access_token()
                    wx_userinfo=WxOauth2.getWxInfo_CGI(wx_openid,access_token)
                    if wx_userinfo:
                        account_info.subscribe=wx_userinfo["subscribe"]
                        account_info.wx_unionid=wx_userinfo["unionid"]
                        self.session.commit()
                    code=""
                else:
                    return 2,"获取用户信息失败,请联系森果客服(senguocc300)"

        #####################获取mp_customer_link###################
        # 商户绑定了自己的公众号
        if oauth_type:
            admin_id = shop_admin.id
            appid    = shop_admin.mp_appid
            has_mp_customer_link = self.session.query(models.Mp_customer_link.id).filter_by(customer_id=account_info.id,mp_appid=appid).first()
            if not has_mp_customer_link:
                sa_access_token = None
                from handlers.openwx import OpenComponent
                open_component = OpenComponent()
                # 自动绑定:需使用ComponentVerifyTicket获取微信openid
                if oauth_type == 1:
                    component_appid = 'wx2be982f79f0a405d'
                    if len(code)<=2:
                        path = 'https://i.senguo.cc' + self.link
                        url = WxOauth2.createOauthUrlForCode(path,"snsapi_userinfo","STATE",appid,component_appid)
                        return 1,url
                    else:
                        ComponentVerifyTicket = redis.get('component_verify_ticket').decode('utf-8')
                        if_success,ret_info = open_component.get_open_component_access_token()
                        if if_success:
                            component_access_token=ret_info
                        else:
                            return 2,ret_info
                        sa_wx_openid,sa_access_token = WxOauth2.getOpenidByComponentAppid(code,appid,component_appid,component_access_token)

                # 非自动绑定:需使用appid与appsecret获取微信openid
                elif oauth_type==2:
                    appsecret = shop_admin.mp_appsecret
                    if len(code)<=2:
                        path = APP_OAUTH_CALLBACK_URL + self.link
                        redirect_uri = tornado.escape.url_escape(path)
                        url = WxOauth2.createOauthUrlForCode(path,"snsapi_base","123",appid)
                        return 1,url
                    else:
                        sa_wx_openid,sa_access_token = WxOauth2.getOpenidByAppsecret(code,appid,appsecret)
                        sa_access_token = None

                if sa_wx_openid:
                    # 如果该用户在对应平台下存有wxopenid则更新,如果没有则生成
                    try:
                        admin_customer_openid = self.session.query(models.Mp_customer_link).filter_by(wx_openid=sa_wx_openid).one()
                        admin_customer_openid.update(session=self.session,customer_id=account_info.id, mp_appid=appid)
                    except:
                        admin_customer_openid = models.Mp_customer_link(customer_id=account_info.id, mp_appid=appid, wx_openid=sa_wx_openid)
                        self.session.add(admin_customer_openid)

                    # 根据基础支持接口的access_token和openid得到并更新用户是否关注的信息
                    if sa_access_token:
                        if not account_info.nickname or account_info.nickname[:2]=="用户":
                            wx_userinfo=WxOauth2.getWxInfo_SNS(sa_wx_openid,sa_access_token)
                            if wx_userinfo:
                                self.update_account_from_wxinfo(account_info,wx_userinfo)
                        auto_access_token = open_component.get_mp_auth_access_token_from_refreshtoken(component_access_token,shop_admin)
                        wx_userinfo=WxOauth2.getWxInfo_CGI(sa_wx_openid,auto_access_token)
                        if wx_userinfo:
                            try:
                                admin_customer_openid.subscribe=wx_userinfo["subscribe"]
                                if not admin_customer_openid.ever_subscribe:
                                    admin_customer_openid.ever_subscribe=wx_userinfo["subscribe"]
                            except:
                                wx_userinfo['time']=str(datetime.datetime.now())
                                wx_userinfo['admin_id']=str(shop_admin.id)
                                wx_userinfo['customer_id']=str(account_info.id)
                                log_msg_dict("get_wxinfo",wx_userinfo)
                    try:
                        self.session.commit()
                    except:
                        self.session.rollback()
        return 0,''
Пример #11
0
 def post(self):
     try:
         data = json.loads(redis.get("cgapp_update_info").decode())
     except ValueError as e:
         data = {}
     return self.write(data)