Ejemplo n.º 1
0
    def _post(self):
        phone = self.get_argument('account')
        if not check.check_account(phone):
            return Result(alert.INVALID_PHONE)()
        
        tkey = keys.VERIFY_CODE_TIME.format(phone)
        op = self.cache.get(tkey)
        if op:
            return Result(alert.VERIFY_CODE_OP)()
        
        code = check.gen_verify_code()
        params = {
            'apikey':constant.YUNPIAN_APIKEY, 
             'mobile':phone, 
             'text':constant.VERIFY_CODE_TEXT.format(code)
        }
        headers = {
            "Accept":"application/json;charset=utf-8;",
            "Content-Type":"application/x-www-form-urlencoded;charset=utf-8;"
        }
        rt = http_util.urllib_request(constant.YUNPIAN_SHORTMSG, "POST", params, headers)
        result = json.loads(rt)
        if result['code'] != 0:
            return Result(alert.VERIFY_CODE_FAIL)()
        
        # save code
        key = keys.VERIFY_CODE.format(phone)
        self.cache.set(key, code, keys.VERIFY_CODE_EXPIRE)
        self.cache.set(tkey, int(time.time()), keys.VERIFY_CODE_TIME_EXPIRE)

        return Result(alert.SUCCESS)()
Ejemplo n.º 2
0
 def post(self, args):
     """
     Retrieve the password # 找回密码
     """
     result = False
     receiver = args.get('email')
     adminDao = AdminDao()
     try:
         result = adminDao.findPass(receiver)
     except Exception as e:
         abort(500, e)
     if result:
         return Result.success()
     return Result.error()
Ejemplo n.º 3
0
 def request_unifiedorder(self, order_code, amount):
     '''
     微信统一订单请求
     '''
     unifiedorder_request = {
         'appid': constant.WBC['APPID'], # 公众账号ID
         'body': u'公司名称-商品',  # 商品描述
         'mch_id': '1397xxxxxx8',  # 商户号:深圳市泽慧文化传播有限公司
         'nonce_str': '',  # 随机字符串
         'notify_url': settings.PAY_NOTICE_URL,  # 微信支付结果异步通知地址
         'openid': self.user.id,  # openid
         'out_trade_no': '',  # 商户订单号
         'spbill_create_ip': self.request.remote_ip ,  # 终端IP
         'total_fee': '',  # 标价金额
         'trade_type': 'JSAPI',  # 交易类型
     }
     unifiedorder_request['nonce_str'] = check.get_nonce_str()
     unifiedorder_request['out_trade_no'] = order_code  # 内部订单号码
     unifiedorder_request['total_fee'] = int(amount * 100)  #单位 分
     
     # 签名并生成xml
     xml = self.get_xml(unifiedorder_request)
     resp = requests.post(constant.WECHAT_UNIFIED_ORDER, data=xml, 
                          headers={'Content-Type': 'text/xml'})
     msg = resp.text.encode('ISO-8859-1').decode('utf-8')
     xml_resp = xmltodict.parse(msg)
     xml_resp = xml_resp['xml']
     
     if xml_resp['return_code'] == 'SUCCESS':
         if xml_resp['result_code'] == 'SUCCESS':
             prepay_id = xml_resp['prepay_id']
             timestamp = str(int(time.time()))
             data = {
                 "app_id": xml_resp['appid'],
                 "nonce_str": check.get_nonce_str(),
                 "package": "prepay_id={0}".format(prepay_id),
                 "sign_type": "MD5",
                 "timestamp": timestamp
             }
             data['pay_sign'] = self.get_sign(data)
             data['order_code'] = order_code  # 付款后操作的订单
             # 签名后返回给前端做支付参数
             return Result(alert.SUCCESS, data=data)
         else:
             msg = xml_resp['err_code_des']
             return Result(alert.FAIL, message=msg)
     else:
         msg = xml_resp['return_msg']
         return Result(alert.FAIL, message=msg)
Ejemplo n.º 4
0
 def post(self, args):
     """
     Reflesh Token # 刷新令牌
     """
     data = {}
     rftoken = args.pop('rftoken')
     username = args.pop('username')
     adminDao = AdminDao()
     try:
         data = adminDao.reflesh_token(rftoken, username)
     except Exception as e:
         abort(500, e)
     if data:
         return Result.success(data)
     return Result.error(data, message="Reflesh Token Fail")
Ejemplo n.º 5
0
 def post(self, args):
     """
     Login # 登录
     """
     data = {}
     username = args.pop('username')
     password = args.pop('password')
     adminDao = AdminDao()
     try:
         data = adminDao.login(username, password)
     except Exception as e:
         abort(500, e)
     if data:
         return Result.success(data)
     return Result.error(data, message="Account or Password Error")
Ejemplo n.º 6
0
 def _get(self):
     order_code = self.get_argument("order_code", '')
     if order_code:
         order = self.order_service.get_by_code(code=order_code)
         if order:
             return self.look_unifiedorder(order)()
     return Result(alert.FAIL, message=u"订单不存在!")()
Ejemplo n.º 7
0
    def look_unifiedorder(self, order):
        '''
        微信统一订单查询
        '''
        orderquery = {
            'appid': constant.WBC['APPID'],
            'mch_id': constant.WBC['MCHID'],
            'nonce_str': check.get_nonce_str(),
            'out_trade_no': order.code
        }
        xml = self.get_xml(orderquery)

        resp = requests.post(constant.WECHAT_QUERY_ORDER, data=xml.encode('utf-8'), 
                             headers={'Content-Type': 'text/xml'})
        msg = resp.text.encode('ISO-8859-1').decode('utf-8')
        xmlresp = xmltodict.parse(msg)
        xmlresp = xmlresp['xml']

        if xmlresp['return_code'] == 'SUCCESS':
            if xmlresp['result_code'] == 'SUCCESS':
                if xmlresp['trade_state'] == 'SUCCESS':
                    transaction_id = xmlresp['transaction_id']
                    cash_fee = xmlresp['cash_fee']

                    user_pay = UserPay()
                    user_pay.user_goods_id = order.id
                    user_pay.transaction_id = transaction_id
                    user_pay.user_id = self.user.id
                    user_pay.goods_id = order.goods_id
                    user_pay.amount = cash_fee
                    user_pay.status = 1
                    
                    self.order_service.pay(user_pay, {'status':1, 'transaction_id':transaction_id}, id=order.id)
                    return Result(alert.SUCCESS)
                else:
                    msg = xmlresp['trade_state_desc']
                    return Result(alert.FAIL, message=msg)
            else:
                msg = xmlresp['err_code_des']
                return Result(alert.FAIL, message=msg)
        else:
            msg = xmlresp['return_msg']
            return Result(alert.FAIL, message=msg)
Ejemplo n.º 8
0
 def get(self):
     """
     add # 增加
     """
     new_captcha = CaptchaTool()
     img, code = new_captcha.get_verify_code()
     session["code"] = code
     current_app.logger.debug('code::')
     current_app.logger.debug(str(session.get("code", '')))
     return Result.success(img)
Ejemplo n.º 9
0
 def post(self):
     """
     upload avatar # 上传头像
     """
     uid = request.uid
     rfile = request.files.get('file')
     filesize = request.form['size']
     data = {}
     attachmentsDao = AttachmentsDao()
     try:
         data = attachmentsDao.upload_avatar(uid, rfile, filesize)
     except Exception as e:
         abort(500, e)
     return Result.success(data)
Ejemplo n.º 10
0
    def _post(self):
        status = int(self.get_argument('status', -1))
        status_list = [status] if status in [1, 2] else [1, 2, 3]

        user_goods_service = UserGoodsService(UserGoods)
        orders = user_goods_service.gets(user_id=self.user.id)

        order_list = []
        for order in orders:
            if order.status not in status_list:
                continue

            d = {}
            d['order_id'] = order.id
            d['user_id'] = order.user_id
            d['goods_id'] = order.goods_id
            d['goods_name'] = order.goods_name
            d['number'] = order.number
            d['feed_day'] = order.feed_day
            d['deliver_date'] = str(order.deliver_date).split()[0]
            #             d['create_date'] = order.create_date
            d['status'] = order.status

            goods = GoodsService(GoodsInfo).get(id=order.goods_id)
            d['brief'] = goods.brief
            d['type'] = goods.type

            d['avatar'] = ''
            if goods.avatar_id:
                avatar = AvatarService(AvatarInfo).get(id=goods.avatar_id)
                d['avatar'] = os.path.join(settings.AVATAR_URL,
                                           avatar.filename) if avatar else ''

            if order.status != 1:
                di = DeliverService(DeliverInfo).get(user_goods_id=order.id)
                if di:
                    d['deliver_date'] = str(di.create_date).split()[0]

            ftext, stext, after = self.get_text(order, d['deliver_date'],
                                                goods.type)
            d['ftext'] = ftext
            d['stext'] = stext
            d['after'] = after

            order_list.append(d)

        return Result(alert.SUCCESS, data=order_list[::-1])()
Ejemplo n.º 11
0
 def post(self):
     """
     upload
     """
     uid = request.uid
     rfile = request.files.get('file')
     filesize = request.form['size']
     module_name = request.headers.get("module_name")
     module_obj_id = request.headers.get("module_obj_id")
     current_app.logger.debug("module_name:" + str(module_name))
     current_app.logger.debug("module_obj_id:" + str(module_obj_id))
     data = {}
     attachmentsDao = AttachmentsDao()
     try:
         data = attachmentsDao.upload(uid, rfile, filesize, module_name,
                                      module_obj_id)
     except Exception as e:
         abort(500, e)
     return Result.success(data)
Ejemplo n.º 12
0
 def _post(self):
     gtype = int(self.get_argument('gtype', 0))
     gtype_list = [gtype] if gtype != 0 else [1, 2, 3]        
     
     service = GoodsService(GoodsInfo)
     all_goods = service.cgets(status=0) 
     
     goods_list = []
     for goods in all_goods:
         if goods.number <= 0:
             continue
         if goods.type not in gtype_list:
             continue
         
         d = {}
         d['id'] = goods.id
         d['name'] = goods.name
         d['price'] = goods.price
         d['feed_day'] = goods.feed_day
         d['number'] = goods.number
         d['status'] = goods.status
         d['brief'] = goods.brief
         d['detail'] = goods.detail  
         d['type'] = goods.type 
         
         if goods.avatar_id:
             avatar_service = AvatarService(AvatarInfo)
             avatar = avatar_service.get(id=goods.avatar_id)   
             d['avatar'] = os.path.join(settings.AVATAR_URL, avatar.filename) if avatar else ''
         
         dis = self.get_discount(goods.id)
         d['last_price'] = goods.price * dis['discount'] if 'discount' in dis else goods.price
         d['dis_desc'] = dis['desc'] if 'desc' in dis else ''
         
         d['price_string'] = str(d['price'])
         d['last_price_string'] = str(d['last_price'])
             
         goods_list.append(d)  
     
     return Result(alert.SUCCESS, data=goods_list)()        
Ejemplo n.º 13
0
    def confirm(token):
        """Confirm token # 确认令牌,返回确认状态

        Args:
            token (str): To be verified token
            
        Returns:
            object: app.common.result.Result 

        """
        # token decoding
        s = Serializer(
            secret_key=current_app.config['SECRET_KEY'],
            salt=current_app.config['AUTH_SALT'])
        data = {}
        try:
            data = s.loads(token)
            # token decoding faild
            # if it happend a plenty of times, there might be someone
            # trying to attact your server, so it should be a warning.
        except SignatureExpired:
            msg = 'token expired'
            # current_app.logger.warning(msg)
            return Result.error(data,status=Status.TOKEN_SIGNATURE_EXPIRED.status, message=Status.TOKEN_SIGNATURE_EXPIRED.message)
        except BadSignature as e:
            encoded_payload = e.payload
            if encoded_payload is not None:
                try:
                    s.load_payload(encoded_payload)
                except BadData:
                    # the token is tampered.
                    msg = 'token tampered'
                    return Result.error(data,status=Status.TOKEN_TAMPERED.status, message=Status.TOKEN_TAMPERED.message)
            msg = 'badSignature of token'
            return Result.error(data,status=Status.TOKEN_BADSIGNATURE.status, message=Status.TOKEN_BADSIGNATURE.message)
        except:
            msg = 'wrong token with unknown reason'
            return Result.error(data,status=Status.TOKEN_UNKNOWN_REASON.status, message=Status.TOKEN_UNKNOWN_REASON.message)
        if ('id' not in data) :
            msg = 'illegal payload inside'
            return Result.error(data,status=Status.TOKEN_ILLEGAL.status, message=Status.TOKEN_ILLEGAL.message)
        return Result.success(data=data,status=Status.TOKEN_SUCCESS.status, message=Status.TOKEN_SUCCESS.message)
Ejemplo n.º 14
0
 def post(self):
     """
     Admin logout - Post.
     """
     data = {}
     return Result.success(data)