Exemple #1
0
def wx_code_to_access_token_fhlogin(request):
    try:
        code = request.GET.get("code")
        state = request.GET.get("state")
        fh_weixinschool = get_fh_weixinschool()
        school_id = fh_weixinschool.school_id
        school = fh_weixinschool.school
        if not school or not fh_weixinschool:
            return HttpResponseForbidden(
                u'<h1>Forbidden<br/> 烽火公众号系统异常,请联系系统管理员!</h1>')

        state = get_orginurl(state)['origin_url']
        param_dict = {
            "appid": fh_weixinschool.app_id,
            "secret": fh_weixinschool.app_secret,
            "code": code,
            "grant_type": "authorization_code"
        }
        param_str = urlencode(param_dict)
        uri = "https://api.weixin.qq.com/sns/oauth2/access_token?%s" % param_str
        logger.debug(uri)
        data_str = send_http_request(url=uri, method="GET")
        logger.debug(data_str)
        data = json.loads(data_str)
        if "errcode" in data or "openid" not in data or not data["openid"]:
            logger.error(uri)
            logger.error(data_str)
            return HttpResponseForbidden(data_str)

        # 拿到openid后,找到对应的account,使用cas登陆
        account = agents.get_account_byfhopenid(data["openid"])
        if not account:
            return HttpResponseForbidden(
                u'<h1>Forbidden<br/> 请先通过学校的公众号绑定帐号!</h1>')

        if settings.DEBUG:
            # 测试登录单系统
            account.backend = AUTHENTICATION_BACKENDS[1]
            auth.login(request, account)
            redirect_uri = convert_to_url_path(state)
        else:
            # cas登陆
            cas_wx_token = wxtoken_compose(account.id)
            redirect_uri = '%slogin?source=wx&token=%s&service=%s' % (
                settings.CAS_SERVER_URL, cas_wx_token,
                convert_to_url_path(state))

        return HttpResponseRedirect(redirect_uri)
    except Exception as ex:
        sErrInfo = traceback.format_exc()
        logger.error(sErrInfo)
        logger.error(ex.message)
        return HttpResponseForbidden(ex.message)
Exemple #2
0
def wx_update_weixinaccount(access_token, openid, school_id, account_id):
    try:
        param_dict = {
            "access_token": access_token,
            "openid": openid,
            "lang": "zh_CN",
        }
        param_str = urlencode(param_dict)
        uri = "https://api.weixin.qq.com/sns/userinfo?%s" % param_str
        logger.debug(uri)
        data_str = send_http_request(url=uri, method="GET")
        logger.debug(data_str)
        data = json.loads(data_str)
        if "errcode" in data or "openid" not in data or not data["openid"]:
            logger.error(uri)
            logger.error(data_str)
            return None
        # print data
        wx_openid = data["openid"]
        wx_nickname = data["nickname"]
        wx_sex = data["sex"]
        wx_province = data["province"]
        wx_city = data["city"]
        wx_country = data["country"]
        wx_headimgurl = data["headimgurl"]
        wx_unionid = data.get("unionid", "")

        weixinaccount = WeixinAccount.objects.get(school_id=school_id,
                                                  openid=wx_openid,
                                                  account_id=account_id,
                                                  del_flag=FLAG_NO)
        if not weixinaccount:
            raise Exception(u'系统异常,获取微信用户信息失败!')

        weixinaccount.name = wx_nickname
        weixinaccount.sex = wx_sex
        weixinaccount.province = wx_province
        weixinaccount.city = wx_city
        weixinaccount.country = wx_country
        weixinaccount.image_url = wx_headimgurl
        weixinaccount.unionid = wx_unionid
        weixinaccount.save()

        return
    except Exception as ex:
        logger.exception(ex)
        return response_exception(ex, ex.message)
Exemple #3
0
def update_weixin_global_access_token(weixinschool):
    if not weixinschool:
        raise BusinessException(ERR_GET_APPID)
    global_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + weixinschool.app_id + '&secret=' + weixinschool.app_secret
    # globalaccesstokeninfo = requests.get(global_access_token_url).text
    globalaccesstokeninfo = send_http_request(url=global_access_token_url,
                                              method="GET")
    globalaccesstokeninfo = json.loads(globalaccesstokeninfo)
    now_time = datetime.datetime.now()

    if globalaccesstokeninfo.get('access_token'):
        weixinschool.access_token = globalaccesstokeninfo.get('access_token')
        weixinschool.access_token_update_time = now_time + datetime.timedelta(
            seconds=int(globalaccesstokeninfo.get('expires_in')) / 2)
        weixinschool.save()
        # print settings.weixin_access_token_updatetime.strftime("%Y-%m-%d %H:%M:%S")
    else:
        # 获取accesstoken失败
        raise Exception(globalaccesstokeninfo)
    return globalaccesstokeninfo
Exemple #4
0
def wx_code_to_access_token_fh(request):
    try:
        code = request.GET.get("code")
        state = request.GET.get("state")
        fh_weixinschool = get_fh_weixinschool()
        school_id = fh_weixinschool.school_id
        school = fh_weixinschool.school
        if not school or not fh_weixinschool:
            return HttpResponseForbidden(
                u'<h1>Forbidden<br/> 烽火公众号系统异常,请联系系统管理员!</h1>')

        state = get_orginurl(state)['origin_url']
        param_dict = {
            "appid": fh_weixinschool.app_id,
            "secret": fh_weixinschool.app_secret,
            "code": code,
            "grant_type": "authorization_code"
        }
        param_str = urlencode(param_dict)
        uri = "https://api.weixin.qq.com/sns/oauth2/access_token?%s" % param_str
        logger.debug(uri)
        data_str = send_http_request(url=uri, method="GET")
        logger.debug(data_str)
        data = json.loads(data_str)
        if "errcode" in data or "openid" not in data or not data["openid"]:
            logger.error(uri)
            logger.error(data_str)
            return HttpResponseForbidden(data_str)

        # 此时应该登陆过,直接记录用户openid, 不请求用户其它资料,可以对用户免打扰。
        WeixinAccount.objects.filter(
            account=request.user,
            del_flag=FLAG_NO).update(openid_fh=data["openid"])

        redirect_uri = convert_to_url_path(state)
        return HttpResponseRedirect(redirect_uri)
    except Exception as ex:
        sErrInfo = traceback.format_exc()
        logger.error(sErrInfo)
        logger.error(ex.message)
        return HttpResponseForbidden(ex.message)
Exemple #5
0
def update_weixin_jsapi_ticket(weixinschool):
    if not weixinschool:
        raise BusinessException(ERR_GET_APPID)

    wx_access_token = get_weixin_global_access_token(weixinschool)

    jsapi_ticket_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + wx_access_token + '&type=jsapi'
    # jsapi_ticket_info = requests.get(jsapi_ticket_url).text
    jsapi_ticket_info = send_http_request(url=jsapi_ticket_url, method="GET")

    jsapi_ticket_info = json.loads(jsapi_ticket_info)
    now_time = datetime.datetime.now()

    if jsapi_ticket_info.get('ticket'):
        weixinschool.jsapi_ticket = jsapi_ticket_info.get('ticket')
        weixinschool.jsapi_ticket_update_time = now_time + datetime.timedelta(
            seconds=int(jsapi_ticket_info.get('expires_in')) / 2)
        weixinschool.save()
        # print settings.weixin_access_token_updatetime.strftime("%Y-%m-%d %H:%M:%S")
    else:
        # 获取accesstoken失败
        raise Exception(jsapi_ticket_info)
    return jsapi_ticket_info
Exemple #6
0
def wx_code_to_access_token(request):
    try:
        code = request.GET.get("code")
        state = request.GET.get("state")
        school_id = request.GET.get("sid", "")
        school = get_school_byid(school_id)
        weixinschool = get_weixin_school(school_id)
        if not school or not weixinschool:
            return HttpResponseForbidden(
                u'<h1>Forbidden<br/> 获取学校信息失败,请从手机微信公众号上登陆使用本系统。</h1>')

        state = get_orginurl(shorturl_id=state, del_indb=False)['origin_url']
        param_dict = {
            "appid": weixinschool.app_id,
            "secret": weixinschool.app_secret,
            "code": code,
            "grant_type": "authorization_code"
        }
        param_str = urlencode(param_dict)
        uri = "https://api.weixin.qq.com/sns/oauth2/access_token?%s" % param_str
        logger.debug(uri)
        data_str = send_http_request(url=uri, method="GET")
        logger.debug(data_str)
        data = json.loads(data_str)
        if "errcode" in data or "openid" not in data or not data["openid"]:
            logger.error(uri)
            logger.error(data_str)
            return HttpResponseForbidden(data_str)

        account = agents.get_account_byopenid(data["openid"], school_id)

        # 检查是否是学校码扫码进来的,如果是扫码且没有绑定,则获取到openid后,将openid跳转到家长绑定的页面,如果已经绑定,则跳转到学校首页
        state_url = convert_to_url_path(state)
        if 'wx/page/scan/schoolcode?sid=' in state_url:
            if not account:
                return HttpResponseRedirect(
                    "/m/register/enrollParent?sid=%s&openid=%s" %
                    (school_id, data["openid"]))
            else:
                return HttpResponseRedirect("/m?sid=%s" % school_id)

        # 检查是否是家长邀请码扫码进来的,则获取到openid后,将openid跳转到家长绑定的页面
        if 'wx/page/scan/parentcode?sid=' in state_url:
            params_get = state_url[state_url.find('?') + 1:]  # ?后面的所有参数
            return HttpResponseRedirect(
                "/m/personal/parent/addParent?%s&openid=%s" %
                (params_get, data["openid"]))

        # 检查是否是个人中心添加角色跳转过来
        if 'wx/page/add/role?sid=' in state_url:
            if not account:
                return HttpResponseForbidden(
                    u'<h1>Forbidden<br/> 请从个人中心=》添加角色页页进入。</h1>')
            else:
                account_mobile = account.mobile
                address = get_account_address(account)
                params_get = state_url[state_url.find('?') + 1:]  # ?后面的所有参数
                return HttpResponseRedirect(
                    "/m/register/identify?%s&openid=%s&mobile=%s&add=%s" %
                    (params_get, data["openid"], account_mobile, address))

        # 检查用户是否关注公众号
        weixin_global_access_token = agents.get_weixin_global_access_token(
            weixinschool)
        if weixinschool.force_follow:
            uri = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN' % (
                weixin_global_access_token, data["openid"])
            logger.debug(uri)
            wx_userinfo_str = send_http_request(url=uri, method="GET")
            logger.debug(wx_userinfo_str)
            wx_userinfo = json.loads(wx_userinfo_str)
            if "errcode" in wx_userinfo or "subscribe" not in wx_userinfo:
                logger.error(uri)
                logger.error(wx_userinfo_str)
                return HttpResponseForbidden(wx_userinfo_str)

            if wx_userinfo["subscribe"] == 0:
                if weixinschool.mp_image_url:
                    return HttpResponseRedirect(weixinschool.mp_image_url)
                else:
                    return HttpResponseForbidden(
                        u'<h1>Forbidden<br/> 使用系统前,请先关注%s微信公众号</h1>' %
                        weixinschool.school.name_full)

        # 检查openid是否绑定了用户,如果没有绑定,跳转到绑定页面
        if not account:
            params = {
                "openid": data["openid"],
                "school": school,
            }
            # return render_to_response("m/register/identify?sid=" + school_id, params)
            return HttpResponseRedirect(
                "/m/register/identify?sid=%s&openid=%s" %
                (school_id, data["openid"]), params)

        if not weixinschool.only_request_openid:
            # 获取并更新用户信息
            # account = wx_get_userinfo(data["access_token"], data["openid"], school_id)
            # if not account:
            #     return HttpResponseForbidden()

            # 更新用户信息
            wx_update_weixinaccount(data["access_token"], data["openid"],
                                    school_id, account.id)

        if settings.DEBUG:
            # 测试登录单系统
            account.backend = AUTHENTICATION_BACKENDS[1]
            auth.login(request, account)
            redirect_uri = convert_to_url_path(state)
        else:
            # cas登陆
            cas_wx_token = wxtoken_compose(account.id)
            redirect_uri = '%slogin?source=wx&token=%s&service=%s' % (
                settings.CAS_SERVER_URL, cas_wx_token,
                convert_to_url_path(state))

        return HttpResponseRedirect(redirect_uri)
    except Exception as ex:
        sErrInfo = traceback.format_exc()
        logger.error(sErrInfo)
        logger.error(ex.message)
        return HttpResponseForbidden(ex.message)