Пример #1
0
def ajax_3(request):
    """
    消息获取
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_msg = []
        try:
            msg_list = Tree.objects.filter(owner=owner, read=False)[0]
            msg_list = Tree.objects.filter(
                owner=owner,
                read=False).exclude(tree_name='na').order_by('action_time')
            for msg in msg_list:
                if msg.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=msg.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, msg.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8 + int(msg.action_time.strftime("%H")) > 24:
                    time = msg.action_time.strftime("%m-")+\
                           str(int(msg.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(msg.action_time.strftime("%H"))-16)+msg.action_time.strftime(":%I:%S")
                else:
                    time = msg.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(msg.action_time.strftime("%H")))+msg.action_time.strftime(":%I:%S")
                dict_msg.append({
                    "msg_nick": nickname,
                    "msg_avatar": avatar,
                    "msg_con": msg.content,
                    "msg_time": time
                })

                # 读取过一次就再也不读取了
                msg.read = True
                msg.save()
            json_msg = json.dumps(dict_msg)
            response.write(json_msg)
            return response
        except IndexError:
            ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
Пример #2
0
def ajax_3(request):
    """
    消息获取
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_msg = []
        try:
            msg_list = Tree.objects.filter(owner=owner, read=False)[0]
            msg_list = Tree.objects.filter(owner=owner, read=False).exclude(tree_name='na').order_by('action_time')
            for msg in msg_list:
                if msg.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=msg.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, msg.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8+int(msg.action_time.strftime("%H")) > 24:
                    time = msg.action_time.strftime("%m-")+\
                           str(int(msg.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(msg.action_time.strftime("%H"))-16)+msg.action_time.strftime(":%I:%S")
                else:
                    time = msg.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(msg.action_time.strftime("%H")))+msg.action_time.strftime(":%I:%S")
                dict_msg.append({"msg_nick": nickname,
                                 "msg_avatar": avatar,
                                 "msg_con": msg.content,
                                 "msg_time": time})

                # 读取过一次就再也不读取了
                msg.read = True
                msg.save()
            json_msg = json.dumps(dict_msg)
            response.write(json_msg)
            return response
        except IndexError:
            ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
Пример #3
0
def ajax_6(request):
    """
    收到的吐槽刷新
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    ret = '0'
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_tucao = []
        try:
            tucao_list = Tree.objects.filter(owner=owner, type=6)[0]
            tucao_list = Tree.objects.filter(owner=owner,
                                             type=6).order_by('-action_time')
            for tucao in tucao_list:
                if tucao.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=tucao.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, tucao.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8 + int(tucao.action_time.strftime("%H")) > 24:
                    time = tucao.action_time.strftime("%m-")+\
                           str(int(tucao.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(tucao.action_time.strftime("%H"))-16)+tucao.action_time.strftime(":%I:%S")
                else:
                    time = tucao.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(tucao.action_time.strftime("%H")))+tucao.action_time.strftime(":%I:%S")
                dict_tucao.append({
                    "tucao_nick": nickname,
                    "tucao_avatar": avatar,
                    "tucao_con": tucao.content,
                    "tucao_time": time
                })
            json_tucao = json.dumps(dict_tucao)
            response.write(json_tucao)
            return response
        except IndexError:
            ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
Пример #4
0
def ajax_5(request):
    """
    收到的祝福的历史刷新
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    ret = '0'
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_bless = []
        try:
            bless_list = Tree.objects.filter(owner=owner, type=5)[0]
            bless_list = Tree.objects.filter(owner=owner,
                                             type=5).order_by('-action_time')
            for bless in bless_list:
                if bless.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=bless.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, bless.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8 + int(bless.action_time.strftime("%H")) > 24:
                    time = bless.action_time.strftime("%m-")+\
                           str(int(bless.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(bless.action_time.strftime("%H"))-16)+bless.action_time.strftime(":%I:%S")
                else:
                    time = bless.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(bless.action_time.strftime("%H")))+bless.action_time.strftime(":%I:%S")
                dict_bless.append({
                    "bless_nick": nickname,
                    'bless_avatar': avatar,
                    'bless_con': bless.content,
                    'bless_time': time
                })
            json_bless = json.dumps(dict_bless)
            response.write(json_bless)
            return response
        except IndexError:
            ret = '1'  # 数据库没有记录,说明没有祝福
    else:
        ret = '2'  # 不明原因的错误
    response.write(ret)
    return response
Пример #5
0
def ajax_6(request):
    """
    收到的吐槽刷新
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    ret = '0'
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_tucao = []
        try:
            tucao_list = Tree.objects.filter(owner=owner, type=6)[0]
            tucao_list = Tree.objects.filter(owner=owner, type=6).order_by('-action_time')
            for tucao in tucao_list:
                if tucao.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=tucao.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, tucao.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8+int(tucao.action_time.strftime("%H")) > 24:
                    time = tucao.action_time.strftime("%m-")+\
                           str(int(tucao.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(tucao.action_time.strftime("%H"))-16)+tucao.action_time.strftime(":%I:%S")
                else:
                    time = tucao.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(tucao.action_time.strftime("%H")))+tucao.action_time.strftime(":%I:%S")
                dict_tucao.append({"tucao_nick": nickname,
                                   "tucao_avatar": avatar,
                                   "tucao_con": tucao.content,
                                   "tucao_time": time})
            json_tucao = json.dumps(dict_tucao)
            response.write(json_tucao)
            return response
        except IndexError:
            ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
Пример #6
0
def ajax_5(request):
    """
    收到的祝福的历史刷新
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    ret = '0'
    if user_id and load_begin:
        owner = User.objects.get(openid=user_id)
        dict_bless = []
        try:
            bless_list = Tree.objects.filter(owner=owner, type=5)[0]
            bless_list = Tree.objects.filter(owner=owner, type=5).order_by('-action_time')
            for bless in bless_list:
                if bless.source_id == 'na':  # 匿名?
                    nickname = '匿名'
                    avatar = 'none'
                else:
                    source = User.objects.get(openid=bless.source_id)  # 是否关注
                    if source.is_plant == False:
                        nickname = source.nickname
                        avatar = source.avatar_url
                    else:
                        user_info = client.user.get(client, bless.source_id)
                        nickname = user_info['nickname']
                        avatar = user_info['headimgurl']
                if 8+int(bless.action_time.strftime("%H")) > 24:
                    time = bless.action_time.strftime("%m-")+\
                           str(int(bless.action_time.strftime("%d"))+1)+'\n'\
                               +str(int(bless.action_time.strftime("%H"))-16)+bless.action_time.strftime(":%I:%S")
                else:
                    time = bless.action_time.strftime("%m-%d")+'\n'\
                               +str(8+int(bless.action_time.strftime("%H")))+bless.action_time.strftime(":%I:%S")
                dict_bless.append({"bless_nick": nickname,
                                   'bless_avatar': avatar,
                                   'bless_con': bless.content,
                                   'bless_time': time})
            json_bless = json.dumps(dict_bless)
            response.write(json_bless)
            return response
        except IndexError:
            ret = '1'  # 数据库没有记录,说明没有祝福
    else:
        ret = '2'  # 不明原因的错误
    response.write(ret)
    return response
Пример #7
0
def share(url, timstamp):
    """

    :param url:当前网页的URL,就是要提供分享接口的页面的
    :return:签名,用于生成页面签名
    """
    client.fetch_access_token()
    if timstamp-int(jsapi_ticket['expires_in']) > 7000:
        ticket = client.jsapi.get_jsapi_ticket(client)
        jsapi_ticket['expires_in'] = time.time()
        jsapi_ticket['ticket'] = ticket
    else:
        ticket = jsapi_ticket['ticket']
    return {"first": client.jsapi.get_jsapi_signature(NONCESTR, ticket, timestamp=timstamp, url=url), "second": ticket}
Пример #8
0
def ajax_2(request):
    """
    :param request:
    :return:
    """
    response = HttpResponse()
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    if user_id and load_begin:
        user = User.objects.get(openid=user_id)
        try:
            user_list = user.friends.filter(is_plant=True)[0]
            user_list = user.friends.filter(is_plant=True).order_by('-count')
            user_dict = []
            for user in user_list:
                # 获取用户头像
                client.fetch_access_token()
                user_info = client.user.get(client, user.openid)
                # 生成用户页面访问链接
                user_home = WeChatOAuth(
                    appId, appsecret,
                    'http://1.blesstree.sinaapp.com/wechat/visit' +
                    '?openid=' + user.openid).authorize_url
                # 生成传输用的数据
                user_dict.append({
                    "name": user.nickname,
                    "avatar": user_info['headimgurl'],
                    "count": user.count,
                    "user_home": user_home
                })
        except IndexError:
            user_list = []
        response['Content-Type'] = 'application/json'
        # user_dict = [{"name": '启程'}, {'name': "标"}, {'name': "啦啦啦"}]
        json_dict = json.dumps(user_dict)
        response.write(json_dict)
    else:
        ret = '2'
        response.write(ret)
    return response
Пример #9
0
def share(url, timstamp):
    """

    :param url:当前网页的URL,就是要提供分享接口的页面的
    :return:签名,用于生成页面签名
    """
    client.fetch_access_token()
    if timstamp - int(jsapi_ticket['expires_in']) > 7000:
        ticket = client.jsapi.get_jsapi_ticket(client)
        jsapi_ticket['expires_in'] = time.time()
        jsapi_ticket['ticket'] = ticket
    else:
        ticket = jsapi_ticket['ticket']
    return {
        "first":
        client.jsapi.get_jsapi_signature(NONCESTR,
                                         ticket,
                                         timestamp=timstamp,
                                         url=url),
        "second":
        ticket
    }
Пример #10
0
def ajax_2(request):
    """
    :param request:
    :return:
    """
    response = HttpResponse()
    user_id = request.POST.get('openid', '')
    load_begin = request.POST.get('load_begin', '')
    client.fetch_access_token()
    if user_id and load_begin:
        user = User.objects.get(openid=user_id)
        try:
            user_list = user.friends.filter(is_plant=True)[0]
            user_list = user.friends.filter(is_plant=True).order_by('-count')
            user_dict = []
            for user in user_list:
                # 获取用户头像
                client.fetch_access_token()
                user_info = client.user.get(client, user.openid)
                # 生成用户页面访问链接
                user_home = WeChatOAuth(appId, appsecret,
                                    'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+user.openid).authorize_url
                # 生成传输用的数据
                user_dict.append({"name": user.nickname,
                                  "avatar": user_info['headimgurl'],
                                  "count": user.count,
                                  "user_home": user_home})
        except IndexError:
            user_list = []
        response['Content-Type'] = 'application/json'
        # user_dict = [{"name": '启程'}, {'name': "标"}, {'name': "啦啦啦"}]
        json_dict = json.dumps(user_dict)
        response.write(json_dict)
    else:
        ret = '2'
        response.write(ret)
    return response
Пример #11
0
def weixin_main(request):
    """
        微信接入验证(GET)
        微信正常接收信息(POST)
    """
    # 中文编码问题
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')

    if request.method == 'GET':
        signature = request.GET.get("signature", None)
        timestamp = request.GET.get("timestamp", None)
        nonce = request.GET.get("nonce", None)
        echostr = request.GET.get("echostr", None)
        token = WEIXIN_TOKEN
        if check_signature(token, signature, timestamp, nonce):
            return HttpResponse(echostr)
    else:
        msg = parse_message(request.body)  # request.body就是post的xml格式文件
        if msg.type == 'text':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            # 消息自动回复
            if msg.content == '我':
                client.fetch_access_token()  # 这句话必须有,先获取接口api调用权限
                user = client.user.get(client, msg.source)
                reply.content = user['nickname']
            elif msg.content == 'access':
                reply.content = client.fetch_access_token()
            elif msg.content == "李启成爱地球":
                # client = WeChatClient(appId, appsecret)
                client.fetch_access_token()
                # oauth = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/home')
                menu = client.menu.create(client, {
                    "button": [
                        {
                            "type": "view",
                            "name": '祝福树',
                            "url": oauth.authorize_url
                        },
                        {
                            "type": "click",
                            "name": '关于小创',
                            "key": "v1002"
                        }
                    ]
                }
                )
                reply.content = menu
            else:
                reply.content = '感谢反馈'
            xml = reply.render()
            return HttpResponse(xml)
        # 事件处理:关注事件|点击按钮推送|
        if msg.type == 'event' and msg.event == 'subscribe':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            reply.content = "欢迎关注华工创维俱乐部,我们将不定期推送新鲜有趣的福利哦~"

            xml = reply.render()
            return HttpResponse(xml)

        if msg.type == 'event' and msg.event == 'unsubscribe':
            user = User.objects.get(openid=msg.source)
            user.is_plant = False  # 取消关注等于没有种树了
            user.save()

        if msg.type == 'event' and msg.event == 'click':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            reply.content = "什么都没有~"

            xml = reply.render()
            return HttpResponse(xml)
Пример #12
0
def visit(request):
    """
    处理访问别人的主页的逻辑
    :param sourceid: 谁的空间
    :return:
    """

    sourceid = request.GET.get('openid', '')
    code = request.GET.get('code', '')

    high_verify = request.GET.get('state', '')
    if high_verify == 'high_verify':
        oauth_vis = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+sourceid)
    else:
        oauth_vis = WeChatOAuth(appId, appsecret,
                                'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+sourceid,
                                scope='snsapi_userinfo',
                                state='high_verify')

    # 这里是防止用户种树后取消关注了(不种树了)老的链接被别人点进去了
    error = False
    try:
        client.fetch_access_token()
        owner_info = client.user.get(client, sourceid)
        owner = owner_info['nickname']
        avatar = owner_info['headimgurl']
        owner_db = User.objects.get(openid=sourceid)
        water_time = 0  # TODO:时间转化问题
        count = owner_db.count
        count_bar = count/3000
        tree_name = owner_db.tree_name
    except KeyError:
        pass
    try:
        User.objects.get(openid=sourceid, is_plant=False)
        error = True
    except ObjectDoesNotExist:
        pass

    # ios系统返回按钮出现的bug的解决方法
    try:
        access_token = oauth_vis.fetch_access_token(code)
    except KeyError:
        # access_token = oauth_vis.access_token = code_access_token[code]['access_token']
        # oauth_vis.open_id = code_access_token[code]['openid']
        return HttpResponseRedirect(oauth_vis.authorize_url)

    try:
        flip_id = openid = oauth_vis.open_id
    except AttributeError:
        flip_id = openid = code_access_token[code]['openid']

    # 经过高级用户认证后的访问就有了获取头像与昵称的能力
    flip_nickname = False
    if high_verify == 'high_verify':
        flip_user = oauth_vis.get_user_info(openid=flip_id, access_token=access_token)
        fl_nickname = flip_nickname = flip_user['nickname']
        flip_avatar = flip_user['headimgurl']
        flip_nickname = True
    else:
        # TODO:这里是没有关注公众号的时候用户点进去,想祝福/吐槽/浇水/的时候
        try:
            client.fetch_access_token()
            user_from_wechat = client.user.get(client, flip_id)
            fl_nickname = flip_nickname = user_from_wechat['nickname']
            flip_avatar = user_from_wechat['headimgurl']
        except KeyError:
            flip_nickname = False
            # 获取一个高级认证作为点击浇水/祝福/吐槽事件的跳转链接,认证之后回调到原来的位置
            btn_redirect_url = WeChatOAuth(appId, appsecret,
                                           'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+sourceid,
                                           scope='snsapi_userinfo',
                                           state='high_verify').authorize_url

    try:
        user = User.objects.get(openid=openid, is_plant=True)
    except ObjectDoesNotExist:
        user = 0

    if user is not 0:
        # 用户已经中树,因为只有关注用户才能种树,不关注用户只能评论吐槽,但是朋友关系要保存
        try:
            user.friends.get(openid=sourceid)
        except ObjectDoesNotExist:
            user.friends.add(User.objects.get(openid=sourceid))
            user.save()
            msg = Tree(owner=owner_db, tree_name=owner_db.tree_name, type=4, action_time=time.time(),
                           read=False, source_id=user.openid, content='成功添加好友'+user.nickname)
            msg.save()
        my_zone_url = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/home/').authorize_url
        return render_to_response('visit.html', locals())

    # 用户没有种树,点击按钮都会跳到认证链接来获取信息,获取的信息要保存
    my_zone_url = WeChatOAuth(appId, appsecret,
                              'http://1.blesstree.sinaapp.com/wechat/home/'+"?visit_index='123'&return_openid="+sourceid)\
        .authorize_url
    if flip_nickname:  # 通过点击别人分享进去的都需要保存,这里互动了的
        try:
            friendship = User.objects.get(openid=flip_id)
            friendship.nickname = fl_nickname
            friendship.avatar_url = flip_avatar
            friendship.save()
        except ObjectDoesNotExist:
            friendship = User(openid=flip_id, nickname=fl_nickname,
                              avatar_url=flip_avatar, time_stamp=time.time(),
                              tree_name='na', is_plant=False)
            friendship.save()
            source_fr = User.objects.get(openid=sourceid)
            friendship.friends.add(source_fr)  # 保存朋友关系,只是此时保存的关系的友人尚未种树
            friendship.save()
    elif request.GET.get('add'):  # 通过点击别人分享进去的都需要保存,这里用户只是点击进去过没有互动
        try:
            friendship = User.objects.get(openid=flip_id)
        except ObjectDoesNotExist:
            friendship = User(openid=oauth_vis.open_id, nickname='na', time_stamp=time.time(), tree_name='na', is_plant=False)
            friendship.save()
            source_fr = User.objects.get(openid=sourceid)
            friendship.friends.add(source_fr)  # 保存朋友关系,只是此时保存的关系的友人尚未种树
            friendship.save()
    return render_to_response('visit.html', locals())
Пример #13
0
def home(request):
    """
    处理进入自己的主页或者第一次使用引导种树的逻辑
    :param request:
    :return:
    """
    # oauth = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/home')
    code = request.GET.get('code')  # 通过认证的code获取openid
    visit_index = request.GET.get('visit_index')
    return_openid = request.GET.get('return_openid')
    try:
        oauth.fetch_access_token(code)  # 包含获取用户信息的所有条件
    except KeyError:
        # oauth.access_token = code_access_token[code]['access_token']
        # oauth.open_id = code_access_token[code]['openid']
        return HttpResponseRedirect(oauth.authorize_url)  # 如果网页认证code获取失败,只有ios会
    try:
        user_db = User.objects.get(openid=oauth.open_id, is_plant=True)
    except ObjectDoesNotExist:
        user_db = 0

    # 如果数据库没有该open_id的记录的话
    if user_db == 0:
        first_outh = WeChatOAuth(appId, appsecret, "http://1.blesstree.sinaapp.com/wechat/first")
        first_plant_url = first_outh.authorize_url
        if visit_index and return_openid:
            visit = True
            return_url = WeChatOAuth(appId, appsecret,
                                     'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+return_openid)\
                .authorize_url
        return render_to_response('index.html', locals())
    else:
        user = '******'+'?code='+code+'&state='
        # 以下信息是为了分享接口而使用的
        app_id = appId
        timestamp = int(time.time())
        noncestr = NONCESTR
        signature = share(user, timestamp)['first']
        ticket = share(user, timestamp)['second']

        # user_info = oauth.get_user_info(oauth.open_id) 这个是得不到user_info的,需要snsapi_userinfo才可以,尼玛
        client.fetch_access_token()
        user_info = client.user.get(client, oauth.open_id)
        user_openid = oauth.open_id
        name = user_info['nickname']
        count = User.objects.get(openid=user_openid).count
        count_bar = count/3000
        imgUrl = avatar_addr = user_info['headimgurl']
        owner = User.objects.get(openid=user_openid)
        # water_time = time.mktime(Tree.objects.filter(
        #     owner=owner, type=7).order_by('action_time')[0].action_time.timetuple())+28800  # 时区差别
        water_time = int(time.time())
        tree_name = owner.tree_name
        # 分享的链接生成,别人点进去是一个get方法,同时,这个是经过转化的,就是加入认证的链接

        share_url = WeChatOAuth(appId, appsecret,
                                'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+oauth.open_id).authorize_url
        add_friend_url = WeChatOAuth(appId, appsecret,
                                     'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+oauth.open_id+'&add=yes')\
            .authorize_url

        return render_to_response('home.html', locals())
Пример #14
0
def weixin_main(request):
    """
        微信接入验证(GET)
        微信正常接收信息(POST)
    """
    # 中文编码问题
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')

    if request.method == 'GET':
        signature = request.GET.get("signature", None)
        timestamp = request.GET.get("timestamp", None)
        nonce = request.GET.get("nonce", None)
        echostr = request.GET.get("echostr", None)
        token = WEIXIN_TOKEN
        if check_signature(token, signature, timestamp, nonce):
            return HttpResponse(echostr)
    else:
        msg = parse_message(request.body)  # request.body就是post的xml格式文件
        if msg.type == 'text':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            # 消息自动回复
            if msg.content == '我':
                client.fetch_access_token()  # 这句话必须有,先获取接口api调用权限
                user = client.user.get(client, msg.source)
                reply.content = user['nickname']
            elif msg.content == 'access':
                reply.content = client.fetch_access_token()
            elif msg.content == "李启成爱地球":
                # client = WeChatClient(appId, appsecret)
                client.fetch_access_token()
                # oauth = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/home')
                menu = client.menu.create(
                    client, {
                        "button": [{
                            "type": "view",
                            "name": '祝福树',
                            "url": oauth.authorize_url
                        }, {
                            "type": "click",
                            "name": '关于小创',
                            "key": "v1002"
                        }]
                    })
                reply.content = menu
            else:
                reply.content = '感谢反馈'
            xml = reply.render()
            return HttpResponse(xml)
        # 事件处理:关注事件|点击按钮推送|
        if msg.type == 'event' and msg.event == 'subscribe':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            reply.content = "欢迎关注华工创维俱乐部,我们将不定期推送新鲜有趣的福利哦~"

            xml = reply.render()
            return HttpResponse(xml)

        if msg.type == 'event' and msg.event == 'unsubscribe':
            user = User.objects.get(openid=msg.source)
            user.is_plant = False  # 取消关注等于没有种树了
            user.save()

        if msg.type == 'event' and msg.event == 'click':
            reply = TextReply()
            reply.source = msg.target
            reply.target = msg.source
            reply.content = "什么都没有~"

            xml = reply.render()
            return HttpResponse(xml)
Пример #15
0
def visit(request):
    """
    处理访问别人的主页的逻辑
    :param sourceid: 谁的空间
    :return:
    """

    sourceid = request.GET.get('openid', '')
    code = request.GET.get('code', '')

    high_verify = request.GET.get('state', '')
    if high_verify == 'high_verify':
        oauth_vis = WeChatOAuth(
            appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/visit' +
            '?openid=' + sourceid)
    else:
        oauth_vis = WeChatOAuth(appId,
                                appsecret,
                                'http://1.blesstree.sinaapp.com/wechat/visit' +
                                '?openid=' + sourceid,
                                scope='snsapi_userinfo',
                                state='high_verify')

    # 这里是防止用户种树后取消关注了(不种树了)老的链接被别人点进去了
    error = False
    try:
        client.fetch_access_token()
        owner_info = client.user.get(client, sourceid)
        owner = owner_info['nickname']
        avatar = owner_info['headimgurl']
        owner_db = User.objects.get(openid=sourceid)
        water_time = 0  # TODO:时间转化问题
        count = owner_db.count
        count_bar = count / 3000
        tree_name = owner_db.tree_name
    except KeyError:
        pass
    try:
        User.objects.get(openid=sourceid, is_plant=False)
        error = True
    except ObjectDoesNotExist:
        pass

    # ios系统返回按钮出现的bug的解决方法
    try:
        access_token = oauth_vis.fetch_access_token(code)
    except KeyError:
        # access_token = oauth_vis.access_token = code_access_token[code]['access_token']
        # oauth_vis.open_id = code_access_token[code]['openid']
        return HttpResponseRedirect(oauth_vis.authorize_url)

    try:
        flip_id = openid = oauth_vis.open_id
    except AttributeError:
        flip_id = openid = code_access_token[code]['openid']

    # 经过高级用户认证后的访问就有了获取头像与昵称的能力
    flip_nickname = False
    if high_verify == 'high_verify':
        flip_user = oauth_vis.get_user_info(openid=flip_id,
                                            access_token=access_token)
        fl_nickname = flip_nickname = flip_user['nickname']
        flip_avatar = flip_user['headimgurl']
        flip_nickname = True
    else:
        # TODO:这里是没有关注公众号的时候用户点进去,想祝福/吐槽/浇水/的时候
        try:
            client.fetch_access_token()
            user_from_wechat = client.user.get(client, flip_id)
            fl_nickname = flip_nickname = user_from_wechat['nickname']
            flip_avatar = user_from_wechat['headimgurl']
        except KeyError:
            flip_nickname = False
            # 获取一个高级认证作为点击浇水/祝福/吐槽事件的跳转链接,认证之后回调到原来的位置
            btn_redirect_url = WeChatOAuth(
                appId,
                appsecret,
                'http://1.blesstree.sinaapp.com/wechat/visit' + '?openid=' +
                sourceid,
                scope='snsapi_userinfo',
                state='high_verify').authorize_url

    try:
        user = User.objects.get(openid=openid, is_plant=True)
    except ObjectDoesNotExist:
        user = 0

    if user is not 0:
        # 用户已经中树,因为只有关注用户才能种树,不关注用户只能评论吐槽,但是朋友关系要保存
        try:
            user.friends.get(openid=sourceid)
        except ObjectDoesNotExist:
            user.friends.add(User.objects.get(openid=sourceid))
            user.save()
            msg = Tree(owner=owner_db,
                       tree_name=owner_db.tree_name,
                       type=4,
                       action_time=time.time(),
                       read=False,
                       source_id=user.openid,
                       content='成功添加好友' + user.nickname)
            msg.save()
        my_zone_url = WeChatOAuth(
            appId, appsecret,
            'http://1.blesstree.sinaapp.com/wechat/home/').authorize_url
        return render_to_response('visit.html', locals())

    # 用户没有种树,点击按钮都会跳到认证链接来获取信息,获取的信息要保存
    my_zone_url = WeChatOAuth(appId, appsecret,
                              'http://1.blesstree.sinaapp.com/wechat/home/'+"?visit_index='123'&return_openid="+sourceid)\
        .authorize_url
    if flip_nickname:  # 通过点击别人分享进去的都需要保存,这里互动了的
        try:
            friendship = User.objects.get(openid=flip_id)
            friendship.nickname = fl_nickname
            friendship.avatar_url = flip_avatar
            friendship.save()
        except ObjectDoesNotExist:
            friendship = User(openid=flip_id,
                              nickname=fl_nickname,
                              avatar_url=flip_avatar,
                              time_stamp=time.time(),
                              tree_name='na',
                              is_plant=False)
            friendship.save()
            source_fr = User.objects.get(openid=sourceid)
            friendship.friends.add(source_fr)  # 保存朋友关系,只是此时保存的关系的友人尚未种树
            friendship.save()
    elif request.GET.get('add'):  # 通过点击别人分享进去的都需要保存,这里用户只是点击进去过没有互动
        try:
            friendship = User.objects.get(openid=flip_id)
        except ObjectDoesNotExist:
            friendship = User(openid=oauth_vis.open_id,
                              nickname='na',
                              time_stamp=time.time(),
                              tree_name='na',
                              is_plant=False)
            friendship.save()
            source_fr = User.objects.get(openid=sourceid)
            friendship.friends.add(source_fr)  # 保存朋友关系,只是此时保存的关系的友人尚未种树
            friendship.save()
    return render_to_response('visit.html', locals())
Пример #16
0
def home(request):
    """
    处理进入自己的主页或者第一次使用引导种树的逻辑
    :param request:
    :return:
    """
    # oauth = WeChatOAuth(appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/home')
    code = request.GET.get('code')  # 通过认证的code获取openid
    visit_index = request.GET.get('visit_index')
    return_openid = request.GET.get('return_openid')
    try:
        oauth.fetch_access_token(code)  # 包含获取用户信息的所有条件
    except KeyError:
        # oauth.access_token = code_access_token[code]['access_token']
        # oauth.open_id = code_access_token[code]['openid']
        return HttpResponseRedirect(
            oauth.authorize_url)  # 如果网页认证code获取失败,只有ios会
    try:
        user_db = User.objects.get(openid=oauth.open_id, is_plant=True)
    except ObjectDoesNotExist:
        user_db = 0

    # 如果数据库没有该open_id的记录的话
    if user_db == 0:
        first_outh = WeChatOAuth(
            appId, appsecret, "http://1.blesstree.sinaapp.com/wechat/first")
        first_plant_url = first_outh.authorize_url
        if visit_index and return_openid:
            visit = True
            return_url = WeChatOAuth(appId, appsecret,
                                     'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+return_openid)\
                .authorize_url
        return render_to_response('index.html', locals())
    else:
        user = '******' + '?code=' + code + '&state='
        # 以下信息是为了分享接口而使用的
        app_id = appId
        timestamp = int(time.time())
        noncestr = NONCESTR
        signature = share(user, timestamp)['first']
        ticket = share(user, timestamp)['second']

        # user_info = oauth.get_user_info(oauth.open_id) 这个是得不到user_info的,需要snsapi_userinfo才可以,尼玛
        client.fetch_access_token()
        user_info = client.user.get(client, oauth.open_id)
        user_openid = oauth.open_id
        name = user_info['nickname']
        count = User.objects.get(openid=user_openid).count
        count_bar = count / 3000
        imgUrl = avatar_addr = user_info['headimgurl']
        owner = User.objects.get(openid=user_openid)
        # water_time = time.mktime(Tree.objects.filter(
        #     owner=owner, type=7).order_by('action_time')[0].action_time.timetuple())+28800  # 时区差别
        water_time = int(time.time())
        tree_name = owner.tree_name
        # 分享的链接生成,别人点进去是一个get方法,同时,这个是经过转化的,就是加入认证的链接

        share_url = WeChatOAuth(
            appId, appsecret, 'http://1.blesstree.sinaapp.com/wechat/visit' +
            '?openid=' + oauth.open_id).authorize_url
        add_friend_url = WeChatOAuth(appId, appsecret,
                                     'http://1.blesstree.sinaapp.com/wechat/visit'+'?openid='+oauth.open_id+'&add=yes')\
            .authorize_url

        return render_to_response('home.html', locals())