Exemple #1
0
    def get(self, oiid):
        result = {'status': False, 'msg': 0}
        user = self.get_current_user()

        if user:
            try:
                orderitem = OrderItem.get(id=oiid)
                order = Order.get(id=orderitem.oid)

                if order.uid == user.id:
                    if OrderItem.select().where(
                            OrderItem.oid == orderitem.oid).count() == 1:
                        order.delete_instance()

                        if user.order > 0:
                            user.order = user.order - 1
                            user.save()
                            self.session['user'] = user
                            self.session.save()

                    orderitem.delete_instance()
                    result['status'] = True
                    result['msg'] = 200

                else:
                    result['msg'] = 403

            except Exception, ex:
                logging.error(ex)
                result['msg'] = 500
Exemple #2
0
 def get(self, oiid):
     result = {'status' : False, 'msg' : 0}
     user = self.get_current_user()
     
     if user:
         try:
             orderitem  = OrderItem.get(id = oiid)
             order = Order.get(id = orderitem.oid)
             
             if order.uid == user.id:
                 if OrderItem.select().where(OrderItem.oid == orderitem.oid).count() == 1:
                     order.delete_instance()
                     
                     if user.order > 0:
                         user.order = user.order - 1
                         user.save()
                         self.session['user'] = user
                         self.session.save()
                 
                 orderitem.delete_instance()
                 result['status'] = True
                 result['msg'] = 200
                 
             else:
                 result['msg'] = 403
             
         except Exception, ex:
             logging.error(ex)
             result['msg'] = 500
Exemple #3
0
    def post(self, oid, sid):

        result = {'status': False, 'msg': 0}
        user = self.get_current_user()

        if user:
            try:
                order = Order.get(id=oid)

                if order.uid == user.id:
                    try:
                        orderitem = OrderItem.get(OrderItem.oid == oid,
                                                  OrderItem.sid == sid)
                    except:
                        orderitem = OrderItem()

                    orderitem.oid = oid
                    orderitem.sid = sid
                    orderitem.num = orderitem.num + 1

                    try:
                        orderitem.save()
                        result['status'] = True
                        result['msg'] = 200
                    except Exception, ex:
                        logging.error(ex)
                        result['msg'] = 500
                else:
                    result['msg'] = 403
Exemple #4
0
 def post(self):
     result = {'status' : False, 'msg' : 0}
     user = self.get_current_user()
     
     if user:
         oiid = int(self.get_argument("oiid", 0))
         num = int(self.get_argument("num", 1))
         
         if (oiid > 0 and num > 0):
             try:
                 orderitem = OrderItem.get(id = oiid)
                 orderitem.num = num
                 
                 try:
                     orderitem.save()
                     result['status'] = True
                     result['msg'] = 200
                 
                 except Exception, ex:
                     logging.error(ex)
                     result['msg'] = 500
             except:
                 result['msg'] = 404
         else:
             result['msg'] = 400  
     else:
         result['msg'] = 403
     
     self.write(simplejson.dumps(result))
Exemple #5
0
    def get(self):
        orderitems = []
        user = self.current_user

        try:
            order = Order.get(uid=user.id, status=0)

            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order.id).dicts():
                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])
                    orderitems.append(orderitem)
                except:
                    pass
        except:
            order = Order()

        ashops = Shop.select().where((Shop.cid == 2) & (Shop.status != 9))
        self.render("shop/order.html",
                    orderitems=orderitems,
                    order=order,
                    ashops=ashops)
Exemple #6
0
def check_order_store_quantity(store_id, oid):
    result = 0
    items = OrderItem.select().where(OrderItem.order == oid)
    r = 0
    if store_id:
        for i in items:
            if i.product.is_store == 1:  # and i.product.store.id == int(store_id)
                r += 1
            else:
                r += check_store_product_quantity(store_id,
                                                  i.product_standard.id)
        if r == items.count():
            result = 1
    else:
        list = []
        order = Order.get(Order.id == oid)
        store = Store.select().where(Store.status == 1)
        sid = 0
        for s in store:
            ss = getDistanceAS(order.take_address.replace(' ', ''), s.id)
            if ss['flag'] == 1:
                list.append(float(ss['data']))
                if float(ss['data']) < setting.PeiSongDistance:
                    sid = s.id
        for i in items:
            if i.product.is_store == 1 and i.product.store.id == sid:
                r += 1
            else:
                r += check_store_product_quantity(sid, i.product_standard.id)
        if r == items.count():
            result = 1
    return result
Exemple #7
0
 def get(self, oid):
     orderitems = []
     price = 0.0
     credit = 0.0
     order = None
     try:
         order = Order.get(id = oid)
         print order.id
         for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts():
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 _oiprice = orderitem['shop'].price
                 
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
                     if orderitem['shop'].cid == 1:
                         _oicredit = orderitem['shopattr'].price
                         credit = credit + _oicredit * orderitem['num']
                         _oiprice = orderitem['shopattr'].price
                     else:
                         _oiprice = orderitem['shopattr'].price
                 else:
                     _oiprice = float(_oiprice)
                     
                 orderitems.append(orderitem)
                 price = price + float(_oiprice) * orderitem['num']
             except:
                 pass
         print price
     except:
         pass
     
     self.render("/responsive/user_confirmorder.html", order = order, credit = credit, orderitems = orderitems)
Exemple #8
0
    def post(self):
        result = {'status': False, 'msg': 0}
        user = self.get_current_user()

        if user:
            oiid = int(self.get_argument("oiid", 0))
            num = int(self.get_argument("num", 1))

            if (oiid > 0 and num > 0):
                try:
                    orderitem = OrderItem.get(id=oiid)
                    orderitem.num = num

                    try:
                        orderitem.save()
                        result['status'] = True
                        result['msg'] = 200

                    except Exception, ex:
                        logging.error(ex)
                        result['msg'] = 500
                except:
                    result['msg'] = 404
            else:
                result['msg'] = 400
        else:
            result['msg'] = 403

        self.write(simplejson.dumps(result))
Exemple #9
0
    def post(self):

        result = {'status': False, 'msg': 0}
        user = self.get_current_user()

        if user:
            sid = int(self.get_argument("sid", 0))
            said = int(self.get_argument("said", 0))
            num = int(self.get_argument("num", 1))

            #判断商品是否下架
            if sid > 0 and said > 0 and num > 0:
                try:
                    Shop.get(id=sid)
                    ShopAttr.get(id=said)

                    #判断是否有未使用的订单或生成新订单
                    try:
                        try:
                            order = Order.get(uid=user.id, status=0)
                        except:
                            order = Order()
                            order.uid = user.id
                            order.mobile = user.mobile
                            order.ordered = int(time.time())
                            try:
                                order.save()
                            except Exception, ex:
                                logging.error(ex)

                        try:
                            orderitem = OrderItem.get(oid=order.id,
                                                      sid=sid,
                                                      said=said)
                        except:
                            orderitem = OrderItem()

                        orderitem.oid = order.id
                        orderitem.sid = sid
                        orderitem.said = said
                        orderitem.num = orderitem.num + num
                        orderitem.save()

                        result['status'] = True
                        result['msg'] = 200

                    except Exception, ex:
                        logging.error(ex)
                        result['msg'] = 500

                except:
Exemple #10
0
 def post(self, oid, sid):
     
     result = {'status' : False, 'msg' : 0}
     user = self.get_current_user()
     
     if user:
         try:
             order = Order.get(id = oid)
             
             if order.uid == user.id:
                 try:
                     orderitem = OrderItem.get(OrderItem.oid == oid, OrderItem.sid == sid)
                 except:
                     orderitem = OrderItem()
                 
                 orderitem.oid = oid
                 orderitem.sid = sid
                 orderitem.num = orderitem.num + 1
                 
                 try:
                     orderitem.save()
                     result['status'] = True
                     result['msg'] = 200
                 except Exception, ex:
                     logging.error(ex)
                     result['msg'] = 500
             else:
                 result['msg'] = 403
Exemple #11
0
    def get(self):
        orderitems = []
        user = self.current_user

        order = None

        distributions = self.get_distributions()
        price = 0.0
        credit = 0.0

        try:
            order = Order.get(uid=user.id, status=0)

            try:
                mobile = '18014349809'
                sendmsg(self.settings, mobile, '新订单')
            except:
                pass

            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order.id).dicts():
                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    _oiprice = orderitem['shop'].price

                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])
                        if orderitem['shop'].cid == 1:
                            _oicredit = orderitem['shopattr'].price
                            credit = credit + _oicredit * orderitem['num']
                        else:
                            _oiprice = orderitem['shopattr'].price
                    else:
                        _oiprice = float(_oiprice)

                    orderitems.append(orderitem)

                    price = price + _oiprice * orderitem['num']

                except:
                    pass
            order.price = price
            order.save()

        except:
            pass

        if orderitems:
            self.render("shop/settle.html",
                        tmday=datetime.date.today() +
                        datetime.timedelta(days=1),
                        order=order,
                        orderitems=orderitems,
                        distributions=distributions.values(),
                        credit=credit)
Exemple #12
0
    def get(self):
        user = self.get_current_user()
        status = self.get_argument("status", None)

        ft = (Order.uid == user.id)

        if status:
            ft = ft & (Order.status == status)

        page = int(self.get_argument("page", 1))
        pagesize = self.settings['admin_pagesize']

        oq = Order.select().where(ft)
        total = oq.count()

        orders = []
        for order in oq.paginate(page, pagesize).dicts():
            order['orderitems'] = []

            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order['id']).dicts():

                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])
                except:
                    break

                order['orderitems'].append(orderitem)

            if order['orderitems']:
                orders.append(order)

            else:
                Order.delete().where(Order.id == order['id']).execute()

                try:
                    user = User.get(id=user.id)

                    if user.order > 0:
                        user.order = user.order - 1
                        user.save()
                        self.session['user'] = user
                        self.session.save()
                except:
                    pass

        self.render('user/order.html',
                    orders=orders,
                    total=total,
                    page=page,
                    pagesize=pagesize)
Exemple #13
0
    def post(self):
        
        result = {'status' : False, 'msg' : 0}
        user = self.get_current_user()
        
        if user:
            sid = int(self.get_argument("sid", 0))
            said = int(self.get_argument("said", 0))
            num = int(self.get_argument("num", 1))
            
            #判断商品是否下架
            if sid > 0 and said > 0 and num > 0:
                try:
                    Shop.get(id = sid)
                    ShopAttr.get(id = said)
                    
                    #判断是否有未使用的订单或生成新订单
                    try:
                        try:
                            order = Order.get(uid = user.id, status = 0)
                        except:
                            order = Order()
                            order.uid = user.id
                            order.mobile = user.mobile
                            order.ordered = int(time.time())
                            try:
                                order.save()
                            except Exception, ex:
                                logging.error(ex)
                        
                        try:
                            orderitem = OrderItem.get(oid = order.id, sid = sid, said = said)
                        except:
                            orderitem = OrderItem()

                        orderitem.oid = order.id
                        orderitem.sid = sid
                        orderitem.said = said
                        orderitem.num = orderitem.num + num
                        orderitem.save()
                        
                        result['status'] = True
                        result['msg'] = 200
                        
                    except Exception, ex:
                        logging.error(ex)
                        result['msg'] = 500
                    
                except:
Exemple #14
0
 def get(self):
     user = self.get_current_user()
     status = self.get_argument("status", None)
     
     ft = (Order.uid == user.id)
     
     if status:
         ft = ft & (Order.status == status)
     
     page = int(self.get_argument("page", 1))
     pagesize = self.settings['admin_pagesize']
     
     oq = Order.select().where(ft)
     total = oq.count()
     
     orders = []
     for order in oq.paginate(page, pagesize).dicts():
         order['orderitems'] = []
         
         for orderitem in OrderItem.select().where(OrderItem.oid == order['id']).dicts():
             
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
             except:
                 break
             
             order['orderitems'].append(orderitem)
         
         if order['orderitems']:
             orders.append(order)
             
         else:
             Order.delete().where(Order.id == order['id']).execute()
             
             try:
                 user = User.get(id = user.id)
                 
                 if user.order > 0:
                     user.order = user.order - 1
                     user.save()
                     self.session['user'] = user
                     self.session.save()
             except:
                 pass
             
     
     self.render('user/order.html', orders = orders, total = total, page = page, pagesize = pagesize)
Exemple #15
0
 def get(self):
     orderitems = []
     user = self.current_user
     
     order = None
     
     distributions = self.get_distributions()
     price = 0.0
     credit = 0.0
     
     try:
         order = Order.get(uid = user.id, status = 0)
         
         try:
             mobile = '18014349809'
             sendmsg(self.settings, mobile, '新订单')
         except:
             pass
             
         for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts():
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 _oiprice = orderitem['shop'].price
                 
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
                     if orderitem['shop'].cid == 1:
                         _oicredit = orderitem['shopattr'].price
                         credit = credit + _oicredit * orderitem['num']
                     else:
                         _oiprice = orderitem['shopattr'].price
                 else:
                     _oiprice = float(_oiprice)
                 
                 orderitems.append(orderitem)
                 
                 price = price + _oiprice * orderitem['num']
                 
             except:
                 pass
         order.price = price
         order.save()
         
     except:
         pass
     
     if orderitems:
         self.render("shop/settle.html", tmday = datetime.date.today() + datetime.timedelta(days=1), order  = order, orderitems = orderitems, distributions = distributions.values(), credit = credit)
Exemple #16
0
    def get(self):
        status = self.get_argument("status", None)
        ft = (Order.status >= 0)
        if status:
            ft = ft & (Order.status == status)

        page = int(self.get_argument("page", 1))
        pagesize = self.settings['admin_pagesize']

        oq = Order.select().where(ft)
        total = oq.count()

        orders = []
        for order in oq.paginate(page, pagesize).order_by(
                Order.ordered.desc()).dicts():
            order['orderitems'] = []
            try:
                order['ua'] = UserAddr.get(id=order['uaid'])
            except:
                order['ua'] = UserAddr()

            try:
                order['distr'] = Distribution.get(id=order['distrid'])
            except:
                order['distr'] = Distribution()

            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order['id']).dicts():

                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])

                    order['orderitems'].append(orderitem)
                except:
                    orderitem['shop'] = Shop()

            if order['orderitems']:
                orders.append(order)

        self.render('admin/order.html',
                    orders=orders,
                    total=total,
                    page=page,
                    pagesize=pagesize)
Exemple #17
0
 def get(self):
     orderitems = []
     user = self.current_user
     
     try:
         order = Order.get(uid = user.id, status = 0)
         
         for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts():
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
                 orderitems.append(orderitem)
             except:
                 pass
     except:
         order = Order()
     
     ashops = Shop.select().where((Shop.cid == 2) & (Shop.status != 9))
     self.render("shop/order.html", orderitems = orderitems, order = order, ashops = ashops)
Exemple #18
0
def check_buy_quantity(pid, uid, c, is_cart):
    result = {'flag': 0, 'quantity': 0}
    try:
        begin = time.mktime(
            time.strptime(
                time.strftime("%Y-%m-%d", time.localtime(time.time())),
                "%Y-%m-%d"))
        end = time.mktime(
            time.strptime(
                time.strftime("%Y-%m-%d 23:59:59",
                              time.localtime(time.time())),
                "%Y-%m-%d %H:%M:%S"))
        item = OrderItem.select(
            OrderItem,
            Order).join(Order).where((Order.ordered > begin)
                                     & (Order.ordered < end)
                                     & (Order.status > 0) & (Order.status < 5)
                                     & (Order.user == uid)
                                     & (OrderItem.product == pid)
                                     & (OrderItem.item_type == 0))
        cart = Cart.select().where((Cart.product == pid) & (Cart.user == uid)
                                   & (Cart.type == 0))
        cart_c = 0
        for n in cart:
            cart_c += n.quantity
        p = Product.get(id=pid)
        quantity = 0
        for n in item:
            quantity += n.quantity
        if is_cart == 1:  # 如果等于1 表示是购物车中操作
            count = quantity + c
        else:
            count = quantity + c + cart_c
        if count > p.xgperusernum:
            result['flag'] = 1
            result['quantity'] = p.xgperusernum - quantity
        if p.xgperusernum == 0:
            result['flag'] = 0
        return result
    except Exception, ex:
        return result
Exemple #19
0
 def get(self):
     status = self.get_argument("status", None)
     ft = (Order.status >= 0)
     if status:
         ft = ft & (Order.status == status)
     
     page = int(self.get_argument("page", 1))
     pagesize = self.settings['admin_pagesize']
     
     oq = Order.select().where(ft)
     total = oq.count()
             
     orders = []
     for order in oq.paginate(page, pagesize).order_by(Order.ordered.desc()).dicts():
         order['orderitems'] = []
         try:
             order['ua'] = UserAddr.get(id = order['uaid'])
         except:
             order['ua'] = UserAddr()
         
         try:
             order['distr'] = Distribution.get(id = order['distrid'])
         except:
             order['distr'] = Distribution()
             
         for orderitem in OrderItem.select().where(OrderItem.oid == order['id']).dicts():
             
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
                 
                 order['orderitems'].append(orderitem)
             except:
                 orderitem['shop'] = Shop()
         
         if order['orderitems']:
             orders.append(order)
     
     self.render('admin/order.html', orders = orders, total = total, page = page, pagesize = pagesize)
Exemple #20
0
    def get(self):
        orderitems = []
        user = self.current_user

        order = None

        distributions = self.get_distributions()
        price = 0.0
        credit = 0.0

        try:
            order = Order.get(uid=user.id, status=0)
            print order.id
            '''
            try:
                mobile = '18014349809'
                sendmsg(self.settings, mobile, '新订单')
            except:
                pass
            '''
            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order.id).dicts():
                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    _oiprice = orderitem['shop'].price

                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])
                        if orderitem['shop'].cid == 1:
                            _oicredit = orderitem['shopattr'].price
                            credit = credit + _oicredit * orderitem['num']
                            _oiprice = orderitem['shopattr'].price
                        else:
                            _oiprice = orderitem['shopattr'].price
                    else:
                        _oiprice = float(_oiprice)

                    orderitems.append(orderitem)
                    price = price + float(_oiprice) * orderitem['num']
                except:
                    pass
            print price
            price_pay = str(int(price * 100))
            print 'price_pay:' + price_pay
            openid = user.openid
            print 'wx_pay:' + openid
            jsApi = JsApi_pub()
            unifiedOrder = UnifiedOrder_pub()
            unifiedOrder.setParameter("openid", openid)  #商品描述
            unifiedOrder.setParameter("body", "菜市优品购物")  #商品描述
            timeStamp = time.time()
            print timeStamp
            out_trade_no = "{0}{1}".format(WxPayConf_pub.APPID,
                                           int(timeStamp * 100))
            unifiedOrder.setParameter("out_trade_no", out_trade_no)  #商户订单号
            print 'out_trade_no:' + out_trade_no
            Order.update(wxid=out_trade_no).where(
                Order.id == order.id).execute()
            unifiedOrder.setParameter("total_fee", price_pay)  #总金额
            print WxPayConf_pub.NOTIFY_URL
            unifiedOrder.setParameter("notify_url",
                                      WxPayConf_pub.NOTIFY_URL)  #通知地址
            unifiedOrder.setParameter("trade_type", "JSAPI")  #交易类型

            prepay_id = unifiedOrder.getPrepayId()
            jsApi.setPrepayId(prepay_id)
            jsApiParameters = jsApi.getParameters()
            print jsApiParameters
            appid = json.loads(jsApiParameters).get("appId")
            timestamp = json.loads(jsApiParameters).get("timeStamp")
            noncestr = json.loads(jsApiParameters).get("nonceStr")
            package = json.loads(jsApiParameters).get("package")
            signtype = json.loads(jsApiParameters).get("signType")
            paysign = json.loads(jsApiParameters).get("paySign")
            print appid + timestamp + noncestr + package + signtype + paysign
            if orderitems:
                self.render("/responsive/wxpay.html",
                            tmday=datetime.date.today() +
                            datetime.timedelta(days=1),
                            order=order,
                            orderitems=orderitems,
                            distributions=distributions.values(),
                            credit=credit,
                            appid=appid,
                            timestamp=timestamp,
                            noncestr=noncestr,
                            package=package,
                            signtype=signtype,
                            paysign=paysign)
        except:
            pass
Exemple #21
0
    def get(self):
        alipay = Alipay(**self.settings)

        params = {}
        ks = self.request.arguments.keys()

        for k in ks:
            params[k] = self.get_argument(k)
        msg = ""
        if alipay.notify_verify(params):
            tn = self.get_argument("out_trade_no", None)
            trade_no = self.get_argument("trade_no", None)
            trade_status = self.get_argument("trade_status", None)
            logging.info("return:%s - %s - %s" % (tn, trade_no, trade_status))

            try:
                order = None
                tn1 = tn.split(',')
                for n in tn1:
                    orders = Order.select().where(Order.ordernum == n)
                    if orders.count() > 0:
                        order = orders[0]
                    if order and order.status == 0:
                        order.status = 1
                        order.save()

                        order_Item = ''
                        cartProducts = OrderItem.select().where(
                            OrderItem.order == order)
                        for cartproduct in cartProducts:
                            order_Item += u'名称:' + cartproduct.product.name + u' X ' + str(
                                cartproduct.quantity) + u'份;'
                            if cartproduct.item_type == 5:
                                pr = Product_Reserve.get(
                                    Product_Reserve.product ==
                                    cartproduct.product)
                                old_quantity = pr.quantity
                                pr.quantity += cartproduct.quantity
                                pr.save()
                                if (old_quantity < pr.quantity_stage1) & (
                                        pr.quantity >= pr.quantity_stage1):
                                    return_reserve_balance(
                                        cartproduct.product.id)
                                elif (old_quantity < pr.quantity_stage2) & (
                                        pr.quantity >= pr.quantity_stage2):
                                    return_reserve_balance(
                                        cartproduct.product.id)
                        for n in cartProducts:
                            if n.product.categoryfront.type == '2':
                                sn = 1
                                for s in range(n.quantity):
                                    sn = sn + s
                                    seed = "1234567890"
                                    sa = []
                                    for i in range(12):
                                        sa.append(random.choice(seed))
                                        salt = ''.join(sa)
                                    OrderItemService.create(order_item=n.id,
                                                            sn=sn,
                                                            service_code=salt,
                                                            service_used=0,
                                                            store=order.store,
                                                            user=order.user)
                        try:
                            admins = AdminUser.select().where(AdminUser.roles %
                                                              '%Y%')
                            receivers = [
                                n.email for n in admins if len(n.email) > 0
                            ]
                            email = {
                                u'receiver':
                                receivers,
                                u'subject':
                                u'用户下单成功',
                                u'body':
                                u"支付方式:在线支付;<br/>订单编号为:" + n + u";<br>订单金额:" +
                                str(order.currentprice) + u";<br>订单详情:" +
                                order_Item
                            }
                            create_msg(simplejson.dumps(email), 'email')
                        except Exception, e:
                            print e

                alipay.send_goods_confirm_by_platform(trade_no)
                msg = "success"
                self.redirect("/cart/pay?result=" + msg + "&tn=" + tn +
                              "&price=" + str(order.currentprice) + "&ptype=1")
            except Exception, ex:
                logging.error(ex)
Exemple #22
0
    def post(self):
        alipay = Alipay(**self.settings)

        params = {}
        ks = self.request.arguments.keys()

        for k in ks:
            params[k] = self.get_argument(k)

        if alipay.notify_verify(params):
            tn = self.get_argument("out_trade_no", None)  #订单编号
            trade_no = self.get_argument("trade_no", None)  #支付宝交易号
            trade_status = self.get_argument("trade_status", None)  #交易状态
            logging.info("notify:%s - %s - %s" % (tn, trade_no, trade_status))

            buyer_email = self.get_argument("buyer_email", None)  #买家支付宝帐号
            notify_time = self.get_argument("notify_time", None)  #通知时间
            subject = self.get_argument("subject", None)  #商品名称
            payment_type = self.get_argument("payment_type", None)  #支付类型
            gmt_create = self.get_argument("gmt_create", None)  #交易创建时间
            gmt_payment = self.get_argument("gmt_payment", None)  #交易付款时间
            gmt_close = self.get_argument("gmt_close", None)  #交易关闭时间
            refund_status = self.get_argument("refund_status", None)  #退款状态
            gmt_refund = self.get_argument("gmt_refund", None)  #退款时间
            seller_email = self.get_argument("seller_email", None)  #卖家支付宝账号
            seller_id = self.get_argument("seller_id", None)  #卖家支付宝账户号
            buyer_id = self.get_argument("buyer_id", None)  #买家支付宝账户号
            price = self.get_argument("price", None)  #商品单价
            total_fee = self.get_argument("total_fee", None)  #Number
            quantity = self.get_argument("quantity", None)  #购买数量
            body = self.get_argument("body", None)  #商品描述
            is_total_fee_adjust = self.get_argument("is_total_fee_adjust",
                                                    None)  #是否调整总价
            use_coupon = self.get_argument("use_coupon", None)  #是否使用红包买家
            error_code = self.get_argument("error_code", None)  #错误代码
            bank_seq_no = self.get_argument("bank_seq_no", None)  #网银流水
            out_channel_inst = self.get_argument("out_channel_inst",
                                                 None)  #实际支付渠道

            pay_response = {
                'out_trade_no': tn,
                'trade_no': trade_no,
                'trade_status': trade_status,
                'buyer_email': buyer_email,
                'notify_time': notify_time,
                'subject': subject,
                'payment_type': payment_type,
                'gmt_create': gmt_create,
                'gmt_payment': gmt_payment,
                'gmt_close': gmt_close,
                'refund_status': refund_status,
                'gmt_refund': gmt_refund,
                'seller_email': seller_email,
                'seller_id': seller_id,
                'buyer_id': buyer_id,
                'price': price,
                'total_fee': total_fee,
                'quantity': quantity,
                'body': body,
                'is_total_fee_adjust': is_total_fee_adjust,
                'use_coupon': use_coupon,
                'error_code': error_code,
                'bank_seq_no': bank_seq_no,
                'out_channel_inst': out_channel_inst
            }

            try:
                order = None
                tn = tn.split(',')
                for n in tn:
                    orders = Order.select().where(Order.ordernum == n)
                    if orders.count() > 0:
                        order = orders[0]
                    if order and order.status == 0:
                        order.status = 1
                        order.pay_account = buyer_email
                        order.trade_no = trade_no
                        order.pay_response = simplejson.dumps(pay_response)
                        order.save()

                        order_Item = ''
                        cartProducts = OrderItem.select().where(
                            OrderItem.order == order)
                        for cartproduct in cartProducts:
                            order_Item += u'名称:' + cartproduct.product.name + u' X ' + str(
                                cartproduct.quantity) + u'份;'
                            if cartproduct.item_type == 5:
                                pr = Product_Reserve.get(
                                    Product_Reserve.product ==
                                    cartproduct.product)
                                old_quantity = pr.quantity
                                pr.quantity += cartproduct.quantity
                                pr.save()
                                if (old_quantity < pr.quantity_stage1) & (
                                        pr.quantity >= pr.quantity_stage1):
                                    return_reserve_balance(
                                        cartproduct.product.id)
                                elif (old_quantity < pr.quantity_stage2) & (
                                        pr.quantity >= pr.quantity_stage2):
                                    return_reserve_balance(
                                        cartproduct.product.id)
                        for n in cartProducts:
                            if n.product.categoryfront.type == '2':
                                sn = 1
                                for s in range(n.quantity):
                                    sn = sn + s
                                    seed = "1234567890"
                                    sa = []
                                    for i in range(12):
                                        sa.append(random.choice(seed))
                                        salt = ''.join(sa)
                                    OrderItemService.create(order_item=n.id,
                                                            sn=sn,
                                                            service_code=salt,
                                                            service_used=0,
                                                            store=order.store,
                                                            user=order.user)
                        try:
                            admins = AdminUser.select().where(AdminUser.roles %
                                                              '%Y%')
                            receivers = [
                                n.email for n in admins if len(n.email) > 0
                            ]
                            email = {
                                u'receiver':
                                receivers,
                                u'subject':
                                u'用户下单成功',
                                u'body':
                                u"支付方式:在线支付;<br/>订单编号为:" + n + u";<br>订单金额:" +
                                str(order.currentprice) + u";<br>订单详情:" +
                                order_Item
                            }
                            create_msg(simplejson.dumps(email), 'email')
                        except Exception, e:
                            print e

            except Exception, ex:
                logging.error(ex)

            if trade_status == 'WAIT_SELLER_SEND_GOODS':
                alipay.send_goods_confirm_by_platform(trade_no)

            self.write("success")
Exemple #23
0
 def post(self):
     order = None
     user = self.get_current_user()
     
     try:
         order = Order.get(uid = user.id, status = 0)
         
         mobile = self.get_argument("mobile", user.mobile)
         uaid = self.get_argument("uaid", None)
         distrid = self.get_argument("distrid", None)
         day = self.get_argument("day", datetime.date.today() + datetime.timedelta(days=1))
         hour = int(self.get_argument("hour", 10))
         payment = self.get_argument("payment", 0)
         message = self.get_argument("message", "")
         isinvoice = self.get_argument("isinvoice", 0)
         invoicesub = self.get_argument("invoicesub", 0)
         invoicename = self.get_argument("invoicename", "")
         invoicecontent = self.get_argument("payment", 1)
         shippingprice = self.get_argument("shippingprice", 0.0)
         
         if uaid and distrid:
             try:
                 distrib = Distribution.get(id = distrid)
                 shippingprice = distrib.price
             except:
                 pass
             
             order.mobile = mobile
             order.uaid = uaid
             order.distrid = distrid
             order.distribbed = "%s %d:00:00" % (str(day), hour)
             order.payment = payment
             order.message = message
             
             order.isinvoice = isinvoice
             
             if isinvoice:
                 order.invoicesub = invoicesub
                 order.invoicename = invoicename
                 order.invoicecontent = invoicecontent
             
             order.shippingprice = shippingprice
             
             order.save()
             
             
                 
             body = ""
             for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts():
                     
                 try:
                     shop = Shop.get(id = orderitem['sid'])
                         
                     sname = ""
                     if orderitem['said'] > 0:
                         shopattr = ShopAttr.get(id = orderitem['said'])
                         
                         if shop.cid == 1:
                             credits = shopattr.price * orderitem['num']
                             
                             if credits > user.credit:
                                 OrderItem.delete().where(OrderItem.id == orderitem['id']).execute()
                             else:
                                 user = User.get(id = user.id)
                                 user.credit = user.credit - credits
                                 user.save()
                                 
                                 clog = CreditLog()
                                 clog.uid = user.id
                                 clog.mobile = user.mobile
                                 clog.ctype = 1
                                 clog.affect = int(credits)
                                 clog.log = u"购买" + shop.name
                                 clog.save()
                                 
                                 self.session['user'] = user
                                 self.session.save()
                                 
                         sname = shopattr.name
                         
                     #body = body + shop.name + " " + sname + " " + str(orderitem['num']) + "个\n"
                     body = body + shop.name + " " + sname + " " + str(orderitem['num'])
                 except Exception, ex:
                     logging.error(ex)
             
             tn = "U%d-S%d" % (user.id, order.id)
             
             if int(payment) == 1:
                 self.redirect("/alipay/topay?tn=%s&body=%s&price=%f" % (tn, body, order.price))
             else:
                 self.flash(u"请选择地址和收货方式")
                 self.redirect("/user/orders")
         else:
Exemple #24
0
def notify_verify(post):
    """验证---签名&&数据是否支付宝发送

    """
    #初级验证---签名
    order_params = {}
    params = {}
    _, prestr = fix_params_filter(post)
    mysign = build_mysign(prestr, Settings.KEY, Settings.SIGN_TYPE)
    if mysign != post.get('sign'):
        return False
    tree = etree.fromstring(post.get("notify_data").encode('utf-8'))
    notify_id = tree.find("notify_id").text
    order_params["trade_no"] = tree.find("trade_no").text
    order_params["out_trade_no"] = tree.find("out_trade_no").text
    order_params["trade_status"] = tree.find("trade_status").text
    order_params["total_fee"] = tree.find("total_fee").text
    order_params['buyer_email'] = tree.find("buyer_email").text
    #二级验证---数据是否支付宝发送
    if notify_id:
        params['partner'] = Settings.PARTNER
        params['notify_id'] = notify_id
        if Settings.TRANSPORT == 'https':
            params['service'] = 'notify_verify'
            gateway = 'https://mapi.alipay.com/gateway.do'
        else:
            gateway = 'http://notify.alipay.com/trade/notify_query.do'
        verify_url = "%s?%s" % (gateway, urlencode(params))
        verify_result = urlopen(verify_url).read()

        if verify_result.lower().strip() == 'true':

            tn = tree.find("out_trade_no").text
            try:
                order = None
                tn = tn.split(',')
                for n in tn:
                    orders = Order.select().where(Order.ordernum == n)
                    if orders.count() > 0:
                        order = orders[0]
                    if order and order.status == 0:
                        order.status = 1
                        order.pay_account = tree.find("buyer_email").text
                        order.trade_no = tree.find("trade_no").text
                        order.save()

                        order_Item = ''
                        cartProducts = OrderItem.select().where(
                            OrderItem.order == order)
                        for n in cartProducts:
                            if n.product.categoryfront.type == '2':
                                sn = 1
                                for s in range(n.quantity):
                                    sn = sn + s
                                    seed = "1234567890"
                                    sa = []
                                    for i in range(12):
                                        sa.append(random.choice(seed))
                                        salt = ''.join(sa)
                                    OrderItemService.create(order_item=n.id,
                                                            sn=sn,
                                                            service_code=salt,
                                                            service_used=0,
                                                            store=order.store,
                                                            user=order.user)
                        # try:
                        #     admins = AdminUser.select().where(AdminUser.roles % '%Y%')
                        #     receivers = [n.email for n in admins if len(n.email)>0]
                        #     email = {u'receiver': receivers, u'subject':u'用户下单成功',u'body': u"支付方式:在线支付;<br/>订单编号为:" + n + u";<br>订单金额:"+ str(order.currentprice) + u";<br>订单详情:"+order_Item}
                        #     create_msg(simplejson.dumps(email), 'email')
                        # except Exception, e:
                        #     print e

            except Exception, ex:
                logging.error(ex)

            return order_params
Exemple #25
0
    def post(self):
        order = None
        user = self.get_current_user()

        try:
            order = Order.get(uid=user.id, status=0)

            mobile = self.get_argument("mobile", user.mobile)
            uaid = self.get_argument("uaid", None)
            distrid = self.get_argument("distrid", None)
            day = self.get_argument(
                "day",
                datetime.date.today() + datetime.timedelta(days=1))
            hour = int(self.get_argument("hour", 10))
            payment = self.get_argument("payment", 0)
            message = self.get_argument("message", "")
            isinvoice = self.get_argument("isinvoice", 0)
            invoicesub = self.get_argument("invoicesub", 0)
            invoicename = self.get_argument("invoicename", "")
            invoicecontent = self.get_argument("payment", 1)
            shippingprice = self.get_argument("shippingprice", 0.0)

            if uaid and distrid:
                try:
                    distrib = Distribution.get(id=distrid)
                    shippingprice = distrib.price
                except:
                    pass

                order.mobile = mobile
                order.uaid = uaid
                order.distrid = distrid
                order.distribbed = "%s %d:00:00" % (str(day), hour)
                order.payment = payment
                order.message = message

                order.isinvoice = isinvoice

                if isinvoice:
                    order.invoicesub = invoicesub
                    order.invoicename = invoicename
                    order.invoicecontent = invoicecontent

                order.shippingprice = shippingprice

                order.save()

                body = ""
                for orderitem in OrderItem.select().where(
                        OrderItem.oid == order.id).dicts():

                    try:
                        shop = Shop.get(id=orderitem['sid'])

                        sname = ""
                        if orderitem['said'] > 0:
                            shopattr = ShopAttr.get(id=orderitem['said'])

                            if shop.cid == 1:
                                credits = shopattr.price * orderitem['num']

                                if credits > user.credit:
                                    OrderItem.delete().where(
                                        OrderItem.id ==
                                        orderitem['id']).execute()
                                else:
                                    user = User.get(id=user.id)
                                    user.credit = user.credit - credits
                                    user.save()

                                    clog = CreditLog()
                                    clog.uid = user.id
                                    clog.mobile = user.mobile
                                    clog.ctype = 1
                                    clog.affect = int(credits)
                                    clog.log = u"购买" + shop.name
                                    clog.save()

                                    self.session['user'] = user
                                    self.session.save()

                            sname = shopattr.name

                        body = body + shop.name + " " + sname + " " + str(
                            orderitem['num']) + "个\n"
                    except Exception, ex:
                        logging.error(ex)

                tn = "U%d-S%d" % (user.id, order.id)

                if int(payment) == 1:
                    self.redirect("/alipay/topay?tn=%s&body=%s&price=%f" %
                                  (tn, body, order.price))
                else:
                    self.flash(u"请选择地址和收货方式")
                    self.redirect("/user/orders")
            else:
Exemple #26
0
 def get(self):
     orderitems = []
     user = self.current_user
     
     order = None
     
     distributions = self.get_distributions()
     price = 0.0
     credit = 0.0
     
     try:
         order = Order.get(uid = user.id, status = 0)
         print order.id
         '''
         try:
             mobile = '18014349809'
             sendmsg(self.settings, mobile, '新订单')
         except:
             pass
         '''    
         for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts():
             try:
                 orderitem['shop'] = Shop.get(id = orderitem['sid'])
                 _oiprice = orderitem['shop'].price
                 
                 if orderitem['said'] > 0:
                     orderitem['shopattr'] = ShopAttr.get(id = orderitem['said'])
                     if orderitem['shop'].cid == 1:
                         _oicredit = orderitem['shopattr'].price
                         credit = credit + _oicredit * orderitem['num']
                         _oiprice = orderitem['shopattr'].price
                     else:
                         _oiprice = orderitem['shopattr'].price
                 else:
                     _oiprice = float(_oiprice)
                     
                 orderitems.append(orderitem)
                 price = price + float(_oiprice) * orderitem['num']
             except:
                 pass
         print price
         price_pay = str(int(price*100))
         print 'price_pay:' + price_pay
         openid = user.openid
         print 'wx_pay:'+ openid
         jsApi = JsApi_pub()
         unifiedOrder = UnifiedOrder_pub()
         unifiedOrder.setParameter("openid",openid) #商品描述
         unifiedOrder.setParameter("body","菜市优品购物") #商品描述
         timeStamp = time.time()
         print timeStamp
         out_trade_no = "{0}{1}".format(WxPayConf_pub.APPID, int(timeStamp*100))
         unifiedOrder.setParameter("out_trade_no", out_trade_no) #商户订单号
         print 'out_trade_no:' + out_trade_no
         Order.update(wxid = out_trade_no).where(Order.id == order.id).execute()
         unifiedOrder.setParameter("total_fee", price_pay) #总金额
         print WxPayConf_pub.NOTIFY_URL
         unifiedOrder.setParameter("notify_url", WxPayConf_pub.NOTIFY_URL) #通知地址 
         unifiedOrder.setParameter("trade_type", "JSAPI") #交易类型
         
         prepay_id = unifiedOrder.getPrepayId()
         jsApi.setPrepayId(prepay_id)
         jsApiParameters = jsApi.getParameters()
         print jsApiParameters
         appid = json.loads(jsApiParameters).get("appId")
         timestamp = json.loads(jsApiParameters).get("timeStamp")
         noncestr = json.loads(jsApiParameters).get("nonceStr")
         package = json.loads(jsApiParameters).get("package")
         signtype = json.loads(jsApiParameters).get("signType")
         paysign = json.loads(jsApiParameters).get("paySign")
         print appid + timestamp + noncestr + package + signtype +paysign
         if orderitems:
             self.render("/responsive/wxpay.html", tmday = datetime.date.today() + datetime.timedelta(days=1), order  = order, orderitems = orderitems, distributions = distributions.values(), credit = credit, appid = appid, timestamp = timestamp, noncestr = noncestr, package = package, signtype = signtype, paysign = paysign)
     except:
         pass