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))
def add_extras(self, order_no, items_list): items = [] for raw_item in items_list: match = re.match(r"^(\d+)\:(\d+)$", raw_item) item_id, item_amount = int(match.group(1)), int(match.group(2)) item_obj = yield self.get_recom_item(item_id) if not item_obj: raise ItemNotFoundError(item_id) item_obj = item_obj[0] title = item_obj['title'] try: img = item_obj['imgs'].pop() except IndexError: img = '' packw = item_obj['packw'] packs = item_amount oid = mongo_uid(_DATABASE, 'order_item') order_no = order_no now = round(time.time() * 1000) item = { 'id': oid, 'orderno': order_no, 'siid': item_id, 'title': title, 'img': img, 'packw': packw, 'packs': packs, 'created': now, 'modified': now } items.append(item) yield self.insert_items(items)
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)
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))
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
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