예제 #1
0
    def test_create_qrcode(self):
        data = {
            "action_name": "QR_LIMIT_STR_SCENE",
            "action_info": {
                "scene": {
                    "scene_str": "123"
                }
            }
        }

        # 测试无 appid 和 appsecret 初始化
        wechat = WechatBasic()
        with self.assertRaises(NeedParamError):
            wechat.create_qrcode(data)

        # 测试有 appid 和 appsecret 初始化
        wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret)
        with HTTMock(wechat_api_mock):
            resp = wechat.create_qrcode(data)
            self.assertEqual(
                resp['ticket'],
                'gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw=='
            )
            self.assertEqual(resp['expire_seconds'], 60)
            self.assertEqual(resp['url'],
                             'http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI')
예제 #2
0
    def test_create_qrcode(self):
        data = {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "123"}}}

        # 测试无 appid 和 appsecret 初始化
        wechat = WechatBasic()
        with self.assertRaises(NeedParamError):
            wechat.create_qrcode(data)

        # 测试有 appid 和 appsecret 初始化
        wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret)
        with HTTMock(wechat_api_mock):
            resp = wechat.create_qrcode(data)
            self.assertEqual(resp['ticket'], 'gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==')
            self.assertEqual(resp['expire_seconds'], 60)
            self.assertEqual(resp['url'], 'http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI')
예제 #3
0
    def create_qrcode(cls, name):
        from app import Qrcode
        token, expired_at = _wechat.get_access_token()
        wechat = WechatBasic(
            appid=settings.app_id,
            appsecret=settings.secret,
            access_token=token,
            access_token_expires_at=expired_at)
        payload = {
            "action_name": "QR_LIMIT_STR_SCENE",
            "action_info": {"scene": {"scene_str": name}}}
        resp = wechat.create_qrcode(payload)
        ticket = resp.get('ticket', '')
        url = resp.get('url', '')
        data = cls.show_qrcode(ticket)
        if not data:
            raise
        output = cStringIO.StringIO()
        output.write(data)

        # upload
        p = qiniu.PutPolicy(settings.bucket)
        path = '/qrcode/%s' % name
        path, hash_key = p.upload(output, path)
        output.close()

        Qrcode.create_code(name, ticket, url, path, hash_key)
        p = qiniu.PublicGetPolicy(settings.bucket, path)
        return p.get_url()
예제 #4
0
파일: shop.py 프로젝트: yyt030/quanduoduo
def bind_saler():
    """绑定收银台"""
    bid = int(request.args.get("bid", 0))
    do = request.args.get("do", 0)
    brand = Brand.query.get(bid)
    salers = brand.brand_salers.count()
    users = brand.brandaccounts
    shop_id = 0
    # 获取二维码
    wechat = WechatBasic(
        appid=current_app.config.get("WECHAT_APPID"), appsecret=current_app.config.get("WECHAT_APPSECRET")
    )
    temp_data = {
        "expire_seconds": 604800,
        "action_name": "QR_SCENE",
        "action_info": {"scene": {"scene_id": int(str("11") + str(brand.id))}},
    }
    # data = {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": int(str("11") + str(brand.id))}}}
    get_ticket_data = wechat.create_qrcode(temp_data)
    ticket = get_ticket_data.get("ticket")
    if do == "download_qrcode":
        logging.info("download_qrcode")
        response = wechat.show_qrcode(ticket)
        response = make_response(response.content)
        response.headers["Content-Type"] = "image/jpg"
        attachment_name = "attachment; filename=汝州百事优惠圈绑定收银台专用二维码.jpg"
        response.headers["Content-Disposition"] = attachment_name
        return response

    return render_template("shop/bind_saler.html", brand=brand, ticket=ticket, users=users)
예제 #5
0
    def create_qrcode(cls, name):
        token, expired_at = _wechat.get_access_token()
        wechat = WechatBasic(appid=settings.APP_ID,
                             appsecret=settings.SECRET,
                             access_token=token,
                             access_token_expires_at=expired_at)
        payload = {
            "action_name": "QR_LIMIT_STR_SCENE",
            "action_info": {
                "scene": {
                    "scene_str": name
                }
            }
        }
        resp = wechat.create_qrcode(payload)
        ticket = resp.get('ticket', '')
        url = resp.get('url', '')
        data = cls.show_qrcode(ticket)
        if not data:
            raise
        output = cStringIO.StringIO()
        output.write(data)

        # upload
        p = qiniu.PutPolicy(settings.BUCKET)
        path = '/qrcode/%s' % name
        path, hash_key = p.upload(output, path)
        output.close()

        Qrcode.create_code(name, ticket, url, path, hash_key)
        p = qiniu.PublicGetPolicy(settings.BUCKET, path)
        return p.get_url()
예제 #6
0
def Share(request):
    openid = request.REQUEST.get("openid", "")
    toid = request.REQUEST.get("toid", "")
    Dict = {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "123"}}}
    KLBWechatBasic = WechatBasic(token=WECHAT_TOKEN, appid=WECHAT_APPID, appsecret=WECHAT_APPSECRET)
    MyQrcode = KLBWechatBasic.create_qrcode(Dict)
    QrecodeURL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s"%(MyQrcode['ticket'])
    db={"QrecodeURL":QrecodeURL,"openid":openid,"toid":toid}
    return render_to_response('wechat/share.html', db, context_instance=RequestContext(request))
예제 #7
0
파일: shop.py 프로젝트: yyt030/quanduoduo
def checkout():
    verify = False
    is_expire = False
    usedit = False
    discount_id = request.args.get("discount_id", 0, type=int)
    record_id = request.args.get("record_id", 0, type=int)  # 领取id
    do = request.args.get("do")
    discount = Discount.query.get_or_404(discount_id)
    shops = discount.shops
    record = GetTicketRecord.query.get_or_404(record_id)
    if record.status == "usedit":
        usedit = True
    if discount:
        expire_date = discount.create_at + timedelta(days=discount.usable)
        print discount.create_at, discount.usable
        expire_date = expire_date.date()
        if datetime.datetime.now().date() > expire_date:
            is_expire = True

    # 获取二维码ticket
    if do == "get_qrcode":
        if record.status == "verify":
            verify = True
        if not record.ticket:
            # 获取永久二维码 scene_id前缀12表示是优惠券类型的二维码
            wechat = WechatBasic(
                appid=current_app.config.get("WECHAT_APPID"), appsecret=current_app.config.get("WECHAT_APPSECRET")
            )
            data = {
                "action_name": "QR_LIMIT_SCENE",
                "action_info": {"scene": {"scene_id": int(str("12") + str(record.id))}},
            }
            get_ticket_data = wechat.create_qrcode(data)
            ticket = get_ticket_data.get("ticket")
            session["ticket"] = ticket
            # 写入数据库
            record.ticket = ticket
            db.session.add(record)
            db.session.commit()
        else:
            ticket = record.ticket
        return json.dumps({"message": {"verify": verify, "ticket": ticket, "expire": 0}})
    elif do == "download_qrcode":
        return ""
    return render_template(
        "shop/checkout.html",
        shops=shops,
        expire_date=expire_date,
        is_expire=is_expire,
        record_id=record_id,
        record=record,
        usedit=usedit,
        discount=discount,
    )
예제 #8
0
 def _compute_qrcode(self):
     self.ensure_one()
     tool.token_tool.refresh()
     wechat = WechatBasic(token=__builtin__.token["access_token"], appid=__builtin__.appid,
                          appsecret=__builtin__.appsecret)
     data = dict()
     # data["expire_seconds"] = 604800
     data["action_name"] = "QR_LIMIT_SCENE"
     data["action_info"] = {"scene": {"scene_id": self.id}}
     ret = wechat.create_qrcode(data)
     # ret = wechat.show_qrcode()
     self.weixin_qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % ret["ticket"]
예제 #9
0
 def _compute_qrcode(self):
     self.ensure_one()
     tool.token_tool.refresh()
     wechat = WechatBasic(token=__builtin__.token["access_token"],
                          appid=__builtin__.appid,
                          appsecret=__builtin__.appsecret)
     data = dict()
     # data["expire_seconds"] = 604800
     data["action_name"] = "QR_LIMIT_SCENE"
     data["action_info"] = {"scene": {"scene_id": self.id}}
     ret = wechat.create_qrcode(data)
     # ret = wechat.show_qrcode()
     self.weixin_qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % ret[
         "ticket"]
예제 #10
0
    def create_qr(self):

        wechat_base = WechatBasic(conf=HangoutConfig.get_wechat_config())
        result = wechat_base.create_qrcode({
            "expire_seconds": QR_MAX_EXPIRE_SECONDS,
            "action_name": "QR_SCENE",
            "action_info": {
                "scene": {
                    "scene_id": self.id
                }
            }
        })
        self.url = result.get("url")
        self.ticket = result.get("ticket")
        self.expire_at = self.created_at + timedelta(days=30)
        self.save()
        return self
예제 #11
0
class WeChatService(object):
    def __init__(self, app_id=None, app_secret=None):
        self.redis = redis.StrictRedis(host='localhost', port=6379, db=1)
        self.app_id = app_id
        self.app_secret = app_secret
        if not app_id:
            self.wechat_admin = WeChatAdmin.objects.all().order_by('id')[1]
            self.wechat = WechatBasic(appid=self.wechat_admin.app_id,
                                      appsecret=self.wechat_admin.app_secret,
                                      token=self.wechat_admin.access_token)
            self.app_id = self.wechat_admin.app_id
            self.app_secret = self.wechat_admin.app_secret
        else:
            self.wechat_admin = None
            self.wechat = WechatBasic(appid=app_id,
                                      appsecret=app_secret,
                                      token='123')

        self.get_token()

    def get_token(self):
        key = 'access_token_{0}'.format(self.app_id)
        token = self.redis.get(key)
        if not token:
            res = self.wechat.grant_token()
            token = res.get('access_token')
            self.redis.set(key, token, 3500)
            if self.wechat_admin:
                self.wechat_admin.access_token = token
                self.wechat_admin.save()
        return token

    def send_message(self, open_id, message):
        token = self.get_token()
        req_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}'.format(
            token)
        message = message.decode('utf-8')
        data = {
            'touser': open_id,
            'msgtype': 'text',
            'text': {
                'content': str('测试')
            }
        }
        result = requests.post(req_url, data=simplejson.dumps(data))
        return json.loads(result.content)

    def get_kefu_list(self):
        token = self.get_token()
        req_url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token={0}'.format(
            token)
        result = requests.get(req_url)
        return json.loads(result.content)

    def distribution_kefu(self, open_id, account, extra_mes):
        token = self.get_token()
        req_url = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token={0}'.format(
            token)
        data = {'kf_account': account, 'openid': open_id, 'text': extra_mes}
        result = requests.post(req_url, data=json.dumps(data))
        return result

    def create_qrcode(self, scene):
        data = {
            "action_name": "QR_LIMIT_STR_SCENE",
            "action_info": {
                "scene": {
                    "scene_str": scene
                }
            }
        }
        result = self.wechat.create_qrcode(data)
        ticket = result.get('ticket', '')
        url = result.get('url', '')
        return ticket, url

    def get_user_info_by_code(self, code):
        req_url = '''https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code'''.format(
            self.wechat_admin.app_id, self.wechat_admin.app_secret, code)
        result = requests.get(req_url)
        return json.loads(result.content)

    def get_promotion_info(self, openID, channel=None):
        result = Promotion.objects.filter(open_id=openID)
        if result.exists():
            return result[0]
        user_info = self.wechat.get_user_info(openID)
        nick = user_info.get('nickname', None)
        city = user_info.get('city', None)
        province = user_info.get('province', None)
        sex = '男'
        if str(user_info.get('sex', 0)) == '2':
            sex = '女'
        elif str(user_info.get('sex', 0)) == '0':
            sex = '未知'
        new_promotion = Promotion(open_id=openID,
                                  nick=nick,
                                  sex=sex,
                                  city=city,
                                  province=province,
                                  channel=channel)
        new_promotion.save()
        return new_promotion

    def message_manage(self, message_body):
        self.wechat.parse_data(message_body)
        message = self.wechat.get_message()
        manage_dict = {
            'text': self.text_manage,
            'image': self.image_manage,
            'video': self.other_manage,
            'shortvideo': self.other_manage,
            'link': self.other_manage,
            'location': self.other_manage,
            'subscribe': self.event_manage,
            'unsubscribe': self.event_manage,
            'scan': self.event_manage,
            'view': self.event_manage,
            'event': self.event_manage,
            'voice': self.other_manage,
            'click': self.click_manage
        }
        result, is_news = manage_dict[message.type](message)
        if not is_news:
            response = self.wechat.response_text(result)
        else:
            response = result
        return response

    def image_manage(self, message):
        return '照片已收到', False

    def other_manage(self, message):
        pass

    def click_manage(self, message):
        pass

    def text_manage(self, message):
        if message.content == 'cm':
            menu = {
                'button': [
                    {
                        'name': '🚘去保养',
                        'type': 'view',
                        'url': 'http://sy.chafanbao.com/page/shops/'
                    },
                    {
                        'name':
                        '昆仑微网',
                        'type':
                        'view',
                        'url':
                        'http://kunlunlube.cnpc.com.cn/klrhy/mindex/m_index.shtml?from=weixin'
                    },
                ]
            }
            self.wechat.create_menu(menu)
            return 'cm success', False
        return '收到', False

    def response_article(self, mount, token):
        article = {
            'url':
            'http://sy.chafanbao.com/page/phone/?token={0}'.format(token),
            'title': '恭喜您获得一张 {0} 元电子券'.format(mount),
            'description': '快来领取!',
            'picurl': 'http://static.fibar.cn/{0}y.jpg'.format(mount)
        }
        news = self.wechat.response_news([article])
        return news, True

    def event_manage(self, message):
        if message.type == 'subscribe':
            return self.handle_coupon(message)
        elif message.type == 'scan':
            return self.handle_coupon(message)

    def handle_coupon(self, message):
        key = message.key
        if key.startswith('qrscene_'):
            unique_id = key.split('qrscene_')[1]
        else:
            unique_id = key
        uc = UniqueCode.objects.filter(unique_id=unique_id).all()
        scode_type = {1: '10', 2: '30', 3: '50', 4: '60', 11: '50'}
        if uc.exists():
            uc = uc[0]
            if uc.code_type == 10:
                return "<a href='http://sy.chafanbao.com/page/shops/'>导航</a>", False
                # return "<a href='https://ditu.amap.com/place/B01670M5JQ'>导航</a>", False
            if uc.code_type == 11:
                return self.response_article(scode_type.get(uc.code_type),
                                             uc.unique_id)
                # return "<a href='http://sy.chafanbao.com/page/phone/?token={0}'>点击领券</a>".format(unique_id)
            if not uc.use:
                return self.response_article(scode_type.get(uc.code_type),
                                             uc.unique_id)
                # return "<a href='http://sy.chafanbao.com/page/phone/?token={0}'>点击领券</a>".format(unique_id)
        return '优惠券已被领取', False
예제 #12
0
def detail():
    discount_id = int(request.args.get("id", 0))
    if not discount_id:
        discount_id = int(request.args.get("did", 0))
    do = request.args.get("do")
    discount = Discount.query.get_or_404(discount_id)

    # discount.count 每天0:00清零 TODO 脚本任务
    left_count = discount.number - discount.count
    discount_shop_count = discount.shops.count()
    shop_photos = ShopPhoto.query.filter(ShopPhoto.brand_id == discount.brand_id)
    user_agent = request.headers.get('User-Agent')

    curr_user = g.user
    # user的领券情况
    # 该用户下领用的存在有效期的券(含使用或者未使用)
    curr_ticket_record = GetTicketRecord.query.filter(GetTicketRecord.user_id == curr_user.id,
                                                      GetTicketRecord.discount_id == discount_id,
                                                      GetTicketRecord.create_at >= datetime.datetime.now() - datetime.timedelta(
                                                          days=discount.usable))
    monday = datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().weekday())
    sunday = datetime.datetime.now() + datetime.timedelta(days=7 - datetime.datetime.now().weekday())
    curr_ticket_records_week = curr_ticket_record.filter(GetTicketRecord.create_at >= monday,
                                                         GetTicketRecord.create_at <= sunday).count()
    # print user_agent
    if do == 'post':
        if 'MicroMessenger' not in user_agent:
            return json.dumps({"message": "请在微信里操作", "redirect": "permit", "type": "tips"})
        else:
            expire_datetime = discount.get_expire_datetime
            # expire_datetime_format = expire_datetime.strftime("%Y-%m%-%d")
            expire_datetime_format = str(expire_datetime.date())
            record = GetTicketRecord.query.filter(GetTicketRecord.user_id == g.user.id,
                                                  GetTicketRecord.discount_id == discount_id).first()
            if record:
                if record.status != 'expire':
                    return json.dumps(
                        {"message": {}, "redirect": "", "type": "error"})
            openid = session['openid']

            wechat = WechatBasic(appid=appid, appsecret=appsecret)
            # wechat.send_text_message(session['openid'], "test")
            # 调用公众号消息模板A0XK30w_sZPti5_gn33PJ5msng7yb71zAEcRa0E44oM发送领券通知
            template_id = 'A0XK30w_sZPti5_gn33PJ5msng7yb71zAEcRa0E44oM'
            """{first.DATA}}
            优惠券:{{keyword1.DATA}}
            来源:{{keyword2.DATA}}
            过期时间:{{keyword3.DATA}}
            使用说明:{{keyword4.DATA}}
            {{remark.DATA}}
            """
            json_data = {
                "first": {
                    "value": "恭喜你领券成功!",
                    "color": "#173177"
                },
                "keyword1": {
                    "value": discount.title,
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "网页获取",
                    "color": "#173177"
                },
                "keyword3": {
                    "value": expire_datetime_format,
                    "color": "#173177"
                },
                "remark": {
                    "value": "凭优惠券详情二维码领取",
                    "color": "#173177"
                }
            }
            # 领取后需要写入到get_discount_record 表
            # TODO 下次是否能领取则通过这张表的数据来判断
            year = time.strftime("%Y", time.localtime())[2:]
            # TODO 根据时间戳生成唯一id,可能有点不规范
            code = year + str(time.time())[4:-3]
            record = GetTicketRecord(user_id=g.user.id, discount_id=discount_id, code=code)
            db.session.add(record)
            discount.count = discount.count + 1
            db.session.add(discount)
            db.session.commit()
            url = current_app.config.get('SITE_DOMAIN') + (
                url_for('shop.checkout', discount_id=discount_id, record_id=record.id))
            wechat.send_template_message(openid, template_id, json_data, url)

            # still 表示本周还能领多少张 TODO 静态数据需要替换
            # allow 表示本周允许领取多少张
            still = discount.number * discount.usable - 1
            # 获取永久二维码 scene_id前缀12表示是优惠券类型的二维码
            wechat = WechatBasic(appid=current_app.config.get('WECHAT_APPID'),
                                 appsecret=current_app.config.get('WECHAT_APPSECRET'))
            data = {"action_name": "QR_LIMIT_SCENE",
                    "action_info": {"scene": {"scene_id": int(str("12") + str(record.id))}}}
            get_ticket_data = wechat.create_qrcode(data)
            ticket = get_ticket_data.get("ticket")
            session['ticket'] = ticket
            # 写入数据库
            record.ticket = ticket
            db.session.add(record)
            db.session.commit()

            return json.dumps(
                {"message": {"still": still, "allow": 1, "tid": record.id, "ctime": "156151515"}, "redirect": "",
                 "type": "success"})

    # other discount in the discount
    other_discounts = Discount.query.filter(Discount.id != discount_id,
                                            Discount.brand_id == discount.brand_id)
    shops = discount.shops.all()
    return render_template('discount/detail.html', discount=discount,
                           discount_shop_count=discount_shop_count,
                           discount_id=discount_id, left_count=left_count,
                           other_discounts=other_discounts, shop_photos=shop_photos,
                           shops=shops, curr_ticket_record=curr_ticket_record.first(),
                           curr_ticket_records_week=curr_ticket_records_week)