Exemple #1
0
    def get_openid(self, code):
        if not code:
            return self.write(error(ErrorCode.PARAMERR, '需要code参数'))

        client = AsyncHTTPClient()
        query = {
            'appid': WXPAY_CONF['youcai']['appid'],
            'secret': WXPAY_CONF['youcai']['secret'],
            'code': code,
            'grant_type': 'authorization_code'
        }
        try:
            response = yield client.fetch(
                'https://api.weixin.qq.com/sns/oauth2/access_token?' +
                urllib.parse.urlencode(query))
            text = response.body.decode()
            result = json.loads(text)
            if 'errmsg' in result:
                return self.write(error(ErrorCode.THIRDERR, result['errmsg']))
            self.session['openid'] = result['openid']
            self.session.save()
            # return self.write({'openid': result})
        except Exception as e:
            log.error(e)
            return self.write(error(ErrorCode.REQERR, '请求openid出错'))
Exemple #2
0
    def insert_items(self, items_list):

        try:
            return self.db[_DATABASE].order_item.insert(items_list)
        except Exception as exc:
            log.error(exc)
            return self.write(error(ErrorCode.DBERR))
Exemple #3
0
    def post(self):
        '''接受手机号,发送验证码
        '''
        try:
            mobile = self.get_argument('mobile')
            if not mobile:
                return self.write(error(ErrorCode.PARAMERR))

        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.PARAMERR))
            return

        result = self.cache.get(mobile)
        if result:
            seconds = round(time.time()) - result['time']
            if seconds < 60:
                return self.write(
                    error(ErrorCode.REQERR, '请稍等%d秒重新发送' % (60 - seconds)))

        code = '%06d' % random.randint(0, 999999)
        content = "有菜手机验证码: {code}".format(code=code)
        try:
            self.sms(mobile, content)
            log.info('send sms: %s, %s' % (mobile, content))
        except Exception as e:
            log.error('send sms failed: %s, %s, %s' % (mobile, content, e))

        self.cache.set(mobile, {'code': code, 'time': round(time.time())}, 5)
        self.write({})
Exemple #4
0
    def get(self):
        doc = []
        page = records = total = ""
        try:
            request_param = self.request_arguments(["page"])
            page = request_param.get_int("page", 1)
            length = request_param.get_int("rows", 10)
            sord = request_param.get_str("sord", 1)
            sidx = request_param.get_str("sidx", "id")
            start = (page - 1) * length
            sord = 1 if sord == "desc" else -1
            doc = (
                yield self.db["ops"]
                .test.find({}, {"_id": 0})
                .sort([(sidx, sord)])
                .skip(start)
                .limit(length)
                .to_list(length)
            )
            records = yield self.db["ops"].test.count()
            total, reste = divmod(records, length)
            total = total + 1 if reste > 0 else total

            state = self.ecode.OK
        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOWN
            log.error(e)

        self.write(dict(rows=doc, page=page, records=records, total=total, state=state.eid))
Exemple #5
0
 def get_seckill_item(self, uid, item_id):
     query = {'uid': uid, 'siid': item_id}
     try:
         return self.db[_DATABASE].user_seckill.find_one(query)
     except Exception as exc:
         log.error(exc)
         return self.write(error(ErrorCode.DBERR))
Exemple #6
0
    def get(self):
        ua = self.request.headers['User-Agent']
        # hasWx = True if -1 != ua.find('MicroMessenger') else False
        hasWx = 'MicroMessenger' in ua

        hasWx = False

        state_url = self.get_argument(
            'state', ''
        )  # state 此参数扫码进来 如: http://192.168.1.222:8003/?state=recomitem/15

        if hasWx:  # 微信
            openid = self.session.get('openid')
            if not openid:  # 没有 openid
                code = self.get_argument('code', None)
                if not code:  # 没有 code 获取code
                    redirect_uri = urllib.parse.quote(self.request.protocol +
                                                      '://' +
                                                      self.request.host)
                    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + YOUCAI_WXPAY_CONF['appid'] + \
                          '&response_type=code&scope=snsapi_base' \
                          '&redirect_uri=' + redirect_uri \
                          + '&state=' + urllib.parse.quote(state_url) \
                          + '&connect_redirect=1#wechat_redirect'
                    self.redirect(url)
                else:  # 有 code 获取openid
                    client = AsyncHTTPClient()
                    query = {
                        'appid': WXPAY_CONF['youcai']['appid'],
                        'secret': WXPAY_CONF['youcai']['secret'],
                        'code': code,
                        'grant_type': 'authorization_code'
                    }
                    try:
                        response = yield client.fetch(
                            'https://api.weixin.qq.com/sns/oauth2/access_token?'
                            + urllib.parse.urlencode(query))
                        result = json.loads(response.body.decode())
                        # log.info(result)
                        if 'errmsg' in result:
                            log.error(result)
                            return self.write(
                                error(ErrorCode.THIRDERR, result['errmsg']))

                        self.session['openid'] = result['openid']
                        self.session.save()
                    except Exception as e:
                        log.error(e)
                        return self.write(error(ErrorCode.REQERR,
                                                '请求openid出错'))

        if state_url:  # 有状态 url 则重定向
            _url = '/#!/' + state_url
            self.redirect(_url)
            return

        self.render('index.html')
Exemple #7
0
 def post(self):
     try:
         mobile = self.get_argument('mobile', None)
     except Exception as e:
         log.error(e)
         self.write(error(ErrorCode.PARAMERR))
         return
     self.set_cookie("yc_mobile", mobile)
     self.write({})
Exemple #8
0
 def get_recom_price(self, item_id):
     query = {'id': item_id}
     filters = {'_id': 0, 'price': 1, 'title': 1, 'img': 1}
     sort = [('id', -1)]
     try:
         return self.db[_DATABASE].recom_item.find(
             query, filters).sort(sort).limit(1).to_list(1)
     except Exception as exc:
         log.error(exc)
         return self.write(error(ErrorCode.DBERR))
Exemple #9
0
 def request_arguments(self, params):
     arguments = self.request.arguments
     for param in params:
         if not arguments.get(param, ''):
             log.error("param:%s is need" % param)
             raise self.ecode.PARAM_ERR
     dto = Dict()
     dto.update({key: arguments[key][0].decode('utf-8') for key in arguments})
     log.warning("req params=%s" % dto)
     return dto
Exemple #10
0
 def request_arguments(self, params):
     arguments = self.request.arguments
     for param in params:
         if not arguments.get(param, ''):
             log.error("param:%s is need" % param)
             raise self.ecode.PARAM_ERR
     dto = Dict()
     dto.update(
         {key: arguments[key][0].decode('utf-8')
          for key in arguments})
     log.warning("req params=%s" % dto)
     return dto
Exemple #11
0
def make_order(openid, title, order_no, fee, remote_ip):
    # log.info('================openid===========')
    # log.info(openid)
    params = {
        'appid': YOUCAI_WXPAY_CONF['appid'],
        'mch_id': YOUCAI_WXPAY_CONF['mchid'],
        'nonce_str': uuid.uuid4().hex,
        'body': title,
        'detail': '公众号扫码订单',
        'out_trade_no': order_no,
        'total_fee': fee,
        'spbill_create_ip': remote_ip,
        'notify_url': YOUCAI_WXPAY_CONF['notify'],
        'trade_type': 'JSAPI',
        'openid': openid
    }
    # log.info('================params===========')
    # log.info(params)

    params.update({'sign': wxpay_sign(params)})
    try:
        xml = xmltodict.unparse({'xml': params}, full_document=False)
        resp = HTTPClient().fetch(YOUCAI_WXPAY_CONF['url'] +
                                  '/pay/unifiedorder',
                                  method='POST',
                                  body=xml)
        ret = xmltodict.parse(resp.body.decode())['xml']
        pay_params = {}
        if ret['return_code'] == 'SUCCESS' and ret['result_code'] == 'SUCCESS':
            sign = ret.pop('sign')
            if sign == wxpay_sign(ret):
                pay_params = {
                    'appId':
                    YOUCAI_WXPAY_CONF['appid'],
                    'timeStamp':
                    round(time.time()),
                    'nonceStr':
                    uuid.uuid4().hex,
                    'package':
                    'prepay_id={prepay_id}'.format(prepay_id=ret['prepay_id']),
                    'signType':
                    'MD5'
                }
                ret_sign = wxpay_sign(pay_params)
                pay_params.update({'paySign': ret_sign})
        else:
            log.error(ret)

        return pay_params
    except Exception as e:
        log.error(e)
Exemple #12
0
    def get(self):
        try:
            pid = int(self.get_argument('pid', -1))
            rrange = int(self.get_argument('range', 1))
            rtype = int(self.get_argument('type', 0))
            start = max(int(self.get_argument('start', 0)), 0)
            length = int(self.get_argument('length', 50))
            group = int(self.get_argument('group', 0))
            if pid == -1 and rtype == 2 and group:
                start = 0
                length = 1000
            else:
                group = 0
                length = min(max(int(length), 1), 100)
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.PARAMERR))
            return

        query = {'status': 1} if rrange == 1 else {}
        if pid != -1:
            query.update({'pid': pid})
        elif rtype:
            if rtype == 2:
                query.update({'type': rtype})
            else:
                query.update({'pid': 0})

        try:
            result = []
            if group:
                result = self.cache.get('group_city')
            if not result:
                result = yield self.db['hamlet'].region.find(
                    query, {
                        '_id': 0,
                        'id': 1,
                        'name': 1,
                        'isleaf': 1
                    }).sort('priority',
                            1).skip(start).limit(length).to_list(length)
                if group:
                    self.cache.today('group_city', result)

            self.write({'regions': result})
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DBERR))
Exemple #13
0
 def add_seckill_item(self, uid, item_id):
     now = round(time.time() * 1000)
     try:
         return self.db[_DATABASE].user_seckill.insert({
             'id':
             mongo_uid(_DATABASE, 'user_seckill'),
             "uid":
             uid,
             "siid":
             item_id,
             'created':
             now
         })
     except Exception as exc:
         log.error(exc)
         return self.write(error(ErrorCode.DBERR))
Exemple #14
0
    def post(self):
        user = self.get_argument('user')
        passwd = self.get_argument('passwd')
        print(self.user_info)
        try:
            user_info = yield self.db['ops'].operator.find_one({'user': user, 'pwd': passwd},
                                                               {'_id': 0, 'passwd': 0})
            if user_info:
                self.save_user_info(user_info)
                self.redirect(self.get_argument("next", "/overview"))
            else:
                raise self.ecode.LOGIN_ERR

        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOW
            log.error(e)
            self.render('login.html', status=state.eid)
Exemple #15
0
    def post(self):
        try:
            request_param = self.request_arguments(['oper'])
            oper = request_param.get_str('oper', 'add')
            if oper == 'add':
                uid = yield self.get_id('operator')
                yield self.db['ops'].operator.insert({'id': uid['id'], 'modified': '2016-03-01 01:00', 'role': 0,
                                                      'status': 1,
                                                      'pid': [],
                                                      'pwd': "123",
                                                      'user': '******',
                                                      })

            state = self.ecode.OK
        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOWN
            log.error(e)

        self.write(dict(state=state.eid))
Exemple #16
0
    def get(self):
        if self.userid == 0:
            return self.write(error(ErrorCode.LOGINERR))

        try:
            docs = yield self.db['hamlet'].address.find({
                'uid': self.userid
            }, {
                '_id': 0,
                'id': 1,
                'name': 1,
                'mobile': 1,
                'city': 1,
                'region': 1,
                'address': 1,
                'default': 1
            }).sort([('default', -1), ('id', -1)]).limit(5).to_list(5)
            self.write(docs)
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DBERR))
Exemple #17
0
    def get(self):
        try:
            recom_item_id = int(self.get_argument('id'))
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.PARAMERR))
            return

        try:
            recom_item = yield self.db['youcai'].recom_item.find_one(
                {'id': recom_item_id}, {'_id': 0})
            if recom_item:
                if IMG_CACHE_URL:
                    recom_item['imgs'] = list(
                        map(
                            lambda x: IMG_CACHE_URL + x[len(IMAGE_DOMAIN):]
                            if x.startswith(IMAGE_DOMAIN) else x,
                            recom_item['imgs']))

                recom_item['descr'] = recom_item['descr'].replace(
                    '\n', '<br/>')
                recom_item['detail']['content'] = recom_item['detail'][
                    'content'].replace('\n', '<br/>')

                buffer = io.BytesIO()
                url = pyqrcode.create(self.request.protocol + '://' +
                                      self.request.host + '/#!/recomitem/' +
                                      str(recom_item_id))
                url.png(buffer, scale=5, quiet_zone=0)
                qrcode = base64.encodebytes(
                    buffer.getvalue()).decode().replace('\n', '')

                recom_item['qrcode'] = qrcode
                return self.write(recom_item)
            else:
                return self.write(error(ErrorCode.NODATA))
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DATAERR))
            return
Exemple #18
0
    def post(self):
        try:
            request_param = self.request_arguments(['oper'])
            oper = request_param.get_str('oper', 'add')
            if oper == 'add':
                uid = yield self.get_id('operator')
                yield self.db['ops'].operator.insert({
                    'id': uid['id'],
                    'modified': '2016-03-01 01:00',
                    'role': 0,
                    'status': 1,
                    'pid': [],
                    'pwd': "123",
                    'user': '******',
                })

            state = self.ecode.OK
        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOWN
            log.error(e)

        self.write(dict(state=state.eid))
Exemple #19
0
    def post(self):
        user = self.get_argument('user')
        passwd = self.get_argument('passwd')
        print(self.user_info)
        try:
            user_info = yield self.db['ops'].operator.find_one(
                {
                    'user': user,
                    'pwd': passwd
                }, {
                    '_id': 0,
                    'passwd': 0
                })
            if user_info:
                self.save_user_info(user_info)
                self.redirect(self.get_argument("next", "/overview"))
            else:
                raise self.ecode.LOGIN_ERR

        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOW
            log.error(e)
            self.render('login.html', status=state.eid)
Exemple #20
0
    def post(self):
        try:
            request_param = self.request_arguments(["oper"])
            oper = request_param.get_str("oper")
            if oper == "add":
                uid = yield self.get_id("server")
                yield self.db["ops"].test.insert(
                    {
                        "id": uid["id"],
                        "modified": "2016-03-01 01:00",
                        "project_name": "aa",
                        "status": "Yes",
                        "location_name": "aa",
                        "note": "haha",
                    }
                )

            state = self.ecode.OK
        except Exception as e:
            state = isinstance(e, Exception) and e or self.ecode.UNKNOWN
            log.error(e)

        self.write(dict(state=state.eid))
Exemple #21
0
    def post(self):
        try:
            mobile = self.get_argument('mobile')
            smscode = self.get_argument('smscode')

        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.PARAMERR))
            return

        now = round(time.time()) * 1000

        smscode_check = self.cache.get(mobile)
        if not smscode_check:
            return self.write(error(ErrorCode.CODEXPIRE))
        if smscode != smscode_check.get('code'):
            return self.write(error(ErrorCode.CODEERR))

        try:
            user = yield self.db['hamlet'].user.find_one({'mobile': mobile}, {'_id': 0})
            if not user:            # 新用户
                user_id = mongo_uid('hamlet', 'user')
                user = {
                    'id': user_id,
                    'unionid': None,
                    'openid': None,
                    'name': None,
                    'nickname': None,
                    'sex': 0,
                    'mobile': mobile,
                    'role': 0,
                    'province': None,
                    'city': None,
                    'address': None,
                    'headimg': GRAVATAR_URL.format(hash=md5(('SQC%d' % user_id).encode()).hexdigest()),
                    'bgimg': None,
                    'hometown': None,
                    'career': None,
                    'hobby': None,
                    'proverb': None,
                    'birthday': None,
                    'cid': 0,
                    'rid ': 0,
                    'zid': 0,
                    'ozid': 0,
                    'zname': None,
                    'coins': 100,
                    'oid': 0,
                    'password': '',
                    'lastlat': None,
                    'lastlng': None,
                    'lastip': None,
                    'status': 0,
                    'offline': False,
                    'created': now,
                    'modified': now}
                yield self.db['hamlet'].user.insert(user)

                self.save_userid(user['id'])
                del user['_id']
                self.session['op'] = user
            else:
                self.save_userid(user['id'])
                self.session['op'] = user
            self.session.save()

            # 获取用户地址列表
            address_list = yield self.db['hamlet'].address.find({'uid': self.userid}, {'_id': 0, 'id': 1, 'default': 1, 'name': 1, 'mobile': 1, 'city': 1, 'region': 1, 'address': 1}).sort([('default', -1), ('id', 1)]).limit(10).to_list(10)
            
            op = {
                'id': user['id'],
                'mobile': user['mobile'],
                'name': user['name'],
                'nickname': user['nickname']
            }
            return self.write({'user': op, 'address_list': address_list})

        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DBERR))
            return
Exemple #22
0
    def get(self):
        self.xsrf_token

        try:
            code = self.get_argument('code', None) or None
            source = self.get_argument('s', '') or ''  # 来源
        except Exception as e:
            log.error(e)
            code = None

        # qmmf:全民免费
        if source not in ['qmmf']:  # 排除无效值
            source = ''

        data = {'msg': '已过期', 'coupons': []}

        if not code:  # code 未传递
            # self.write(error(ErrorCode.UNKOWN, 'code 未传递'))
            self.render('coupon/coupon_error.html', data=data)
            return

        # 验证优惠券包合法性
        try:
            coupon_pack = yield self.db['youcai'].coupon_pack.find_one(
                {'code': code}, {
                    '_id': 0,
                    'id': 1,
                    'code': 1,
                    'remains': 1
                })
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.SRVERR, '呃,出了点小问题,有菜君正在处理,请稍候再试!'))
            return

        if not coupon_pack:  # code 无效
            # self.write(error(ErrorCode.UNKOWN, 'code 无效'))
            self.render('coupon/coupon_error.html', data=data)
            return

        coupons = yield self.db['youcai'].coupon \
            .find({'cpid': coupon_pack['id']}, {'_id': 0, 'uid': 1, 'discount': 1, 'created': 1}).sort(
            [('created', -1)]).to_list(None)
        if coupons:
            for coupon in coupons:
                user = yield self.db['hamlet'].user \
                    .find_one({'id': coupon['uid']}, {'_id': 0, 'nickname': 1, 'mobile': 1, 'headimg': 1})
                coupon['created'] = time.strftime(
                    '%Y-%m-%d %X',
                    time.localtime(int(coupon['created']) / 1000))
                coupon['discount'] = int(coupon['discount'] / 100)
                coupon['headimg'] = user['headimg']
                coupon['text'] = '红包的金额和你的颜值一样高哦'
                if user['nickname']:
                    if len(user['nickname']) > 7:
                        coupon['nickname'] = user['nickname'][:6] + '*' * 2
                    else:
                        coupon['nickname'] = user['nickname']
                else:
                    coupon['nickname'] = user['mobile'][:3] + '*' * 6 + user[
                        'mobile'][-2:]

        else:
            coupons = []

        if coupon_pack['remains'] <= 0:  # 优惠券已经被抢光
            # self.write(error(ErrorCode.UNKOWN, "优惠券已经被抢光"))
            self.render('coupon/coupon_error.html',
                        data={
                            'msg': '抢光了',
                            'coupons': coupons
                        })
            return

        # 获取历史优惠券信息
        coupon = {}
        try:
            # self.set_cookie("yc_mobile", '18521592117')
            # cookie_mobile = self.get_secure_cookie("yc_mobile")
            cookie_mobile = self.get_cookie("yc_mobile")
            if cookie_mobile:
                # 获取 uid
                user = yield self.db['hamlet'].user.find_one(
                    {'mobile': cookie_mobile}, {
                        '_id': 0,
                        'id': 1
                    })
                if user:
                    # 获取该批次优惠券
                    coupon = yield self.db['youcai'].coupon \
                        .find_one({'cpid': coupon_pack['id'], 'uid': user['id']},
                                  {'_id': 0, 'id': 1, 'type': 1, 'distype': 1, 'discount': 1, 'charge': 1}
                                  )
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.SRVERR, '呃,出了点小问题,有菜君正在处理,请稍候再试!'))
            return

        if coupon:
            coupon['discount'] = int(coupon['discount'] / 100)
        else:
            coupon = {}

        self.render('coupon/coupon.html',
                    coupon_pack=coupon_pack,
                    coupon=coupon,
                    data={
                        'coupons': coupons,
                        'source': source
                    })
Exemple #23
0
    def post(self):
        if self.userid == 0:
            return self.write(error(ErrorCode.LOGINERR))

        try:
            raw_extras = self.get_argument(
                'extras', None)  # 格式:id1:amount1,id2:amount2...
            name = self.get_argument('name')
            mobile = self.get_argument('mobile')
            address = self.get_argument('address')
            memo = self.get_argument('memo', '')
            paytype = int(self.get_argument('paytype', None) or 2)
        except Exception as e:
            log.error(e)
            return self.write(error(ErrorCode.PARAMERR))

        if not name or not mobile or not address:
            log.error("name or mobile or address must specified")
            return self.write(error(ErrorCode.PARAMERR))

        if not raw_extras:
            log.error("raw extras can't be null")
            return self.write(error(ErrorCode.PARAMERR))

        oid = mongo_uid(_DATABASE, 'order')
        order_no = gen_orderno(oid, short=True)  # used for alipay also
        # combo_order_no = 0
        order_type = 3
        status = 0
        times = 0
        item_type = 2
        fid = 0
        fname = ''

        # farm_and_items = {}
        raw_extras_list = raw_extras.split(',')
        for item in raw_extras_list:  # 这里其实还残留有问题,暂时只是购买一件商品还可以,要是
            match = re.match(r"^(\d+)\:(\d+)$",
                             item)  # 多件商品,而且商品列表中已经有一件购买过的秒杀商品 -->
            item_id = int(match.group(1))  # 中途报错,会使用户不能购买一些自己没有购买过的秒杀品
            item_obj = yield self.get_recom_item(item_id)
            if not item_obj:
                raise ItemNotFoundError(item_id)

            item_obj = item_obj[0]
            recom_type = item_obj['type']

            if not fid:  # 既然不存在拆分订单,只要fid和fname赋过值,就无需再赋值
                fid = item_obj['fid']
            if not fname:
                fname = item_obj['farm']

            if recom_type == 2:  # 秒杀  然后只需对秒杀品特殊处理,删除普通单品无用处理
                item_type = 3
                ckey = 'seckill_%d_%d' % (self.userid, item_id)
                seckill = self.cache.get(ckey)
                if not seckill:
                    seckill = yield self.get_seckill_item(self.userid, item_id)
                if seckill:
                    return self.write(
                        error(ErrorCode.DATAEXIST, '您已经秒杀过该商品,不能重复秒杀!'))

                yield self.add_seckill_item(self.userid, item_id)
                self.cache.today(ckey, True)

        try:
            price = yield self.get_extras_price(raw_extras_list)
        except ItemNotFoundError as exc:
            log.error(exc)
            return self.write(error(ErrorCode.NODATA, '要购买的菜品在数据库找不到'))

        title = yield self.get_extras_title(raw_extras_list)
        combo, combo_idx = None, None
        combo_order_no = 0

        # freight
        freight = 1000 if item_type == 2 and price < 9900 else 0

        yield self.create_order(oid, order_no, combo_order_no, order_type,
                                item_type, price, freight, status, times, fid,
                                fname, combo, combo_idx, name, mobile, address,
                                memo, title)

        try:
            yield self.add_extras(order_no, raw_extras_list)
        except ItemNotFoundError as exc:
            log.error(exc)
            return self.write(error(ErrorCode.NODATA, '要购买的菜品在数据库找不到'))

        result = {'orderno': str(order_no)}

        fee = price + freight
        result.update({'fee': fee, 'freight': freight})
        if paytype == 2:  # 支付宝支付
            alipay_info = {
                'partner':
                "2088911366083289",
                'seller_id':
                "2088911366083289",
                'out_trade_no':
                order_no,
                'subject':
                title,
                'body':
                "有菜H5订单",
                'total_fee':
                "%.2f" % (fee / 100),
                'notify_url':
                "https://api.shequcun.com/alipay/notify?apptype={apptype}".
                format(apptype=APPTYPE_YOUCAI_H5),
                'service':
                "alipay.wap.create.direct.pay.by.user",
                'payment_type':
                "1",
                '_input_charset':
                "utf-8",
                'it_b_pay':
                "30m",
                'return_url':
                "https://youcai.shequcun.com/#!/pay_result"
            }
            acc = []
            for param in sorted(alipay_info.items(), key=itemgetter(0)):
                if param[1]:
                    acc.append('%s=%s' % (param[0], param[1]))

            sign = base64.encodebytes(
                rsa.sign('&'.join(acc).encode(), PRI_KEY,
                         'SHA-1')).decode().replace('\n', '')
            alipay_info.update({'sign': sign, 'sign_type': 'RSA'})
            resp = yield AsyncHTTPClient().fetch(
                "https://mapi.alipay.com/gateway.do?" + urlencode(alipay_info))
            # result.update({'alipay': "https://mapi.alipay.com/gateway.do?" + urlencode(alipay_info)})
            result.update({'alipay': resp.effective_url})
        elif paytype == 3:  # 微信支付
            params = {
                'appid': YOUCAI_WXPAY_CONF['appid'],
                'mch_id': YOUCAI_WXPAY_CONF['mchid'],
                'nonce_str': uuid.uuid4().hex,
                'body': title,
                'detail': '公众号扫码订单',
                'out_trade_no': order_no,
                'total_fee': fee,
                'spbill_create_ip': self.request.remote_ip,
                'notify_url': YOUCAI_WXPAY_CONF['notify'],
                'trade_type': 'JSAPI',
                'openid': self.session.get('openid')
            }
            params.update({'sign': wxpay_sign(params)})
            try:
                xml = xmltodict.unparse({'xml': params}, full_document=False)
                resp = yield AsyncHTTPClient().fetch(YOUCAI_WXPAY_CONF['url'] +
                                                     '/pay/unifiedorder',
                                                     method='POST',
                                                     body=xml)
                ret = xmltodict.parse(resp.body.decode())['xml']

                if ret['return_code'] == 'SUCCESS' and ret[
                        'result_code'] == 'SUCCESS':
                    sign = ret.pop('sign')
                    if sign == wxpay_sign(ret):
                        pay_params = {
                            'appId':
                            YOUCAI_WXPAY_CONF['appid'],
                            'timeStamp':
                            round(time.time()),
                            'nonceStr':
                            uuid.uuid4().hex,
                            'package':
                            'prepay_id={prepay_id}'.format(
                                prepay_id=ret['prepay_id']),
                            'signType':
                            'MD5'
                        }
                        ret_sign = wxpay_sign(pay_params)
                        pay_params.update({'paySign': ret_sign})

                        self.session['wx_pay'] = pay_params
                        self.session.save()
                else:
                    log.error(ret)
            except Exception as e:
                log.error(e)

        return self.write(result)
Exemple #24
0
    def post(self):
        if self.userid == 0:
            return self.write(error(ErrorCode.LOGINERR))

        try:
            aid = int(self.get_argument('id', None) or 0)
            name = self.get_argument('name')
            mobile = self.get_argument('mobile')
            city = self.get_argument('city', '北京')
            region = self.get_argument('region')
            address = self.get_argument('address')
        except Exception as e:
            log.error(e)
            return self.write(error(ErrorCode.PARAMERR))

        now = round(time.time() * 1000)
        try:
            if aid:
                data = {}
                if name:
                    data['name'] = name
                if mobile:
                    data['mobile'] = mobile
                if city:
                    data['city'] = city
                if region:
                    data['region'] = region
                if address:
                    data['address'] = address
                if not data:
                    data['default'] = True
                data['modified'] = now

                doc = yield self.db['hamlet'].address.find_and_modify(
                    {'id': aid}, {'$set': data},
                    new=True,
                    fields={
                        '_id': 0,
                        'city': 1,
                        'region': 1,
                        'address': 1
                    })
                if doc:
                    result = doc['city'] + doc['region'] + doc['address']
                else:
                    return self.write(error(ErrorCode.NODATA))

                if data.get('default'):
                    yield self.db['hamlet'].address.update(
                        {
                            'uid': self.userid,
                            'id': {
                                '$ne': aid
                            }
                        }, {'$set': {
                            'default': False
                        }},
                        multi=True)
            else:
                aid = mongo_uid('hamlet', 'address')
                yield self.db['hamlet'].address.insert({
                    'id': aid,
                    'uid': self.userid,
                    'name': name,
                    'mobile': mobile,
                    'city': city,
                    'region': region,
                    'street': '',
                    'zid': 0,
                    'zname': '',
                    'building': '',
                    'unit': '',
                    'room': '',
                    'bur': '',
                    'address': address,
                    'default': True,
                    'created': now,
                    'modified': now
                })
                result = city + region + address
                yield self.db['hamlet'].address.update(
                    {
                        'uid': self.userid,
                        'id': {
                            '$ne': aid
                        }
                    }, {'$set': {
                        'default': False
                    }},
                    multi=True)

            try:
                yield self.db['hamlet'].user.update(
                    {'id': self.userid}, {'$set': {
                        'address': result
                    }})
                self.session['user'].update({'address': result})
                self.session.save()
            except Exception as e:
                log.error(e)

            self.write({'address': result})
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DBERR))
Exemple #25
0
    def create_order(self,
                     oid,
                     order_no,
                     combo_order_no,
                     order_type,
                     item_type,
                     price,
                     freight,
                     status,
                     times,
                     fid,
                     farm,
                     combo,
                     combo_idx,
                     name,
                     mobile,
                     address,
                     memo,
                     title=None):
        oid = oid
        order_no = order_no
        combo_order_no = combo_order_no
        order_type = order_type  # 1 for combo order
        item_type = item_type
        uid = self.userid
        combo_idx = combo_idx
        if not combo:
            combo_id = None
            title = title
            img = ''
            year = None
            issue_no = None
        else:
            combo_id = combo['id']
            title = combo['title']
            img = combo['img']
            year = combo['year']
            issue_no = combo['issue_no']
        price = price
        freight = freight
        times = times
        name = name
        mobile = mobile
        address = address
        paytype = 0
        status = status  # 0 means haven't payed yet
        fid = fid
        farm = farm

        now = round(time.time() * 1000)
        if order_type == 2:
            chgtime = {"0": now, "1": now}
        else:
            chgtime = {"0": now}

        kwargs = dict(id=oid,
                      orderno=order_no,
                      con=combo_order_no,
                      uid=uid,
                      combo_id=combo_id,
                      combo_idx=combo_idx,
                      coupon_id=0,
                      fid=fid,
                      farm=farm,
                      title=title,
                      img=img,
                      year=year,
                      issue_no=issue_no,
                      type=order_type,
                      item_type=item_type,
                      price=price,
                      freight=freight,
                      times=times,
                      name=name,
                      mobile=mobile,
                      address=address,
                      memo=memo,
                      paytype=paytype,
                      status=status,
                      chgtime=chgtime,
                      created=now,
                      modified=now)

        try:
            return self.db[_DATABASE].order.insert(kwargs)
        except Exception as exc:
            log.error(exc)
            return self.write(error(ErrorCode.DBERR))
Exemple #26
0
    def post(self):
        '''
        用户输入手机号,获取优惠券
        参数:
            mobile:
            code:
            smscode(可选)
        '''
        try:
            mobile = self.get_argument('mobile', None)
            code = self.get_argument('code', None)
            smscode = self.get_argument('smscode', None)
        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.PARAMERR))
            return

        # 验证码是否存在,是它第一次还是第二次请求的标志
        if smscode:
            cache_smscode = self.cache.get(mobile)
            if not cache_smscode or smscode != cache_smscode.get('code'):
                self.write(error(ErrorCode.CODEERR))
                return

        now = round(time.time() * 1000)
        try:
            coupon_pack = yield self.db['youcai'].coupon_pack.find_one(
                {'code': code}, {'_id': 0})

            if not coupon_pack:  # 优惠券包无效
                self.write(error(ErrorCode.UNKOWN, '优惠券包不存在'))
                return

            if coupon_pack['expire'] <= now:  # 优惠券包已过期
                self.write(error(ErrorCode.UNKOWN, '优惠券已过期'))
                return

            if coupon_pack['remains'] <= 0:
                self.write(error(ErrorCode.UNKOWN, "优惠券已经被抢光"))
                return

            # 该手机号对应的用户是否存在,不存在则插入user表
            user = yield self.db['hamlet'].user.find_one({'mobile': mobile}, {
                '_id': 0,
                'id': 1
            })

            if user:  # 老用户
                # 不管怎么样,只要用户存在,获取优惠券就正常进行
                user_id = user['id']
                coupon = yield self.db['youcai'].coupon.find_one(
                    {
                        'uid': user_id,
                        'cpid': coupon_pack['id']
                    }, {
                        '_id': 0,
                        'id': 1,
                        'type': 1,
                        'distype': 1,
                        'discount': 1,
                        'charge': 1
                    })
                if coupon:
                    # 用户手机号存放在 cookie中
                    self.set_cookie("yc_mobile", mobile)
                    self.write({'coupon': coupon})
                    return
            else:  # 新用户
                # 用户不存在,则进行判断是否有验证码,
                # 有     :则是验证码已经通过,继续往下走
                # 没有   :则发验证码,
                if smscode:  # 注册 并 领取红包
                    user_id = mongo_uid('hamlet', 'user')
                    user_doc = {
                        'id':
                        user_id,
                        'unionid':
                        None,
                        'openid':
                        None,
                        'name':
                        None,
                        'nickname':
                        None,
                        'sex':
                        0,
                        'mobile':
                        mobile,
                        'role':
                        0,
                        'province':
                        None,
                        'city':
                        None,
                        'address':
                        None,
                        'headimg':
                        GRAVATAR_URL.format(
                            hash=md5(('SQC%d' %
                                      user_id).encode()).hexdigest()),
                        'bgimg':
                        None,
                        'hometown':
                        None,
                        'career':
                        None,
                        'hobby':
                        None,
                        'proverb':
                        None,
                        'birthday':
                        None,
                        'cid':
                        0,
                        'rid ':
                        0,
                        'zid':
                        0,
                        'ozid':
                        0,
                        'zname':
                        None,
                        'coins':
                        100,
                        'oid':
                        0,
                        'password':
                        '',
                        'lastlat':
                        None,
                        'lastlng':
                        None,
                        'lastip':
                        None,
                        'status':
                        0,
                        'offline':
                        False,
                        'created':
                        now,
                        'modified':
                        now
                    }
                    yield self.db['hamlet'].user.insert(user_doc)
                else:
                    # TODO -发-验-证-码-

                    # 改动 --> 不发送验证码,只是单纯的告诉前端,你需要获取验证
                    self.write(error(ErrorCode.NOUSER, '您还不是有菜用户,请注册领取红包'))
                    return

            # 优惠券包剩余数量减1
            ret = yield self.db['youcai'].coupon_pack.find_and_modify(
                {'code': code}, {'$inc': {
                    'remains': -1
                }},
                new=True,
                fields={
                    '_id': 0,
                    'remains': 1
                })
            if ret['remains'] == 0:
                yield self.db['youcai'].order.update(
                    {'orderno': coupon_pack['orderno']},
                    {'$set': {
                        'cpflag': False
                    }})

            # 添加一条优惠券
            discount = random.randint(coupon_pack['minpar'],
                                      coupon_pack['maxpar'])
            discount -= discount % 100
            coupon_doc = {
                'id': mongo_uid('youcai', 'coupon'),
                'cpid': coupon_pack['id'],
                'uid': user_id,
                'type': coupon_pack['type'],
                'distype': 1,
                'discount': discount,
                'charge': coupon_pack['charge'],
                'used': False,
                'expire':
                now + 2592000000,  # 2592000000 = 30 * 24 * 60 * 60 * 1000,
                'created': now
            }
            yield self.db['youcai'].coupon.insert(coupon_doc)

            # 用户手机号存放在 cookie中
            self.set_cookie("yc_mobile", mobile)
            # self.set_secure_cookie("yc_mobile", mobile)

            return self.write({
                'coupon': {
                    'cpid': coupon_doc['cpid'],
                    'type': coupon_doc['type'],
                    'distype': coupon_doc['distype'],
                    'discount': coupon_doc['discount'],
                    'charge': coupon_doc['charge']
                }
            })

        except Exception as e:
            log.error(e)
            self.write(error(ErrorCode.DBERR, '呃,出了点小问题,有菜君正在处理,请稍候再试!'))
            return