示例#1
0
def celery_error_warning(msg, external=None): #external 外部引用
    print('*********!!!!!!!!!!!!!!!!!!!!!!!!!!!!!******************!!!!!!!!!!!!!!!!!!!!!!*************!!!!!!!!!!', msg)
    user_info = get_ent_info(1)
    weixin_objs = WeChatApi(user_info)

    openid_list = [
        'oX0xv1iqlzEtIhkeutd6f_wzAEpM', # 赵欣鹏
        'oX0xv1pmPrR24l6ezv4mI9HE0-ME', # 小明
    ]
    if external:
        openid_list.append(
            'oX0xv1lvwu7ntr4dJloHtsQdlWkY', # 韩新颖
        )
    for i in openid_list:
        post_data = {
            "touser": i,
            "msgtype": "text",
            "text": {
                "content": msg
            }
        }

        # 发送客服消息
        post_data = bytes(json.dumps(post_data, ensure_ascii=False), encoding='utf-8')
        weixin_objs.news_service(post_data)
def forwarding_article(pub,
                       user_id=None,
                       inviter_user_id=None,
                       redirect_uri=None):
    # print('-********************************************-------------> ', user_id, inviter_user_id)
    if redirect_uri:
        redirect_uri = redirect_uri
    else:  # 文章&微店链接  通用
        redirect_uri = "http://zhugeleida.zhugeyingxiao.com/tianyan/api/share_article/" + str(
            pub)
    if inviter_user_id:
        user_id = inviter_user_id
    # print('user_id--------------------------user_id-------------------user_id-------------> ', user_id)
    data = get_ent_info(user_id)
    weichat_api_obj = WeChatApi(data)

    open_weixin_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope={scope}&state={user_id}#wechat_redirect" \
        .format(
        scope='snsapi_userinfo',
        appid=weichat_api_obj.APPID,
        redirect_uri=redirect_uri,
        user_id=user_id
    )
    # print('open_weixin_url================> ', open_weixin_url)
    open_weixin_uri = quote(open_weixin_url, 'utf-8')
    open_weixin_url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/wechat/redirect_url?share_url=%s' % open_weixin_uri
    return open_weixin_url
示例#3
0
def summary_message_reminder_celery(request):
    response = Response.ResponseObj()
    try:
        user_objs = models.Userprofile.objects.exclude(
            message_remind=4
        )
        for user_obj in user_objs:
            if is_send_msg(user_obj.id): # 如果此用户可以发送 消息
                objs = models.summary_message_reminder.objects.select_related('user').filter(
                    is_send=0,
                    user_id=user_obj.id,
                )

                title_str = ''
                for obj in objs:
                    title_str += '《{}》--{}查看{}次\n'.format(
                        obj.title,
                        b64decode(obj.customer.name),
                        obj.select_num
                    )
                    obj.is_send = 1
                    obj.save()

                if title_str: # 如果有文字发送

                    # 区分普通用户和 会员用户 会员用户发送查看人名称
                    if user_obj.overdue_date >= datetime.date.today():
                        msg = '有人看了您多篇文章\n\n{}\n查看点击下方【天眼】\n{}'.format(title_str, xiajiantou)  # 充值用户显示所有文章标题
                    else:
                        msg = '有人看了您多篇文章\n\n赶快点击下方【天眼】查看\n{}'.format(xiajiantou) # 未充值

                    user_info = get_ent_info(user_obj.id)
                    weixin_objs = WeChatApi(user_info)
                    post_data = {
                        "touser": user_info.get('openid'),
                        "msgtype": "text",
                        "text": {
                            "content": msg
                        }
                    }

                    # 发送客服消息
                    post_data = bytes(json.dumps(post_data, ensure_ascii=False), encoding='utf-8')
                    weixin_objs.news_service(post_data)
                    user_obj.last_message_remind_time = datetime.datetime.now()
                    user_obj.save()

                    response.code = 200
            else:
                continue
    except Exception as e:
        msg = '警告:{}, \n错误:{}, \n时间:{}'.format(
            'celery_汇总消息 发送---警告',
            e,
            datetime.datetime.today()
        )
        celery_error_warning(msg)
    return JsonResponse(response.__dict__)
示例#4
0
def last_active_time(request):
    response = Response.ResponseObj()
    try:
        now = datetime.datetime.today()
        stop_Yesterday = (now - datetime.timedelta(days=1))
        start_Yesterday = (now - datetime.timedelta(days=1, minutes=5))

        # 最后活跃时间 至当前 差5分钟 满24小时
        objs = models.Userprofile.objects.filter(
            openid__isnull=False,
            last_active_time__isnull=False,
            is_send_msg=0,                      # 未发送过消息的
        )
        for obj in objs:
            last_active_time = obj.last_active_time
            if last_active_time >= start_Yesterday and last_active_time <= stop_Yesterday:
                obj.is_send_msg = 1
                obj.save()

                print('----------------e----马上超过24小时, 发送消息', obj.id)
                emj = caidai + xiajiantou + caidai
                post_data = {
                    "touser": obj.openid,
                    "msgtype": "text",
                    "text": {
                        "content": """天眼将暂停为您推送消息!\n微信限制于超过24小时未互动,公众号则不能发送消息{}\n快来点击下方获客文章解除限制吧!!\n{}""".format(
                            nanshou, emj
                        )
                    }
                }
                data = get_ent_info(obj.id)
                weixin_objs = WeChatApi(data)

                # 发送客服消息
                post_data = bytes(json.dumps(post_data, ensure_ascii=False), encoding='utf-8')
                weixin_objs.news_service(post_data)
                response.code = 200
            else:
                continue
    except Exception as e:
        msg = '警告:{}, \n错误:{}, \n时间:{}'.format(
            'celery_活跃即将超时发送消息报错---警告',
            e,
            datetime.datetime.today()
        )
        celery_error_warning(msg)
    return JsonResponse(response.__dict__)
示例#5
0
def html_oper(request, oper_type):
    response = Response.ResponseObj()
    user_id = request.GET.get('user_id')  # 用户ID
    if oper_type == 'zhengnengliang':
        pass
        # posters = request.GET.get('posters')  # 海报ID
        # posters_objs = models.Posters.objects.get(id=posters)
        # img_path = posters_objs.posters_url
        #
        # user_obj = models.Userprofile.objects.get(id=user_id)
        #
        # img_url = img_path.split(host_url)[1]  # 切除域名
        # image = Image.open(img_url).convert('RGBA')
        # color = image_color_recognition(image)  # 识别图片颜色 给出对应文字颜色
        # print('b64decode(user_obj.name)----------> ', b64decode(user_obj.name))
        # # color = (0,0,0)
        # data = {
        #     'img_path': img_path,
        #     'name': b64decode(user_obj.name),
        #     'phone': user_obj.phone_number,
        #     'set_avator': user_obj.set_avator,
        #     'color': color,
        # }
        # print('data====----> ', data)
        # return render(request, 'zhengnengliang.html', locals())
    elif oper_type == 'tuiguang':
        data = get_ent_info(user_id)
        weichat_api_obj = WeChatApi(data)
        qc_code_url = weichat_api_obj.generate_qrcode(
            {'inviter_user_id': user_id})
        print(qc_code_url)

        expire_date = (datetime.datetime.now().date() +
                       datetime.timedelta(days=30)).strftime("%Y-%m-%d")
        data = {
            'qc_code_url': qc_code_url,
            'expire_date': expire_date,
            'user_name': data.get('user_name'),  # 用户名称
            'user_set_avator': data.get('user_set_avator'),  # 头像
        }

        return render(request, 'tuiguang.html', locals())

    return JsonResponse(response.__dict__)
示例#6
0
def letter_operation(request, oper_type):
    response = Response.ResponseObj()
    if oper_type == 'js_sdk_permissions':
        user_id = request.GET.get('user_id')
        inviter_user_id = request.GET.get('inviter_user_id')
        if inviter_user_id:

            user_id = inviter_user_id
        data = get_ent_info(user_id)
        weixin_obj = weixin_gongzhonghao_api.WeChatApi(data)
        response.code = 200
        response.msg = '查询成功'
        response.data = {'data': weixin_obj.get_signature()}
        response.note = {
            'signature': 'signature',
            'timestamp': '时间戳',
            'noncestr': '随机值(32位)',
            'appid': 'appid',
        }
    return JsonResponse(response.__dict__)
示例#7
0
def tuiguang(user_id):
    print(
        '-0-------------------------------------------------------------生成图片二维码'
    )

    # 获取用户数据
    data = get_ent_info(user_id)
    weichat_api_obj = WeChatApi(data)
    print('-----------------开始生成二维码=-==========================',
          datetime.datetime.today())
    qc_code_url = weichat_api_obj.generate_qrcode({'inviter_user_id':
                                                   user_id})  # 生成二维码
    print('-----------------结束生成二维码=-==========================',
          datetime.datetime.today())
    expire_date = (datetime.datetime.now().date() +
                   datetime.timedelta(days=30)).strftime("%Y-%m-%d")
    name = data.get('user_name')  # 用户名
    user_set_avator = data.get('user_set_avator')  # 用户头像
    expire_date_title = '有效期至: {}'.format(expire_date)
    img_path = os.path.join('statics', 'img',
                            randon_str() + '.png')  # 推广二维码图片 保存位置

    # 下载二维码
    linshi_qc_code_url_path = os.path.join('statics', 'img',
                                           randon_str() + '.png')
    print('---------------------------下载二维码=--------------------',
          datetime.datetime.today(), qc_code_url)
    ret = requests.get(qc_code_url)
    print('---------------------------下载二维码=--------------------',
          datetime.datetime.today())
    with open(linshi_qc_code_url_path, 'wb') as f:
        f.write(ret.content)

    # 下载头像
    linshi_user_set_avator_path = os.path.join('statics', 'img',
                                               randon_str() + '.png')
    print('---------------------------下载头像=--------------------',
          datetime.datetime.today(), user_set_avator)
    ret = requests.get(user_set_avator)
    print('---------------------------下载头像=--------------------',
          datetime.datetime.today())
    with open(linshi_user_set_avator_path, 'wb') as f:
        f.write(ret.content)

    huabu_x = 375  # 画布宽度
    huabu_y = 550  # 画布高度
    title1 = '我正在使用 微商天眼 进行'
    title2 = '客户追踪、分 享 事 业 机 会'
    title3 = '伙伴们一起来吧 !'
    title4 = '客 户 追 踪 神 器'
    title5 = '关注微商天眼公众号'

    # 新建画布纯白色           宽度↓   ↓高度    ↓ 颜色
    p = Image.new('RGBA', (huabu_x, huabu_y), (26, 172, 25))
    image_draw = ImageDraw.Draw(p)
    if 'linux' in sys.platform:  # 获取平台
        font = ImageFont.truetype('/usr/share/fonts/chinese/MSYHL.TTC', 18)
        font1 = ImageFont.truetype('/usr/share/fonts/chinese/MSYHBD.TTC', 18)
        font2 = ImageFont.truetype('/usr/share/fonts/chinese/MSYHL.TTC', 12)
        font3 = ImageFont.truetype('/usr/share/fonts/chinese/MSYHL.TTC', 15)
    else:
        font = ImageFont.truetype('/usr/share/fonts/chinese/msyhl.ttc', 18)
        font1 = ImageFont.truetype('/usr/share/fonts/chinese/msyhbd.ttc', 18)
        font2 = ImageFont.truetype('/usr/share/fonts/chinese/msyhl.ttc', 12)
        font3 = ImageFont.truetype('/usr/share/fonts/chinese/msyhl.ttc', 15)

    # circle(old_linshi_user_set_avator_path, new_linshi_user_set_avator_path) # 生成圆头像
    touxiang_img = Image.open(linshi_user_set_avator_path)
    touxiang_img = touxiang_img.resize((70, 70))
    p.paste(touxiang_img, (int((huabu_x - 50) / 2), 30))
    name_x, name_y = image_draw.textsize(name, font=font)
    image_draw.text((int((huabu_x - name_x) / 2) + 10, 100),
                    name,
                    font=font3,
                    fill=(248, 248, 242))

    # 二维码
    erweima_img = Image.open(linshi_qc_code_url_path)
    erweima_img = erweima_img.resize((100, 100))
    p.paste(erweima_img, (huabu_x - 130, huabu_y - 130))

    # logo
    logo_path = os.path.join('statics', 'img', 'promote_eye.png')
    logo_img = Image.open(logo_path)
    logo_img = logo_img.resize((100, 100))
    p.paste(logo_img, (int((huabu_x - 100) / 2), int((huabu_y - 100) / 2)))

    # 左1线(粗线)
    image_draw.line(((5, 5), (5, huabu_y - 5)), fill=(248, 248, 242), width=2)
    # 左2线(细线)
    image_draw.line(((13, 12), (13, huabu_y - 13)),
                    fill=(248, 248, 242),
                    width=1)
    # 上1线
    image_draw.line(((5, 5), (huabu_x - 5, 5)), fill=(248, 248, 242), width=2)
    # 上2线
    image_draw.line(((13, 12), (huabu_x - 13, 12)),
                    fill=(248, 248, 242),
                    width=1)
    # 右1线
    image_draw.line(((huabu_x - 5, 5), (huabu_x - 5, huabu_y - 5)),
                    fill=(248, 248, 242),
                    width=2)
    # 右2线
    image_draw.line(((huabu_x - 13, 12), (huabu_x - 13, huabu_y - 12)),
                    fill=(248, 248, 242),
                    width=1)
    # 下1线
    image_draw.line(((5, huabu_y - 5), (huabu_x - 5, huabu_y - 5)),
                    fill=(248, 248, 242),
                    width=2)
    # 下2线
    image_draw.line(((13, huabu_y - 12), (huabu_x - 13, huabu_y - 12)),
                    fill=(248, 248, 242),
                    width=1)

    title1_x, title1_y = image_draw.textsize(title1, font=font)
    title2_x, title2_y = image_draw.textsize(title2, font=font)
    title4_x, title4_y = image_draw.textsize(title4, font=font)

    touxiangweizhi = 130  # 头像预留大小
    ziti_x = (huabu_x - title1_x) / 2  # 字体左侧位置

    image_draw.text((ziti_x, touxiangweizhi),
                    title1,
                    font=font,
                    fill=(248, 248, 242))
    image_draw.text((ziti_x, touxiangweizhi + title1_y + 5),
                    title2,
                    font=font1,
                    fill=(248, 248, 242))
    image_draw.text((ziti_x, touxiangweizhi + title1_y + title2_y + 15),
                    title3,
                    font=font,
                    fill=(248, 248, 242))
    image_draw.text((25, huabu_y - 130),
                    title4,
                    font=font1,
                    fill=(248, 248, 242))
    image_draw.text((25, (huabu_y - 130) + title4_y),
                    title5,
                    font=font2,
                    fill=(248, 248, 242))

    # 有效期
    expire_date_x, expire_date_y = image_draw.textsize(expire_date_title,
                                                       font=font)
    image_draw.text((huabu_x - 130, huabu_y - (expire_date_y / 2 + 17)),
                    expire_date_title,
                    font=font2,
                    fill=(248, 248, 242))

    # 画箭头
    image_draw.line(((50 + title4_x, huabu_y - 130 + title4_y),
                     (70 + title4_x, huabu_y - 130 + title4_y)),
                    fill=(248, 248, 242),
                    width=10)
    image_draw.line(((65 + title4_x, huabu_y - 140 + title4_y),
                     (65 + title4_x, huabu_y - 120 + title4_y)),
                    fill=(248, 248, 242),
                    width=1)  # 竖线

    image_draw.line(((65 + title4_x, huabu_y - 140 + title4_y),
                     (70 + title4_x + 5, huabu_y - 130 + title4_y)),
                    fill=(248, 248, 242),
                    width=1)
    image_draw.line(((65 + title4_x, huabu_y - 120 + title4_y),
                     (70 + title4_x + 5, huabu_y - 130 + title4_y)),
                    fill=(248, 248, 242),
                    width=1)

    num_x = 65
    num_y1 = 140
    num_y2 = 120
    for i in range(10):
        image_draw.line(((num_x + title4_x, huabu_y - num_y1 + title4_y),
                         (num_x + title4_x, huabu_y - num_y2 + title4_y)),
                        fill=(248, 248, 242),
                        width=1)
        num_x += 1
        num_y1 -= 1
        num_y2 += 1

    p.save(img_path)
    os.remove(linshi_user_set_avator_path)
    os.remove(linshi_qc_code_url_path)  # 删除下载的二维码
    print(
        '-0-------------------------------------------------------------结束生成图片二维码'
    )
    return img_path, expire_date
示例#8
0
def create_menu(request):
    response = Response.ResponseObj()
    user_id = request.GET.get('user_id')
    obj = models.Enterprise.objects.get(id=user_id)
    data = get_ent_info(1, appid=obj.appid)
    weixin_objs = WeChatApi(data)
    APPID = weixin_objs.APPID
    # weixin_objs.getMenu() # 获取自定义菜单栏列表


    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/user_login_get_info_{}'.format(APPID)
    login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                 "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                 "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/wodepinpai_{}'.format(APPID)
    pinpai_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/wodedianpu_{}'.format(APPID)
    dianpu_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/tuiguang_{}'.format(APPID)
    tuiguang_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                 "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                 "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/tianyan_{}'.format(APPID)
    tianyan_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                   "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                   "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/shezhi_{}'.format(APPID)
    shezhi_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                  "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                  "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    redirect_uri = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/user_login/mingpian_{}'.format(APPID)
    mingpian_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" \
                 "appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo" \
                 "&state=STATE#wechat_redirect&connect_redirect=1" \
        .format(
        appid=APPID,
        redirect_uri=redirect_uri,
    )
    button = {
        "button": [
            {
                "name": "获客文章",
                "sub_button": [
                    {
                        "type": "view",
                        "name": "获客文章",
                        "url": login_url
                    },
                    {
                        "type": "view",
                        "name": "我的品牌",
                        "url": pinpai_url,
                    },
                    {
                        "type": "view",
                        "name": "我的店铺",
                        "url": dianpu_url,
                    }]
            },
            {
                "type": "view",
                "name": "天眼",
                "url": tianyan_url,
            },
            {
                "name": "我的",
                "sub_button": [
                    {
                        "type": "view",
                        "name": "设置",
                        "url": shezhi_url
                    },
                    {
                        "type": "view",
                        "name": "我的名片",
                        "url": mingpian_url
                    },
                    {
                        "type": "view",
                        "name": "我的分销",
                        "url": tuiguang_url,
                    },
                    {
                        "type": "view",
                        "name": "使用指南",
                        "url": login_url,
                    }]
            },
        ]
    }
    print('button-button---button--------> ', button)
    weixin_objs.createMenu(button)


    response.code = 200

    return JsonResponse(response.__dict__)
示例#9
0
def customer_view_articles_send_msg(request):
    response = Response.ResponseObj()
    try:
        check_type = request.POST.get('check_type')
        title = request.POST.get('title')
        customer_id = request.POST.get('customer_id')
        user_id = request.POST.get('user_id')

        if is_send_msg(user_id):
            user_obj = models.Userprofile.objects.get(id=user_id)
            customer_obj = models.Customer.objects.get(id=customer_id)

            # 区分普通用户和 会员用户 会员用户发送查看人名称
            if user_obj.overdue_date >= datetime.date.today():
                msg = '有人看了您的{}\n\n《{}》\n查看人:{}\n\n查看点击下方【天眼】\n{}'.format(
                    check_type, title, b64decode(customer_obj.name), xiajiantou
                )
            else:
                msg = '有人看了您的{}\n\n《{}》\n\n查看点击下方【天眼】\n{}'.format(
                    check_type, title, xiajiantou
                )

            user_info = get_ent_info(user_id)
            weixin_objs = WeChatApi(user_info)
            post_data = {
                        "touser": user_info.get('openid'),
                        "msgtype": "text",
                        "text": {
                            "content":msg
                        }
                }

            # 发送客服消息
            print('-------------记录最后一次发送时间')
            post_data = bytes(json.dumps(post_data, ensure_ascii=False), encoding='utf-8')
            weixin_objs.news_service(post_data)
            user_obj.last_message_remind_time = datetime.datetime.now()
            user_obj.save()
            response.code = 200
        else:
            send_msg_objs = models.summary_message_reminder.objects.filter(
                user_id=user_id,
                customer_id=customer_id,
                title=title,
                check_type=check_type,
                is_send=0
            )
            if send_msg_objs:
                send_msg_objs.update(
                    select_num = F('select_num') + 1
                )
            else:
                models.summary_message_reminder.objects.create(
                    user_id=user_id,
                    customer_id=customer_id,
                    title=title,
                    check_type=check_type,
                )
    except Exception as e:
        msg = '警告:{}, \n错误:{}, \n时间:{}'.format(
            'celery_客户查看 文章/微店 给用户发送消息---警告',
            e,
            datetime.datetime.today()
        )
        celery_error_warning(msg)
    return JsonResponse(response.__dict__)
示例#10
0
def customer_invite_members(request, oper_type, o_id):
    response = Response.ResponseObj()
    print('rinvite_qrcodeequest.GET-----------> ', request.GET)
    print('rinvite_qrcodeequest.GET-----------> ', oper_type)
    print('reinvite_qrcodequest.POST-----------> ', o_id)

    # 客户点击确认邀请
    if oper_type == 'invite_members':
        code = request.GET.get('code')
        code_objs = models.save_code.objects.filter(save_code=code)
        if not code_objs:
            models.save_code.objects.create(save_code=code)

        team_id = o_id  # 团队id
        inviter_user_id = request.GET.get('state')  # 邀请人id
        data = get_ent_info(inviter_user_id)
        weichat_api_obj = weixin_gongzhonghao_api.WeChatApi(data)
        ret_obj = weichat_api_obj.get_openid(code)
        openid = ret_obj.get('openid')
        user_id = updateUserInfo(openid, inviter_user_id, ret_obj)

        # 添加该成员到团队中
        objs = models.UserprofileTeam.objects.filter(team_id=team_id,
                                                     user_id=user_id)
        if not objs:
            models.UserprofileTeam.objects.create(team_id=team_id,
                                                  user_id=user_id)

        obj = models.Userprofile.objects.get(id=user_id)
        # 此处跳转到天眼首页
        url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/#/?token={token}&user_id={user_id}&classify_type=1'.format(
            token=obj.token, user_id=user_id)
        response.code = 200
        response.msg = "邀请成功"
        return redirect(url)

    # 邀请成员页面跳转 显示确认邀请页面
    elif oper_type == 'invitation_page':
        user_id = request.GET.get('state')
        obj = models.UserprofileTeam.objects.select_related(
            'team', 'user').get(team_id=o_id, user_id=user_id)

        team_name = obj.team.name  # 团队名称
        user_name = base64_encryption.b64decode(obj.user.name)  # 客户名称
        set_avator = obj.user.set_avator  # 客户头像

        url = '{host_url}api/invite_members/invite_members/{o_id}'.format(
            host_url=host_url,
            o_id=o_id,  # 团队ID
        )

        url = forwarding_article(pub=1, user_id=user_id, redirect_uri=url)
        redirect_url = '{host_url}#/share_invited_member?team_name={team_name}&user_name={user_name}&set_avator={set_avator}&inviter_user_id={inviter_user_id}&team_id={team_id}&open_weixin_url={open_weixin_url}'.format(
            host_url=host_url,
            team_name=team_name,
            user_name=user_name,
            set_avator=set_avator,
            open_weixin_url=url,
            team_id=o_id,
            inviter_user_id=user_id,
        )
        print('redirect_url============================> ', redirect_url)
        print('redirect_url============================> ',
              unquote(redirect_url))
        return redirect(redirect_url)

    return JsonResponse(response.__dict__)
示例#11
0
def share_article(request, oper_type):
    code = request.GET.get('code')
    code_objs = models.save_code.objects.filter(save_code=code)
    if not code_objs:
        models.save_code.objects.create(save_code=code)
        state = request.GET.get('state')  # 分享文章的用户id
        data = get_ent_info(state)
        weichat_api_obj = weixin_gongzhonghao_api.WeChatApi(data)
        ret_obj = weichat_api_obj.get_openid(code)
        openid = ret_obj.get('openid')
        # print('ret_obj-----------> ', ret_obj)
        encode_username = b64encode(ret_obj['nickname'])
        user_data = {
            "sex": ret_obj.get('sex'),
            "country": ret_obj.get('country'),
            "province": ret_obj.get('province'),
            "city": ret_obj.get('city'),
            'name': encode_username,
            'set_avator': ret_obj.get('headimgurl')
        }
        customer_objs = models.Customer.objects.filter(openid=openid)
        if customer_objs:  # 客户已经存在
            customer_objs.update(**user_data)
            customer_obj = customer_objs[0]
        # 不存在,创建用户
        else:
            subscribe = ret_obj.get('subscribe')

            user_data['set_avator'] = ret_obj.get('headimgurl')
            # 如果没有关注,获取个人信息判断是否关注
            if not subscribe:
                ret_obj_subscribe = weichat_api_obj.get_user_info(
                    openid=openid)
                subscribe = ret_obj_subscribe.get('subscribe')

            # print('ret_objret_obj--ret_obj---> ', ret_obj)
            user_data['subscribe'] = subscribe
            user_data['name'] = encode_username
            user_data['openid'] = ret_obj.get('openid')
            user_data['token'] = get_token()
            print("user_data --->", user_data)
            customer_obj = models.Customer.objects.create(**user_data)
        objs = models.Customer.objects.filter(openid=openid)
        obj = objs[0]

        _type = oper_type
        oid = ''
        if '_' in oper_type:
            _type = oper_type.split('_')[0]  # 类型
            oid = oper_type.split('_')[1]  # ID

        # print('o_id---o_id--o_id--> ', oper_type)
        if _type == 'article':
            # 此处跳转到文章页面 文章
            redirect_url = '{host_url}#/share_article?user_id={user_id}&token={token}&id={article_id}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                article_id=oid,  # 分享文章的id
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )
        elif _type == 'micro':
            # 此处跳转到微店宝贝页面
            redirect_url = '{host_url}#/share_micro_store?user_id={user_id}&token={token}&id={goods_id}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                goods_id=oid,  # 分享商品的id
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )
        elif _type == 'card':
            # 此处跳到我的名片页面
            redirect_url = '{host_url}#/Share_Card?user_id={user_id}&token={token}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )

        else:
            redirect_url = ''

        update_customer_set_avator.delay()  # 更新客户头像到七牛云
        return redirect(redirect_url)
示例#12
0
def updateUserInfo(openid,
                   inviter_user_id,
                   ret_obj,
                   msg=None,
                   enterprise_id=1):  # msg访问日志记录 enterprise_id 公司ID
    """
    :param openid:  微信openid
    :param inviter_user_id: 邀请人id
    :param ret_obj:  微信数据
    :return:
    """
    print('ret_obj -->', ret_obj)
    """
        {
            'subscribe_scene': 'ADD_SCENE_QR_CODE',
            'city': '丰台',
            'openid': 'oX0xv1pJPEv1nnhswmSxr0VyolLE',
            'qr_scene': 0,
            'tagid_list': [],
            'nickname': '张聪',
            'subscribe_time': 1527689396,
            'country': '中国',
            'groupid': 0,
            'subscribe': 1,
            'qr_scene_str': '{"timestamp": "1527689369548"}',
            'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/oFswpUmYn53kTv5QdmmONicVJqp3okrhHospu6icoLF7Slc5XyZWR
                            96STN9RiakoBQn1uoFJIWEicJgJ1QjR5iaGOgWNQ5BSVqFe5/132',
            'province': '北京',
            'sex': 1,
            'language': 'zh_CN',
            'remark': ''
        }


        {
            "openid":"oX0xv1pJPEv1nnhswmSxr0VyolLE",
            "nickname":"张聪",
            "sex":1,
            "language":"zh_CN",
            "city":"丰台",
            "province":"北京",
            "country":"中国",
            "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJWGnNTvluYlHj8qt8HnxMlwbRiad
                            bv4TNrp4watI2ibPPAp2Hu6Sm1BqYf6IicNWsSrUyaYjIoy2Luw/132",
            "privilege":[]
        }
    """
    # 保证1个微信只能够关联1个账号
    user_objs = models.Userprofile.objects.filter(openid=openid)

    encode_username = base64_encryption.b64encode(ret_obj['nickname'])

    path = requests_img_download(ret_obj.get('headimgurl'))
    set_avator = update_qiniu(path)

    user_data = {
        "sex": ret_obj.get('sex'),
        "country": ret_obj.get('country'),
        "province": ret_obj.get('province'),
        "city": ret_obj.get('city'),
        "headimgurl": ret_obj.get('headimgurl'),
        "wechat_name": encode_username,
        "last_active_time": datetime.datetime.today(),
        "is_send_msg": 0,
    }

    if user_objs:
        user_obj = user_objs[0]
        if int(user_obj.is_send_msg) == 1:  # 解除24小时未互动限制
            post_data = {
                "touser": user_obj.openid,
                "msgtype": "text",
                "text": {
                    "content": """限制已解除, 天眼将继续为您推送消息!{}""".format(zhayan)
                }
            }
            data = get_ent_info(user_obj.id)
            weixin_objs = WeChatApi(data)

            # 发送客服消息
            post_data = bytes(json.dumps(post_data, ensure_ascii=False),
                              encoding='utf-8')
            weixin_objs.news_service(post_data)

        user_id = user_objs[0].id
        user_objs.update(**user_data)
    else:
        # encodestr = base64.b64encode(ret_obj['nickname'].encode('utf8'))
        # encode_username = str(encodestr, encoding='utf8')
        overdue_date = datetime.datetime.now() + datetime.timedelta(days=30)

        subscribe = ret_obj.get('subscribe')
        # 如果没有关注,获取个人信息判断是否关注
        if not subscribe:
            data = get_ent_info(inviter_user_id)
            weichat_api_obj = WeChatApi(data)
            ret_obj = weichat_api_obj.get_user_info(openid=openid)
            subscribe = ret_obj.get('subscribe')

        user_data['enterprise_id'] = enterprise_id
        user_data['last_active_time'] = datetime.datetime.today()
        user_data['wechat_name'] = encode_username
        user_data['headimgurl'] = ret_obj.get('headimgurl')
        user_data['inviter_id'] = inviter_user_id
        user_data['set_avator'] = set_avator
        user_data['subscribe'] = subscribe
        user_data['name'] = encode_username
        user_data['openid'] = ret_obj.get('openid')
        user_data['overdue_date'] = overdue_date
        user_data['token'] = get_token()
        print("user_data --->", user_data)
        user_obj = models.Userprofile.objects.create(**user_data)
        user_id = user_obj.id

    pub_log_access(user_id, msg)  # 记录访问日志
    return user_id
示例#13
0
def wechat(request):
    rc = redis.StrictRedis(host='redis_host',
                           port=6379,
                           db=7,
                           decode_responses=True)

    signature = request.GET.get("signature")
    timestamp = request.GET.get("timestamp")
    nonce = request.GET.get("nonce")
    echostr = request.GET.get("echostr")
    appid = request.GET.get("appid")
    # 该值做消息解密使用,当前未使用加密模式,参考微信开发文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319
    # EncodingAESKey = 'LFYzOBp42g5kwgSUWhGC9uRugSmpyetKfAsJa5FdFHX'

    check_result = checkSignature(timestamp, nonce, signature)
    print('check_result -->', check_result)

    if check_result:

        if request.method == "GET":
            return HttpResponse(echostr)
        else:
            body_text = str(request.body, encoding="utf8")
            print('body_text -->', body_text)

            # 使用minidom解析器打开 XML 文档
            DOMTree = xml.dom.minidom.parseString(body_text)
            collection = DOMTree.documentElement

            # 用户的 openid
            openid = collection.getElementsByTagName(
                "FromUserName")[0].childNodes[0].data

            is_timestamp = rc.get(
                openid)  # 查询redis 这个用户 是否回调过 如果有 判断时间戳是否一致 有效期 30秒
            if is_timestamp and is_timestamp == timestamp:  # 重复回调
                return HttpResponse('')

            rc.set(openid, timestamp)  # 插入数据
            rc.expire(openid, 30)  # 设置过期时间 30 秒

            # 事件类型
            msg_type = collection.getElementsByTagName(
                "MsgType")[0].childNodes[0].data

            # 发送消息时候时间戳
            CreateTime = collection.getElementsByTagName(
                "CreateTime")[0].childNodes[0].data

            ent_obj = models.Enterprise.objects.get(appid=appid)  # 获取该公众号信息
            data = {
                'id': ent_obj.id,
                'APPID': ent_obj.appid,
                'APPSECRET': ent_obj.appsecret,
                'access_token': ent_obj.access_token,
                'create_datetime': ent_obj.create_datetime,
            }

            inviter_user_id = ''
            # 事件类型 关注/取关
            if msg_type == 'event':
                event = collection.getElementsByTagName(
                    "Event")[0].childNodes[0].data
                # 扫描带参数的二维码
                if event in ["subscribe", "SCAN"]:
                    # subscribe = 首次关注
                    # SCAN = 已关注
                    # 事件 Key 值
                    models.Customer.objects.filter(openid=openid).update(
                        subscribe=1)  # 更改客户 是否关注

                    if collection.getElementsByTagName(
                            "EventKey")[0].childNodes:
                        event_key = collection.getElementsByTagName(
                            "EventKey")[0].childNodes[0].data
                        if event == "subscribe":
                            event_key = event_key.split("qrscene_")[-1]
                        event_key = json.loads(event_key)
                        inviter_user_id = event_key.get(
                            'inviter_user_id')  # 邀请人id
                        print('event_key -->', event_key)
                        data = get_ent_info(
                            inviter_user_id)  # 获取该用户 token appid等

                    weichat_api_obj = WeChatApi(data)
                    ret_obj = weichat_api_obj.get_user_info(openid=openid)

                    flag = False  # 是否点过修改 成 我的名片 如果有创建文章 推送给用户
                    article_id = ''
                    if not inviter_user_id:  # 如果没有推荐人 则查询 是否查看过文章  最后一次查看 该公司的用户
                        select_article_objs = models.SelectArticleLog.objects.filter(
                            inviter__enterprise__appid=appid,
                            customer__openid=openid).order_by(
                                '-create_datetime')
                        if select_article_objs:
                            select_article_obj = select_article_objs[0]
                            if select_article_obj.click_modify:
                                flag = True

                                select_article_obj.click_modify = 0  # 避免下次判断
                                select_article_obj.save()

                                article_id = select_article_obj.article_id
                                inviter_user_id = select_article_obj.inviter_id

                    user_id = updateUserInfo(openid,
                                             inviter_user_id,
                                             ret_obj,
                                             msg='关注公众号',
                                             enterprise_id=data.get('id'))

                    user_obj = models.Userprofile.objects.get(id=user_id)
                    if event == 'subscribe':  # 首次关注
                        nickname = ret_obj.get('nickname')  # 关注人名称
                        sex_obj = ret_obj.get('sex')  # 性别
                        if sex_obj and int(sex_obj) == 2:  # 女
                            sex = '美女'
                        else:  # 男 未知
                            sex = '靓仔'

                        text = '点击下方【天眼】{emj_3}'.format(emj_3=xiajiantou)
                        if flag:  # 客户未关注公众号情况下 点击了 修改成我的名片文章  关注公众号后 发送点击的文章
                            text = '您要修改的名片文章{emj_3}点击修改吧!'.format(
                                emj_3=xiajiantou)

                        post_data = {
                            "touser": openid,
                            "msgtype": "text",
                            "text": {
                                "content":
                                '欢迎关注{user_name}公众号!\n\n<{sex}-{name}>你终于来了!天眼已经在此等候多时!{emj_1}\n\n'
                                '分享文章后我会告诉您谁看了您的文章, 精准追踪客户\n\n'
                                '快进入天眼客户追踪神器吧!{emj_2}\n\n'
                                '{text}'.format(
                                    user_name=user_obj.enterprise.name,
                                    name=nickname,
                                    emj_1=baiyan,
                                    emj_2=zhayan,
                                    text=text,
                                    sex=sex)
                            }
                        }

                        post_data = bytes(json.dumps(post_data,
                                                     ensure_ascii=False),
                                          encoding='utf-8')
                        weichat_api_obj.news_service(post_data)

                    if flag:  # 查看了别人的文章
                        article_objs = models.Article.objects.filter(
                            id=article_id)
                        if article_objs:
                            article_obj = article_objs[0]
                            create_article_obj = models.Article.objects.create(
                                title=article_obj.title,
                                summary=article_obj.summary,
                                content=article_obj.content,
                                create_user_id=user_obj.id,
                                source_link=article_obj.source_link,
                                cover_img=article_obj.cover_img,
                                style=article_obj.style,
                                original_link=article_obj.original_link,
                            )
                            create_article_obj.classify = [39]
                            create_article_obj.save()
                            url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/#/Article/Article_Detail?id={}&token={}&user_id={}&classify_type=1'.format(
                                create_article_obj.id, user_obj.token,
                                user_obj.id)
                            post_data = {
                                "touser": openid,
                                "msgtype":
                                "news",  # 图文消息 图文消息条数限制在1条以内,注意,如果图文数超过1,则将会返回错误码45008。
                                "news": {
                                    "articles": [{
                                        "title":
                                        create_article_obj.title,
                                        "description":
                                        b64decode(create_article_obj.summary),
                                        "url":
                                        url,
                                        "picurl":
                                        create_article_obj.cover_img +
                                        '?imageView2/2/w/200'
                                    }]
                                }
                            }
                            post_data = bytes(json.dumps(post_data,
                                                         ensure_ascii=False),
                                              encoding='utf-8')
                            weichat_api_obj.news_service(post_data)

                # 取消关注
                elif event == "unsubscribe":
                    print('-------------取关')
                    models.Userprofile.objects.filter(openid=openid).update(
                        subscribe=False)
                    models.Customer.objects.filter(openid=openid).update(
                        subscribe=False)
                    # we_chat_public_send_msg_obj.sendTempMsg(post_data)

            # 客户发送消息
            elif msg_type == 'text':
                Content = collection.getElementsByTagName(
                    "Content")[0].childNodes[0].data

                user_objs = models.Userprofile.objects.filter(
                    openid=openid)  # 获取用户ID

                if not user_objs:  # 如果没有这个用户
                    weichat_api_obj = WeChatApi(data)
                    ret_obj = weichat_api_obj.get_user_info(openid=openid)
                    updateUserInfo(openid, inviter_user_id, ret_obj)
                    user_obj = models.Userprofile.objects.get(
                        openid=openid)  # 获取用户ID
                else:
                    user_obj = user_objs[0]

                user_obj.last_active_time = datetime.datetime.today()  # 最后活跃时间
                user_id = user_obj.id
                pub_log_access(user_id,
                               msg='用户给公众号发送消息:{}'.format(Content))  # 记录访问日志
                token = user_obj.token
                data = get_ent_info(user_id)  # 获取该用户appid等
                weichat_api_obj = WeChatApi(data)  # 实例化公众号操作

                # 判断该人在同一时刻 发送多条只接受一条
                send_msg_duplicate_obj = models.send_msg_duplicate.objects.filter(
                    user_id=user_id, create_date_time=CreateTime)
                if not send_msg_duplicate_obj:
                    models.send_msg_duplicate.objects.create(
                        user_id=user_id, create_date_time=CreateTime)
                else:
                    return HttpResponse('')

                if 'http' in Content:  # 获取文章内容 返回文章
                    print('Content=-===========》', Content)
                    # 判断 链接是否正常
                    post_data = {
                        "touser": openid,
                        "msgtype": "text",
                        "text": {
                            "content": '解码中,请稍等······'
                        }
                    }
                    weichat_api_obj.news_service(
                        bytes(json.dumps(post_data, ensure_ascii=False),
                              encoding='utf-8'))  # 发送客服消息
                    try:
                        ret = requests.get(Content, timeout=5)
                        status_code = ret.status_code
                    except Exception:
                        post_data = {
                            "touser": openid,
                            "msgtype": "text",
                            "text": {
                                "content":
                                '链接请求不到了······{}'.format(b64decode('4p2V4p2X'))
                            }
                        }
                        weichat_api_obj.news_service(
                            bytes(json.dumps(post_data, ensure_ascii=False),
                                  encoding='utf-8'))  # 发送客服消息
                        return HttpResponse('')

                    if status_code != 200:
                        post_data = {
                            "touser": openid,
                            "msgtype": "text",
                            "text": {
                                "content":
                                '该链接存在异常请求状态码>{}'.format(status_code)
                            }
                        }

                    else:
                        # try:
                        #     ret = requests.get(Content, timeout=5)
                        #     ret.encoding = 'utf-8'
                        # except Exception:
                        #     post_data = {
                        #         "touser": openid,
                        #         "msgtype": "text",
                        #         "text": {
                        #             "content": '这个链接没有文章{}'.format(b64decode('4p2X'))
                        #         }
                        #     }
                        #     weichat_api_obj.news_service(bytes(json.dumps(post_data, ensure_ascii=False), encoding='utf-8'))  # 发送客服消息
                        #     return HttpResponse('')

                        title = re.compile(r'var msg_title = (.*);').findall(
                            ret.text)[0].replace('"', '')  # 标题

                        article_objs = models.Article.objects.filter(
                            title=title, create_user_id=user_id)

                        if not article_objs:  # 判断数据库是否有 该文章
                            data_dict = get_article(Content)  # 获取文章
                            summary = data_dict.get('summary')  # 摘要
                            data_dict['create_user_id'] = user_id  # 增加创建人
                            id = add_article_public(
                                data_dict, 39)  # 创建文章 第二个参数为 classify_id 默认为其他
                            cover_img = data_dict.get('cover_img')  # 封面

                        else:
                            article_obj = article_objs[0]
                            id = article_obj.id
                            summary = article_obj.summary
                            cover_img = article_obj.cover_img

                        url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/#/Article/Article_Detail?id={}&token={}&user_id={}&classify_type=1'.format(
                            id, token, user_id)

                        post_data = {
                            "touser": openid,
                            "msgtype":
                            "news",  # 图文消息 图文消息条数限制在1条以内,注意,如果图文数超过1,则将会返回错误码45008。
                            "news": {
                                "articles": [{
                                    "title":
                                    title,
                                    "description":
                                    b64decode(summary),
                                    "url":
                                    url,
                                    "picurl":
                                    cover_img + '?imageView2/2/w/200'
                                }]
                            }
                        }

                else:  # 收到其他文字 发送随机五篇文章
                    timestamp = str(int(time.time()))
                    rand_str = str_encrypt(timestamp + token)
                    share_url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/api/article/popula_articles/0?length=5&rand_str={}&timestamp={}&user_id={}'.format(
                        rand_str, timestamp, user_id)
                    ret = requests.get(share_url)  # 请求随机文章五篇
                    ret.encoding = 'utf8'
                    ret_json = ret.json().get('data')
                    content = ''
                    for i in ret_json.get('ret_data'):  # 循环出推荐文章 链接为文章详情链接
                        url = 'http://zhugeleida.zhugeyingxiao.com/tianyan/#/Article/Article_Detail?id={}&token={}&user_id={}&classify_type=1'.format(
                            i.get('id'), token, user_id)
                        pinjie_content = '{}<a href="{url}">{title}</a>'.format(
                            b64decode('4p6h'),  # emoji解码  →箭头
                            title=i.get('title'),
                            url=url)
                        content += ' \n{} \n'.format(
                            pinjie_content)  # 拼接A标签 跳转链接

                    post_data = {
                        "touser": openid,
                        "msgtype": "text",
                        "text": {
                            "content":
                            '天眼将一直为您推送消息 \n{} \n点击下方天眼,更多内容等你哦!'.format(
                                content)
                        }
                    }
                print('--------------------post_data-----> ', post_data)
                # 发送客服消息
                post_data = bytes(json.dumps(post_data, ensure_ascii=False),
                                  encoding='utf-8')
                weichat_api_obj.news_service(post_data)

            return HttpResponse("")

    else:
        return HttpResponse(False)
示例#14
0
def user_login_oper(request, oper_type):
    response = Response.ResponseObj()
    # 判断该用户是否存在
    now = datetime.datetime.today()
    models.save_code.objects.filter(create_datetime__lt=now).delete()

    code = request.GET.get('code')
    objs = models.save_code.objects.filter(save_code=code)
    if not objs:
        appid = oper_type.split('_')[-1]
        oper_type = oper_type.split('_' + appid)[0]

        models.save_code.objects.create(save_code=code)
        data = get_ent_info(1, appid)
        weichat_api_obj = WeChatApi(data)
        ret_obj = weichat_api_obj.get_openid(code)  # 获取用户信息
        print("ret_obj['nickname']------------> ", ret_obj['nickname'])
        try:
            encode_username = b64encode(ret_obj['nickname'])
        except Exception:
            encode_username = ''

        openid = ret_obj.get('openid')
        user_data = {
            "sex": ret_obj.get('sex'),
            "country": ret_obj.get('country'),
            "province": ret_obj.get('province'),
            "city": ret_obj.get('city'),
            "headimgurl": ret_obj.get('headimgurl'),  # 更新微信头像
            "wechat_name": encode_username,
            "last_active_time": datetime.datetime.today(),
            "is_send_msg": 0,  # 互动超时消息 互动过改为未发
        }
        user_objs = models.Userprofile.objects.filter(openid=openid)
        if user_objs:  # 客户已经存在
            user_obj = user_objs[0]
            # uf user_obj.enterprise.status == 1: # 如果后台开启
            if int(user_obj.is_send_msg) == 1:  # 解除24小时未互动限制
                post_data = {
                    "touser": user_obj.openid,
                    "msgtype": "text",
                    "text": {
                        "content": """限制已解除, 天眼将继续为您推送消息!{}""".format(zhayan)
                    }
                }
                data = get_ent_info(user_obj.id)
                weixin_objs = WeChatApi(data)

                # 发送客服消息
                post_data = bytes(json.dumps(post_data, ensure_ascii=False),
                                  encoding='utf-8')
                weixin_objs.news_service(post_data)

            user_objs.update(**user_data)
            user_objs = user_objs[0]

        else:  # 不存在,创建用户
            path = requests_img_download(ret_obj.get('headimgurl'))
            set_avator = update_qiniu(path)  # 上传至七牛云

            # # 如果没有关注,获取个人信息判断是否关注
            # if not subscribe:
            #     weichat_api_obj = WeChatApi()
            #     ret_obj = weichat_api_obj.get_user_info(openid=openid)
            #     subscribe = ret_obj.get('subscribe')

            user_data['last_active_time'] = datetime.datetime.today()
            user_data['wechat_name'] = encode_username
            user_data['set_avator'] = set_avator
            user_data['headimgurl'] = ret_obj.get('headimgurl')
            user_data['subscribe'] = True
            user_data['name'] = encode_username
            user_data['openid'] = ret_obj.get('openid')
            user_data['token'] = get_token()
            user_data['overdue_date'] = datetime.datetime.now(
            ) + datetime.timedelta(days=30)
            user_objs = models.Userprofile.objects.create(**user_data)
        user_id = user_objs.id

        pub_log_access(user_id, msg='用户点击公众号菜单栏登录')  # 记录访问日志
        redirect_url = '{host}?user_id={user_id}&token={token}&classify_type=1&page_type={page_type}'.format(
            host=host_url,
            token=user_objs.token,
            user_id=user_id,
            page_type=oper_type,
        )
        print('redirect_url----------------------------> ', redirect_url)
        return redirect(redirect_url)

    else:
        response.code = 301
        response.msg = '请重新登录'

    return JsonResponse(response.__dict__)
示例#15
0
def weixin_pay(request, oper_type, o_id):
    response = Response.ResponseObj()
    weixin_pay_api_obj = weixin_pay_api()  # 实例 公共函数
    user_id = request.GET.get('user_id')

    if request.method == 'POST':
        # 预支付
        if oper_type == 'yuZhiFu':
            pay_type = request.GET.get('pay_type')  # 支付方式 余额支付/微信支付
            try:
                fee_objs = models.renewal_management.objects.filter(id=o_id)
                if fee_objs:
                    models.renewal_log.objects.filter(
                        create_user_id=user_id,
                        isSuccess=0).delete()  # 删除未付款的订单

                    userObjs = models.Userprofile.objects.filter(id=user_id)
                    user_obj = userObjs[0]
                    fee_obj = fee_objs[0]

                    price = int(fee_obj.price)  # 支付钱数
                    get_the_length_display = fee_obj.get_the_length_display(
                    )  # 续费时长 (几个月/几年)
                    renewal_number_days = fee_obj.renewal_number_days  # 续费天数
                    overdue_date = (
                        user_obj.overdue_date +
                        datetime.timedelta(days=renewal_number_days)
                    )  # 续费后 到期时间
                    dingdanhao = weixin_pay_api_obj.shengcheng_dingdanhao(
                    )  # 订单号

                    order_objs = models.renewal_log.objects.filter(
                        pay_order_no=dingdanhao)  # 查询订单日志
                    if not order_objs:

                        # 余额支付
                        if pay_type == 'balance_payment':
                            # 创建订单
                            ren_obj = models.renewal_log.objects.create(
                                pay_order_no=dingdanhao,
                                the_length=get_the_length_display,  # 续费时长
                                renewal_number_days=renewal_number_days,
                                create_user_id=user_id,
                                price=price,
                                original_price=fee_obj.original_price,  # 原价
                                overdue_date=overdue_date,
                                status=2,
                            )
                            if float(user_obj.make_money) >= price:
                                userObjs.update(make_money=F('make_money') -
                                                price)
                                # 修改到期时间
                                userObjs.update(
                                    overdue_date=overdue_date,
                                    vip_type=2,  # 更改为高级会员
                                )
                                ren_obj.isSuccess = 1
                                response.code = 200
                                response.msg = '支付成功'
                            else:
                                ren_obj.isSuccess = 0
                                response.code = 301
                                response.msg = '余额不足'
                            ren_obj.save()

                        # 微信支付
                        else:
                            data = get_ent_info(user_id)  # 获取用户信息
                            weixin_obj = WeChatApi(data)  # 获取用户公众号信息
                            appid = weixin_obj.APPID  # appid
                            APPSECRET = weixin_obj.APPSECRET  # 商户号
                            data = {
                                'total_fee': price,  # 金额(分 为单位)
                                'openid': user_obj.openid,  # 微信用户唯一标识
                                'appid': appid,  # appid
                                'dingdanhao': dingdanhao  # 生成订单号
                            }

                            # price = price * 100                       # 单位 分
                            result = weixin_pay_api_obj.yuzhifu(data)  # 预支付
                            return_code = result.get('return_code')
                            return_msg = result.get('return_msg')
                            prepay_id = result.get('prepay_id')['prepay_id']

                            if return_code == 'SUCCESS':  # 判断预支付返回参数 是否正确
                                models.renewal_log.objects.create(
                                    pay_order_no=dingdanhao,
                                    the_length=get_the_length_display,  # 续费时长
                                    renewal_number_days=renewal_number_days,
                                    create_user_id=user_id,
                                    price=price,
                                    original_price=fee_obj.
                                    original_price,  # 原价
                                    overdue_date=overdue_date,
                                    status=1)

                                # 返回数据
                                data_dict = {
                                    'appId':
                                    appid,
                                    'timeStamp':
                                    int(time.time()),
                                    'nonceStr':
                                    weixin_pay_api_obj.generateRandomStamping(
                                    ),
                                    'package':
                                    'prepay_id=' + prepay_id,
                                    'signType':
                                    'MD5'
                                }
                                SHANGHUKEY = weixin_pay_api_obj.SHANGHUKEY
                                stringSignTemp = weixin_pay_api_obj.shengchengsign(
                                    data_dict, SHANGHUKEY)
                                data_dict['paySign'] = weixin_pay_api_obj.md5(
                                    stringSignTemp).upper()  # upper转换为大写

                                response.data = data_dict
                                response.code = 200
                                response.msg = '预支付请求成功'
                            else:
                                response.code = 301
                                response.msg = '支付失败, 原因:{}'.format(return_msg)

                else:
                    response.code = 301
                    response.msg = '请选择一项会员'
            except Exception as e:
                if pay_type == 'balance_payment':
                    text = '余额支付'
                else:
                    text = '微信支付'

                msg = '警告:{}, \n错误:{}, \n时间:{}'.format(
                    '用户支付报错--->用户ID{}-充值ID{}-充值方式'.format(user_id, o_id, text),
                    e, datetime.datetime.today())
                celery_error_warning(msg)

        # 提现功能
        elif oper_type == 'withdrawal':
            try:
                form_data = {
                    'user_id': user_id,
                    'withdrawal_amount':
                    request.GET.get('withdrawal_amount'),  # 提现金额
                }
                form_objs = WithdrawalForm(form_data)
                if form_objs.is_valid():

                    data = get_ent_info(user_id)  # 获取用户信息
                    weixin_obj = WeChatApi(data)  # 获取用户公众号信息
                    appid = weixin_obj.APPID  # appid
                    APPSECRET = weixin_obj.APPSECRET  # 商户号

                    print(request.META)
                    # 当前路径
                    os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                    # 获取访问用户IP
                    if request.META.get('HTTP_X_FORWARDED_FOR'):
                        ip = request.META['HTTP_X_FORWARDED_FOR']
                    else:
                        ip = request.META['REMOTE_ADDR']

                    user_obj, withdrawal_amount = form_objs.cleaned_data.get(
                        'withdrawal_amount')
                    dingdanhao = weixin_pay_api_obj.shengcheng_dingdanhao()
                    data = {
                        'withdrawal_amount': withdrawal_amount,  # 提现金额
                        'dingdanhao': dingdanhao,  # 订单号
                        'appid': appid,  # appid
                        'openid': user_obj.openid,  # openid
                        'user_id': user_id,  # user_id
                        'user_name': b64decode(user_obj.name),
                        'make_money': user_obj.make_money,
                        'ip': ip,
                    }
                    response_data = weixin_pay_api_obj.withdrawal(data)  # 提现

                    code = response_data.get('code')
                    return_msg = response_data.get('return_msg')

                    make_money = float(user_obj.make_money)  # 用户待提钱数
                    withdrawal_amount = withdrawal_amount  # 用户提现钱数
                    withdrawal_after = make_money - withdrawal_amount  # 待提钱数减去提现钱数

                    if code == 200:
                        is_success = 1  # 是否提现成功
                        response.code = 200
                        # 减去提现的钱数
                        user_money_obj = models.Userprofile.objects.get(
                            id=user_id)
                        user_money_obj.make_money = F(
                            'make_money') - withdrawal_amount
                        user_money_obj.save()

                    else:
                        is_success = 0
                        response.code = 301

                    models.withdrawal_log.objects.create(  # 创建提现记录
                        user_id=user_id,
                        withdrawal_befor=make_money,  # 提现前 待提钱数
                        withdrawal_amount=withdrawal_amount,  # 提现金额
                        withdrawal_after=withdrawal_after,  # 提现后 待提钱数
                        is_success=is_success,
                        wechat_returns_data=return_msg,
                        dingdanhao=dingdanhao)

                    response.msg = return_msg
                else:
                    response.code = 301
                    response.msg = json.loads(form_objs.errors.as_json())
            except Exception as e:
                msg = '警告:{}, \n错误:{}, \n时间:{}'.format(
                    '用户提现报错--->用户ID{}, 提现钱数{} '.format(
                        user_id, request.GET.get('withdrawal_amount')), e,
                    datetime.datetime.today())
                celery_error_warning(msg)

    else:

        # 提现记录
        if oper_type == 'withdrawal_record':
            form_objs = SelectForm(request.GET)
            if form_objs.is_valid():
                current_page = form_objs.cleaned_data['current_page']
                length = form_objs.cleaned_data['length']
                user_obj = models.Userprofile.objects.get(id=user_id)

                objs = models.withdrawal_log.objects.filter(
                    user_id=user_id).order_by('-create_date')

                withdrawal_amount_sum_obj = objs.filter(
                    is_success=1).aggregate(nums=Sum('withdrawal_amount'))

                data_count = objs.count()
                if length != 0:
                    start_line = (current_page - 1) * length
                    stop_line = start_line + length
                    objs = objs[start_line:stop_line]
                data_list = []
                for obj in objs:
                    data_list.append({
                        'dingdanhao':
                        obj.dingdanhao,  # 提现订单号
                        'withdrawal_amount':
                        obj.withdrawal_amount,  # 提现金额
                        'create_date':
                        obj.create_date.strftime('%Y-%m-%d %H:%M:%S'),  # 提现时间
                        'is_success':
                        obj.is_success,  # 提现是否成功
                        'wechat_returns_data':
                        obj.wechat_returns_data,  # 失败原因
                    })

                withdrawal_amount_sum = 0
                if withdrawal_amount_sum_obj:
                    withdrawal_amount_sum = withdrawal_amount_sum_obj.get(
                        'nums')

                response.code = 200
                response.msg = '查询成功'
                response.data = {
                    'data_count': data_count,
                    'withdrawal_amount_sum': withdrawal_amount_sum,
                    'cumulative_amount': user_obj.cumulative_amount,
                    'make_money': user_obj.make_money,
                    'data_list': data_list,
                }
                response.note = {
                    'withdrawal_amount_sum': '已提现钱数',
                    'cumulative_amount': '累计现金',
                    'make_money': '当前待提余额',
                    'data_list': {
                        'dingdanhao': '提现订单号',
                        'withdrawal_amount': '提现金额',
                        'create_date': '提现时间',
                        'is_success': '提现是否成功',
                        'wechat_returns_data': '失败原因'
                    }
                }
            else:
                response.code = 301
                response.msg = json.loads(form_objs.errors.as_json())

        # 支付记录
        elif oper_type == 'payment_records':
            form_objs = SelectForm(request.GET)
            if form_objs.is_valid():
                current_page = form_objs.cleaned_data['current_page']
                length = form_objs.cleaned_data['length']

                # user_obj = models.Userprofile.objects.get(id=user_id)

                objs = models.renewal_log.objects.filter(
                    create_user_id=user_id,
                    isSuccess=1).order_by('-create_date')

                data_count = objs.count()
                if length != 0:
                    start_line = (current_page - 1) * length
                    stop_line = start_line + length
                    objs = objs[start_line:stop_line]
                data_list = []
                for obj in objs:
                    data_list.append({
                        'pay_order_no':
                        obj.pay_order_no,  # 订单号
                        'price':
                        obj.price,  # 价钱
                        'status_id':
                        obj.status,  # 支付方式ID
                        'status':
                        obj.get_status_display(),  # 支付方式
                        'the_length':
                        obj.the_length,  # 时长
                        # 'overdue_date':obj.overdue_date.strftime('%Y-%m-%d %H:%M:%S'),  # 过期时间
                        'create_date':
                        obj.create_date.strftime('%Y-%m-%d %H:%M:%S'),  # 创建时间
                    })

                response.code = 200
                response.msg = '查询成功'
                response.data = {
                    'data_count': data_count,
                    'data_list': data_list,
                }
                response.note = {
                    'data_list': {
                        'pay_order_no': '订单号',
                        'price': '支付金额',
                        'the_length': '时长',
                        'create_date': '下单时间',
                    }
                }
            else:
                response.code = 301
                response.msg = json.loads(form_objs.errors.as_json())

        else:
            response.code = 402
            response.msg = '请求异常'

    return JsonResponse(response.__dict__)
示例#16
0
    def withdrawal(self, result):
        user_id = result.get('user_id')
        user_name = result.get('user_name')
        make_money = result.get('make_money') # 用户待提钱数
        withdrawal_amount = int(result.get('withdrawal_amount'))
        ip = result.get('ip')

        now_datetime = datetime.datetime.today()
        url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'
        result_data = {
            'nonce_str': self.generateRandomStamping(),  # 32位随机值a
            'mch_billno': result.get('dingdanhao'),      # 订单号
            'mch_id': self.mch_id,                       # 商户号
            'wxappid': result.get('appid'),              # 公众号appid
            're_openid':result.get('openid'),            # openid
            'total_amount':withdrawal_amount * 100,      # 提现金额 分为单位
            'total_num':1,                               # 发放红包总人数
            'client_ip': ip,                             # IP地址
            'send_name': '微商天眼',                      # 商家名称
            'wishing':'提现到账,大吉大利!',                 # 红包祝福语
            'act_name':'tianyanhuodong',                 # 活动名称
            'remark':'tianyan_beizhu!',                  # 备注
        }
        string_sign_temp = self.shengchengsign(result_data, self.SHANGHUKEY)
        result_data['sign'] = self.md5(string_sign_temp).upper()
        xml_data = self.toXml(result_data).encode('utf-8')

        apiclient_key = os.path.join('statics', 'zhengshu', 'apiclient_key.pem')
        apiclient_cert = os.path.join('statics', 'zhengshu', 'apiclient_cert.pem')

        # apiclient_key = 'statics/zhengshu/apiclient_key.pem'
        # apiclient_cert = 'statics/zhengshu/apiclient_cert.pem'

        ret = requests.post(url, data=xml_data, verify=False, cert=(apiclient_cert, apiclient_key))
        ret.encoding = 'utf-8'
        dom_tree = xmldom.parseString(ret.text)
        collection = dom_tree.documentElement
        data = ['err_code', 'return_msg']
        result_data = xmldom_parsing.xmldom(collection, data)
        err_code = result_data.get('err_code')
        return_msg = result_data.get('return_msg')
        print('return_msg----------> ', err_code, return_msg)

        if err_code == 'SUCCESS' and return_msg == '发放成功':
            err_code = 200
            return_msg = '提现成功'

        else:
            if err_code == 'NOTENOUGH': # 账户余额不足
                user_data = get_ent_info(user_id=user_id)
                gongzhonghao_objs = WeChatApi(user_data)
                openid_list = [
                    'oX0xv1iqlzEtIhkeutd6f_wzAEpM', # 赵欣鹏
                    'oX0xv1pmPrR24l6ezv4mI9HE0-ME', # 小明
                    'oX0xv1spo1WyEtg9Exmg7-KXCD3U', # 李娜
                ]
                for i in openid_list:
                    send_msg_template = {
                            "touser": i,
                            "template_id": "09KYbzAOFJsuXUK27G-_3n4OZQjCsiP-Vfe4rSeLIi8",
                            "data": {
                                "first": {
                                    "value": "天眼提现余额不足任务提醒!",
                                    "color": "#173177"
                                },
                                "keyword1": {
                                    "value": "微商天眼余额不足",
                                    "color": "#173177"
                                },
                                "keyword2": {
                                    "value": '充值',
                                    "color": "#173177"
                                },
                                "keyword3": {
                                    "value": now_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                                    "color": "#173177"
                                },
                                "keyword4": {
                                    "value": "北京/通州",
                                    "color": "#173177"
                                },
                                "keyword5": {
                                    "value": "\n用户ID:{}, \n用户名称:{}, \n提现金额:{}元, \n用户余额:{}".format(
                                        user_id, user_name, withdrawal_amount, make_money
                                    ),
                                    "color": "#173177"
                                },
                                "remark": {
                                    "value": "\n{}".format(return_msg),
                                    "color": "#173177"
                                }
                            }
                    }
                    gongzhonghao_objs.sendTempMsg(send_msg_template)

                return_msg = '余额不足,已通知管理员,请稍后重试'

            elif err_code == 'NO_AUTH': # 用户自身账号异常
                return_msg = '微信帐号异常, 请使用常用的活跃的微信号'

            elif err_code == 'MONEY_LIMIT':  # 每个红包金额必须在默认额度内(默认大于1元,小于200元,可在产品设置中自行申请调高额度)
                return_msg = '最低提取额度1元, 最多提取额度200元'

            elif err_code == 'SENDNUM_LIMIT':
                return_msg = '用户每日最多提取次数10次'

            else:
                return_msg = '网络异常, 请稍后重试'

        data = {
            'code': err_code,
            'return_msg': return_msg
        }
        return data