3269 lines
143 KiB
PHP
Executable File
3269 lines
143 KiB
PHP
Executable File
<?php
|
||
namespace wstmart\common\model;
|
||
use think\Db;
|
||
use think\Loader;
|
||
use wstmart\common\model\LogSms;
|
||
use wstmart\admin\model\SysConfigs as SCM;
|
||
|
||
/**
|
||
* ============================================================================
|
||
* 订单业务处理类
|
||
*/
|
||
class Orders extends Base{
|
||
/**
|
||
* 快速下单
|
||
*/
|
||
public function quickSubmit($orderSrc = 0, $uId=0){
|
||
$deliverType = 0;
|
||
$isInvoice = ((int)input('post.isInvoice')!=0)?1:0;
|
||
$invoiceClient = ($isInvoice==1)?input('post.invoiceClient'):'';
|
||
$payType = 1;
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
if($userId==0)return WSTReturn('下单失败,请先登录');
|
||
$isUseScore = (int)input('isUseScore');
|
||
$useScore = (int)input('useScore');
|
||
//检测购物车
|
||
$carts = model('common/carts')->getQuickCarts($uId);
|
||
if(empty($carts['carts']))return WSTReturn("请选择要购买的商品");
|
||
//使用积分金额不能超过商品金额
|
||
$tempScoreMoney = WSTScoreToMoney($carts['goodsTotalMoney']-$carts['promotionMoney'],true);
|
||
$useScore = ($useScore>$tempScoreMoney)?$tempScoreMoney:$useScore;
|
||
$orderScoreMap = [];
|
||
$scoreMoney = $this->getOrderScoreMoney($isUseScore,$useScore,$uId);
|
||
//生成订单
|
||
Db::startTrans();
|
||
try{
|
||
//提交订单前执行钩子
|
||
hook('beforeSubmitOrder',['carts'=>$carts,"payType"=>$payType]);
|
||
$shopOrder = current($carts['carts']);
|
||
$goods = $shopOrder['list'][0];
|
||
if($goods['goodsStock']<$goods['cartNum'])return WSTReturn("下单失败,商品库存不足");
|
||
//给用户分配卡券
|
||
$cards = model('GoodsVirtuals')->where(['goodsId'=>$goods['goodsId'],'dataFlag'=>1,'shopId'=>$goods['shopId'],'isUse'=>0])->lock(true)->limit($goods['cartNum'])->select();
|
||
if(count($cards)<$goods['cartNum'])return WSTReturn("下单失败,商品库存不足");
|
||
//修改库存
|
||
Db::name('goods')->where('goodsId',$goods['goodsId'])->update([
|
||
'goodsStock'=>['exp','goodsStock-'.$goods['cartNum']],
|
||
'saleNum'=>['exp','saleNum+'.$goods['cartNum']],
|
||
]);
|
||
$orderunique = WSTOrderQnique();
|
||
$orderNo = WSTOrderNo();
|
||
$orderScore = 0;
|
||
//创建订单
|
||
$order = [];
|
||
$order['orderNo'] = $orderNo;
|
||
$order['orderType'] = 1;
|
||
$order['areaId'] = 0;
|
||
$order['userName'] = '';
|
||
$order['userAddress'] = '';
|
||
$order['userId'] = $userId;
|
||
$order['shopId'] = $shopOrder['shopId'];
|
||
$order['payType'] = $payType;
|
||
$order['goodsMoney'] = $shopOrder['goodsMoney'];
|
||
$order['deliverType'] = $deliverType;
|
||
$order['deliverMoney'] = 0;
|
||
$order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
|
||
$order['scoreMoney'] = 0;
|
||
$order['useScore'] = 0;
|
||
if($scoreMoney['useMoney']>0){
|
||
$order['scoreMoney'] = $scoreMoney['useMoney'];
|
||
$order['useScore'] = $scoreMoney['useScore'];
|
||
}
|
||
$order['realTotalMoney'] = WSTPositiveNum($order['totalMoney'] - $order['scoreMoney'] - $shopOrder['promotionMoney']);
|
||
$order['needPay'] = $order['realTotalMoney'];
|
||
if($order['needPay']>0){
|
||
$order['orderStatus'] = -2;//待付款
|
||
$order['isPay'] = 0;
|
||
}else{
|
||
$order['orderStatus'] = 0;//待发货
|
||
$order['isPay'] = 1;
|
||
}
|
||
//惠宝
|
||
$orderScore = 0;
|
||
//如果开启下单获取惠宝则有惠宝
|
||
if(WSTConf('CONF.isOrderScore')==1){
|
||
$orderScore = $this->round($order['goodsMoney'],0);
|
||
}
|
||
$order['orderScore'] = $orderScore;
|
||
$order['isInvoice'] = $isInvoice;
|
||
if($isInvoice==1){
|
||
$order['invoiceJson'] = model('invoices')->getInviceInfo((int)input('param.invoiceId'));// 发票信息
|
||
$order['invoiceClient'] = $invoiceClient;
|
||
}else{
|
||
$order['invoiceJson'] = '';
|
||
$order['invoiceClient'] = '';
|
||
}
|
||
$order['orderRemarks'] = input('post.remark_'.$shopOrder['shopId']);
|
||
$order['orderunique'] = $orderunique;
|
||
$order['orderSrc'] = $orderSrc;
|
||
$order['dataFlag'] = 1;
|
||
$order['payRand'] = 1;
|
||
$order['createTime'] = date('Y-m-d H:i:s');
|
||
//创建订单前执行钩子
|
||
hook('beforeInsertOrder',['order'=>&$order,'carts'=>$carts]);
|
||
$result = $this->data($order,true)->isUpdate(false)->allowField(true)->save($order);
|
||
if(false !== $result){
|
||
$orderId = $this->orderId;
|
||
//标记虚拟卡券为占用状态
|
||
$goodsCards = [];
|
||
foreach ($cards as $key => $card) {
|
||
$card->isUse = 1;
|
||
$card->orderId = $orderId;
|
||
$card->orderNo = $orderNo;
|
||
$card->save();
|
||
$goodsCards[] = ['cardId'=>$card->id];
|
||
}
|
||
//创建订单商品记录
|
||
$orderGgoods = [];
|
||
$orderGoods['orderId'] = $orderId;
|
||
$orderGoods['goodsId'] = $goods['goodsId'];
|
||
$orderGoods['goodsNum'] = $goods['cartNum'];
|
||
$orderGoods['goodsPrice'] = $goods['shopPrice'];
|
||
$orderGoods['goodsSpecId'] = 0;
|
||
$orderGoods['goodsSpecNames'] = '';
|
||
$orderGoods['goodsName'] = $goods['goodsName'];
|
||
$orderGoods['goodsImg'] = $goods['goodsImg'];
|
||
$orderGoods['commissionRate'] = WSTGoodsCommissionRate($goods['goodsCatId']);
|
||
$orderGoods['goodsCode'] = '';
|
||
$orderGoods['goodsType'] = 1;
|
||
$orderGoods['extraJson'] = json_encode($goodsCards);
|
||
$orderGoods['promotionJson'] = '';
|
||
$orderTotalGoods = [];
|
||
$orderTotalGoods[] = $orderGoods;
|
||
//创建订单商品前执行钩子
|
||
hook('beforeInsertOrderGoods',['orderId'=>$orderId,'orderGoods'=>&$orderTotalGoods,'carts'=>$carts]);
|
||
Db::name('order_goods')->insertAll($orderTotalGoods);
|
||
//计算订单佣金
|
||
$commissionFee = 0;
|
||
if((float)$orderGoods['commissionRate']>0){
|
||
$commissionFee += $this->round($goods['shopPrice']*1*$orderGoods['commissionRate']/100,2);
|
||
}
|
||
$this->where('orderId',$orderId)->update(['commissionFee'=>$commissionFee]);
|
||
//提交订单后执行钩子
|
||
hook('afterSubmitOrder',['orderId'=>$orderId]);
|
||
//创建惠宝流水--如果有抵扣惠宝就肯定是开启了惠宝支付
|
||
if($order['useScore']>0){
|
||
$score = [];
|
||
$score['userId'] = $userId;
|
||
$score['score'] = $order['useScore'];
|
||
$score['dataSrc'] = 1;
|
||
$score['dataId'] = $orderId;
|
||
$score['dataRemarks'] = "交易订单【".$orderNo."】使用惠宝".$order['useScore']."个";
|
||
$score['scoreType'] = 0;
|
||
model('UserScores')->add($score);
|
||
}
|
||
//建立订单记录
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = -2;
|
||
$logOrder['logContent'] = "下单成功,等待用户支付";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//等待支付-给店铺增加提示消息
|
||
$tpl = WSTMsgTemplates('ORDER_SUBMIT');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$orderNo];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $shopOrder['shopId'];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_SUBMIT_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsSubmitOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orderNo]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.submitOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'submit','');
|
||
}
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $orderNo;
|
||
$params['ORDER_TIME'] = date('Y-m-d H:i:s');
|
||
$goodsNames = $goods['goodsName']."*".$goods['cartNum'];
|
||
$params['GOODS'] = $goodsNames;
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = '';
|
||
$params['PAY_TYPE'] = WSTLangPayType($order['payType']);
|
||
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_SUBMIT";
|
||
$msg["shopId"] = $shopOrder['shopId'];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxSubmitOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $orderNo;
|
||
$params['ORDER_TIME'] = date('Y-m-d H:i:s');
|
||
$goodsNames = $goods['goodsName']."*".$goods['cartNum'];
|
||
$params['GOODS'] = $goodsNames;
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = '';
|
||
$params['PAY_TYPE'] = WSTLangPayType($order['payType']);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_SUBMIT','userType'=>3,'userId'=>explode(',',WSTConf('CONF.submitOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
//虚拟商品支付完成-立即发货
|
||
if($order['needPay']==0){
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
$this->handleVirtualGoods($orderId);
|
||
}
|
||
}
|
||
//删除session的购物车商品
|
||
session('TMP_CARTS',null);
|
||
Db::commit();
|
||
return WSTReturn("提交订单成功", 1,$orderunique);
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('提交订单失败',-1);
|
||
}
|
||
}
|
||
/**
|
||
* 正常订单
|
||
*/
|
||
public function submit($orderSrc = 0, $uId=0){
|
||
|
||
|
||
$addressId = (int)input('post.s_addressId');//收货地址ID
|
||
$deliverType = empty(input('post.deliverType')) ? 0 : 1;//0是快递,1是自提,自提的不要运费,先取消 mark 20170907
|
||
$isInvoice = ((int)input('post.isInvoice')!=0)?1:0;//是否开发票
|
||
$invoiceClient = ($isInvoice==1)?input('post.invoiceClient'):'';//发票抬头
|
||
$payType = 1;//((int)input('post.payType')!=0)?1:0;//1是在线支付0是货到付款
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$isUseScore = 0;//(int)input('isUseScore');//是否使用惠宝支付
|
||
$useScore = 0;//input('useScore');//惠宝抵扣金额
|
||
|
||
//dump($useScore);die;
|
||
if($userId==0)return WSTReturn('下单失败,请先登录',-999);//增加-999,需要登录 mark hsf 20171222
|
||
//检测购物车
|
||
//$carts = model('common/carts')->getCarts(true, $userId);
|
||
//if(empty($carts['carts']))return WSTReturn("请选择要购买的商品");
|
||
//检测地址是否有效
|
||
$address = Db::name('user_address')->where(['userId'=>$userId,'addressId'=>$addressId,'dataFlag'=>1])->find();
|
||
if(empty($address)){
|
||
return WSTReturn("无效的用户地址");
|
||
}
|
||
$areaIds = [];
|
||
$areaMaps = [];
|
||
$tmp = explode('_',$address['areaIdPath']);//区域id路径 省Id_市Id_县Id 例如:440000_440100_440106_
|
||
$address['areaId2'] = $tmp[1];//记录配送城市
|
||
|
||
|
||
/**
|
||
* 添加直接提交订单和购物机结算2种方式 mark hsf 20171222
|
||
*
|
||
*/
|
||
$type = (int)input('post.type');//是否是立即下单
|
||
if($type==0){//购物车结算
|
||
//检测购物车
|
||
$carts = model('common/carts')->getCarts(true, $userId);
|
||
}else{//立即下单的
|
||
$carts = model('carts')->buyNow($address['areaId2'], $userId);//立即下单结算方式
|
||
}
|
||
if(empty($carts['carts']))return WSTReturn("请选择要购买的商品");
|
||
$carts['ect_pay'] = isset($carts['ect_pay']) ? (int)$carts['ect_pay'] : 0;
|
||
$carts['goodsType'] = isset($carts['goodsType']) ? $carts['goodsType'] : 1;
|
||
if(1 == $carts['ect_pay'] || (isset($carts['is_seckilling']) && $carts['is_seckilling'] == 1) || (isset($carts['promotion_goods']) && $carts['promotion_goods'] == 1)){//不可抵用惠宝
|
||
$isUseScore=0;
|
||
$useScore=0;
|
||
}
|
||
$from = (int)input('post.from');
|
||
if(3 == $from){
|
||
$carts['goodsType'] = $from;
|
||
$helpUserId = (int)input('post.helpUserId');//助购用户ID
|
||
$helpLevel = (int)input('post.helpLevel');//助购用户ID
|
||
if($helpUserId<=0){
|
||
return WSTReturn("请选择助购用户");
|
||
}
|
||
if($helpUserId == $userId && $userId!=1){$helpLevel=0;}
|
||
}
|
||
$pay_code = input('payCode');
|
||
//$carts['ect_pay']=0;
|
||
// if($carts['ect_pay'] == 1 && $pay_code !='ect'){
|
||
// return WSTReturn("ECT专区产品,请在APP里选择ECT支付!");
|
||
// }
|
||
// if(!$carts['ect_pay'] && input('payCode') =='ect'){
|
||
// //return WSTReturn("ECT支付调试中,请耐心等待!");
|
||
// //return WSTReturn("该商品不支持ECT支付!");
|
||
// }
|
||
|
||
/*****************end******************/
|
||
// if(!$carts['ect_pay'] && input('payCode') =='ect'){
|
||
// return WSTReturn("该商品不支持ECT支付!");
|
||
// }
|
||
// if(time() < 1539532800 && input('payCode') =='ect'){
|
||
// return WSTReturn("ECT支付调试中,15号可用");
|
||
// }
|
||
|
||
if(isset($carts['is_seckilling']) && $carts['is_seckilling'] == 1){
|
||
$s_m = new \addons\hyhsale\model\Hyhsale();
|
||
$s_m->batchUpdateSaleGoods($carts);
|
||
}
|
||
|
||
// 验证商品规格是否已选
|
||
foreach ($carts['carts'] as $v) {
|
||
foreach ($v['list'] as $val) {
|
||
// 坑啊判断下会死嘛 ---- 20200116
|
||
if($val['isSpec']!=1)continue;
|
||
$id = Db::name('goods_specs')->where(['shopId'=>$val['shopId'],'goodsId'=>$val['goodsId']])->column('id');
|
||
if($id && $val['goodsSpecId'] == ''){
|
||
return WSTReturn("请选择商品规格型号!");
|
||
}
|
||
}
|
||
}
|
||
|
||
foreach ($tmp as $vv){
|
||
if($vv=='')continue;
|
||
if(!in_array($vv,$areaIds))$areaIds[] = $vv;
|
||
}
|
||
if(!empty($areaIds)){
|
||
$areas = Db::name('areas')->where(['dataFlag'=>1,'areaId'=>['in',$areaIds]])->field('areaId,areaName')->select();
|
||
foreach ($areas as $v){
|
||
$areaMaps[$v['areaId']] = $v['areaName'];//areaMaps键名是城市id,键名是中文名,如 [21] => "青海省" [278] =>"海东市"[2310] => "化隆"
|
||
}
|
||
$tmp = explode('_',$address['areaIdPath']);
|
||
$areaNames = [];
|
||
foreach ($tmp as $vv){
|
||
if($vv=='')continue;//440000_440100_440106_按_截取的话最后一个是空
|
||
$areaNames[] = $areaMaps[$vv];//返回省市区的数组
|
||
$address['areaName'] = implode('',$areaNames);//拼接成省市区字符串
|
||
}
|
||
}
|
||
|
||
$address['userAddress'] = $address['areaName'].$address['userAddress'];//拼接省市区+具体地址
|
||
WSTUnset($address, 'isDefault,dataFlag,createTime,userId');//去除多余字段
|
||
//放钩子计算11.11订单的分类商品使用优惠券后的金额
|
||
//hook("orderCatsCouponEleven",['carts'=>&$carts,'isSettlement'=>true,'uId'=>$userId]);
|
||
|
||
$maxScoreMoney = 0;//初始化最大可用惠宝数 mark hsf 20171117
|
||
$total_promotion_money = 0;//初始化合计优惠 mark hsf 20170303
|
||
foreach ($carts['carts'] as &$v){
|
||
$total_promotion_money += $v['promotionMoney'];//合计优惠 mark hsf 20170303
|
||
}
|
||
unset($v);
|
||
$carts['couponMoney'] = isset($carts['couponMoney']) ? $carts['couponMoney'] : 0;
|
||
$maxScoreMoney = ($carts['goodsTotalMoney']-$carts['allShippingMoney']-$total_promotion_money-$carts['couponMoney']) * HuiScale();//减去优惠过的
|
||
$maxScoreMoney = $maxScoreMoney < 0 ? 0 : $maxScoreMoney;
|
||
$useScore = $useScore < $maxScoreMoney ? $useScore : $maxScoreMoney;
|
||
|
||
//计算出每个订单应该分配的金额和惠宝
|
||
$orderScoreMoney = $this->allocScoreMoney($carts,$isUseScore,$useScore, $uId);
|
||
|
||
//加权分配价格
|
||
$orderPromotioneMap = $this->allocPromotioneMoney($carts, $uId);
|
||
//生成订单
|
||
Db::startTrans();
|
||
try{
|
||
|
||
//提交订单前执行钩子
|
||
hook('beforeSubmitOrder',['carts'=>$carts,"payType"=>$payType]);
|
||
$orderunique = WSTOrderQnique();
|
||
foreach ($carts['carts'] as $ckey =>$shopOrder){
|
||
$orderNo = WSTOrderNo();
|
||
$orderScore = 0;
|
||
//创建订单
|
||
$order = [];
|
||
$order = array_merge($order,$address);
|
||
$order['orderNo'] = $orderNo;
|
||
$order['userId'] = $userId;
|
||
$order['shopId'] = $shopOrder['shopId'];
|
||
$order['payType'] = $payType;
|
||
$order['goodsType'] = $carts['goodsType'];
|
||
$order['goodsMoney'] = $shopOrder['goodsMoney'];
|
||
//计算运费和总金额
|
||
$order['deliverType'] = $deliverType;
|
||
$order['deliverMoney']=0;
|
||
$order['helpUserId']=isset($helpUserId)?$helpUserId:0;//助购用户,只有助购的时候有
|
||
$order['helpUserLevel']=isset($helpLevel)?$helpLevel:0;//助购用户,只有助购的时候有
|
||
if($shopOrder['isFreeShipping']){
|
||
$order['deliverMoney'] = 0;
|
||
}else{
|
||
//$order['deliverMoney'] = ($deliverType==1)?0:WSTOrderFreight($shopOrder['shopId'],$order['areaId2']);
|
||
if($deliverType!=1){
|
||
foreach ($shopOrder['list'] as &$value) {
|
||
$order['deliverMoney'] += $value['freight'];
|
||
}
|
||
}
|
||
|
||
}
|
||
$order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
|
||
//惠宝支付-计算分配惠宝和金额
|
||
$shopOrderMoney = $orderScoreMoney[$shopOrder['shopId']];
|
||
$order['scoreMoney'] = $shopOrderMoney['useMoney'];
|
||
$order['useScore'] = $shopOrderMoney['useScore'];
|
||
|
||
if(isset($orderPromotioneMap[$shopOrder['shopId']]['promotioneMoney'])){
|
||
$shopPromotionMoney = $orderPromotioneMap[$shopOrder['shopId']]['promotioneMoney'];
|
||
}else{
|
||
$shopPromotionMoney = 0;
|
||
}
|
||
//实付金额要减去惠宝兑换的金额和店铺总优惠
|
||
$order['realTotalMoney'] = WSTPositiveNum($order['totalMoney'] - $order['scoreMoney'] - $shopOrder['promotionMoney'] - $shopPromotionMoney );
|
||
$pay_ratio = 1;
|
||
if($pay_code == 'ect'){
|
||
$pay_ratio_value = Db::name('payments')->where(['payCode'=>'ect'])->value('payRatio');
|
||
if($pay_ratio_value < 0.9 || $pay_ratio_value > 1){
|
||
$pay_ratio = 1;
|
||
}else{
|
||
$pay_ratio = $pay_ratio_value;
|
||
}
|
||
}
|
||
$order['realTotalMoney'] *= $pay_ratio;//支付折扣价
|
||
$order['needPay'] = $order['realTotalMoney'];
|
||
if($payType==1){
|
||
if($order['needPay']>0){
|
||
$order['orderStatus'] = -2;//待付款
|
||
$order['isPay'] = 0;
|
||
}else{
|
||
$order['orderStatus'] = 0;//待发货
|
||
$order['isPay'] = 1;
|
||
}
|
||
}else{
|
||
$order['orderStatus'] = 0;//待发货
|
||
if($order['needPay']==0)$order['isPay'] = 1;
|
||
}
|
||
//惠宝
|
||
$orderScore = 0;
|
||
//如果开启下单获取惠宝则有惠宝
|
||
if(WSTConf('CONF.isOrderScore')==1){
|
||
$orderScore = WSTMoneyGiftScore($order['realTotalMoney']);//惠宝按成交价的20%算 mark hsf 20180308
|
||
}
|
||
$order['orderScore'] = $orderScore;
|
||
$order['isInvoice'] = $isInvoice;
|
||
if($isInvoice==1){
|
||
$order['invoiceJson'] = model('invoices')->getInviceInfo((int)input('param.invoiceId'));// 发票信息
|
||
$order['invoiceClient'] = $invoiceClient;
|
||
}else{
|
||
$order['invoiceJson'] = '';// 发票信息
|
||
$order['invoiceClient'] = '';
|
||
}
|
||
$order['orderRemarks'] = input('post.remark_'.$shopOrder['shopId']);
|
||
$order['orderunique'] = $orderunique;
|
||
$order['orderSrc'] = $orderSrc;
|
||
$order['dataFlag'] = 1;
|
||
$order['payRand'] = 1;
|
||
$order['pay_name']=$carts['ect_pay'];
|
||
$order['createTime'] = date('Y-m-d H:i:s');
|
||
$commissionRate = Db::name('shop_commission')->where('shopId',$order['shopId'])->field('commission')->find();
|
||
//计算订单总佣金
|
||
if((float)$commissionRate>0){
|
||
$order['commissionFee'] = $this->round(($order['realTotalMoney']-$order['deliverMoney'])*$commissionRate['commission']/100,2);
|
||
}else{
|
||
$order['commissionFee'] = 0;
|
||
//$order['commissionFee'] = $this->round(($order['realTotalMoney']-$order['deliverMoney'])*0.06,2);
|
||
}
|
||
$order['commissionFee'] = $order['commissionFee'] < 0?0:$order['commissionFee'];
|
||
if(isset($carts['is_seckilling']) && $carts['is_seckilling'] == 1){
|
||
|
||
}else{
|
||
//创建订单前执行钩子
|
||
hook('beforeInsertOrder',['order'=>&$order,'carts'=>$carts]);//优惠券和满就送钩子,秒杀先关
|
||
}
|
||
|
||
$result = $this->data($order,true)->isUpdate(false)->allowField(true)->save($order);
|
||
if(false !== $result){
|
||
$orderId = $this->orderId;
|
||
$orderTotalGoods = [];
|
||
//$commissionFee = 0;
|
||
foreach ($shopOrder['list'] as $gkey =>$goods){
|
||
//创建订单商品记录
|
||
$orderGgoods = [];
|
||
$orderGoods['orderId'] = $orderId;
|
||
$orderGoods['goodsId'] = $goods['goodsId'];
|
||
$orderGoods['goodsNum'] = $goods['cartNum'];
|
||
$orderGoods['goodsPrice'] = $goods['shopPrice'];
|
||
$orderGoods['goodsSpecId'] = $goods['goodsSpecId'];
|
||
$orderGoods['discountRate'] = Db::name('goods')->where(['goodsId'=>$goods['goodsId']])->value('discountRate');
|
||
|
||
if(!empty($goods['specNames'])){
|
||
$specNams = [];
|
||
foreach ($goods['specNames'] as $pkey =>$spec){
|
||
$specNams[] = $spec['catName'].':'.$spec['itemName'];
|
||
}
|
||
$orderGoods['goodsSpecNames'] = implode('@@_@@',$specNams);
|
||
}else{
|
||
$orderGoods['goodsSpecNames'] = '';
|
||
}
|
||
$orderGoods['goodsName'] = $goods['goodsName'];
|
||
$orderGoods['goodsImg'] = $goods['goodsImg'];
|
||
$orderGoods['freight'] = $goods['freight'];
|
||
/*
|
||
根据是否批发算佣金 mark 20171117
|
||
*/
|
||
if(empty($goods['isWhsle'])){
|
||
$isWhsle = 0;
|
||
}else{
|
||
$isWhsle = 1;
|
||
}
|
||
$orderGoods['commissionRate'] = WSTGoodsCommissionRate($goods['goodsCatId'],$isWhsle);
|
||
/*
|
||
-------------end-------------
|
||
*/
|
||
$orderGoods['goodsCode'] = '';
|
||
$orderGoods['goodsType'] = 0;
|
||
$orderGoods['extraJson'] = '';
|
||
$orderGoods['promotionJson'] = '';
|
||
$orderTotalGoods[] = $orderGoods;
|
||
//计算订单总佣金
|
||
// if((float)$orderGoods['commissionRate']>0){
|
||
// $commissionFee += $this->round($orderGoods['goodsPrice']*$orderGoods['goodsNum']*$orderGoods['commissionRate']/100,2);
|
||
// }
|
||
//修改库存
|
||
if($goods['goodsSpecId']>0){
|
||
Db::name('goods_specs')->where('id',$goods['goodsSpecId'])->update([
|
||
'specStock'=>['exp','specStock-'.$goods['cartNum']],
|
||
'saleNum'=>['exp','saleNum+'.$goods['cartNum']]
|
||
]);
|
||
}
|
||
Db::name('goods')->where('goodsId',$goods['goodsId'])->update([
|
||
'goodsStock'=>['exp','goodsStock-'.$goods['cartNum']],
|
||
'saleNum'=>['exp','saleNum+'.$goods['cartNum']],
|
||
]);
|
||
}
|
||
if(isset($carts['is_seckilling']) && $carts['is_seckilling'] == 1){
|
||
|
||
}else{
|
||
//创建订单商品前执行钩子
|
||
hook('beforeInsertOrderGoods',['orderId'=>$orderId,'orderGoods'=>&$orderTotalGoods,'carts'=>$carts]);
|
||
}
|
||
Db::name('order_goods')->insertAll($orderTotalGoods);
|
||
//更新订单佣金
|
||
//$this->where('orderId',$orderId)->update(['commissionFee'=>$commissionFee]);
|
||
//提交订单后执行钩子
|
||
hook('afterSubmitOrder',['orderId'=>$orderId]);
|
||
|
||
//创建惠宝流水--如果有抵扣惠宝就肯定是开启了惠宝支付
|
||
if($order['useScore']>0){
|
||
$score = [];
|
||
$score['userId'] = $userId;
|
||
$score['score'] = $order['useScore'];
|
||
$score['dataSrc'] = 1;
|
||
$score['dataId'] = $orderId;
|
||
$score['dataRemarks'] = "交易订单【".$orderNo."】使用惠宝".$order['useScore']."个";
|
||
$score['scoreType'] = 0;
|
||
model('UserScores')->add($score);
|
||
}
|
||
|
||
//建立订单记录
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = ($payType==1 && $order['needPay']==0)?-2:$order['orderStatus'];
|
||
$logOrder['logContent'] = ($payType==1)?"下单成功,等待用户支付":"下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
if($payType==1 && $order['needPay']==0){
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
}
|
||
//给店铺增加提示消息
|
||
$tpl = WSTMsgTemplates('ORDER_SUBMIT');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$orderNo];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $shopOrder['shopId'];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
}
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_SUBMIT_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsSubmitOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orderNo]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.submitOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'submit','');
|
||
}
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $orderNo;
|
||
$params['ORDER_TIME'] = date('Y-m-d H:i:s');
|
||
$goodsNames = [];
|
||
foreach ($shopOrder['list'] as $gkey =>$goods){
|
||
$goodsNames[] = $goods['goodsName']."*".$goods['cartNum'];
|
||
}
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
|
||
$params['PAY_TYPE'] = WSTLangPayType($order['payType']);
|
||
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_SUBMIT";
|
||
$msg["shopId"] = $shopOrder['shopId'];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxSubmitOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $orderNo;
|
||
$params['ORDER_TIME'] = date('Y-m-d H:i:s');
|
||
$goodsNames = [];
|
||
foreach ($shopOrder['list'] as $gkey =>$goods){
|
||
$goodsNames[] = $goods['goodsName']."*".$goods['cartNum'];
|
||
}
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
|
||
$params['PAY_TYPE'] = WSTLangPayType($order['payType']);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_SUBMIT','userType'=>3,'userId'=>explode(',',WSTConf('CONF.submitOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
/**
|
||
* 修改用户优惠券状态
|
||
*/
|
||
if(isset($carts['recordId']) && $carts['recordId']){
|
||
$now = time();
|
||
Db::name('coupon_record')->where(['id'=>$carts['recordId'],'userId'=>$userId])->update(['isUse'=>1,'useTime'=>$now]);
|
||
}
|
||
/**
|
||
* 添加直接提交订单和购物机结算2种方式 mark hsf 20171222
|
||
*
|
||
*/
|
||
if($type==0){//购物车结算
|
||
//删除已选的购物车商品
|
||
Db::name('carts')->where(['userId'=>$userId,'isCheck'=>1])->delete();
|
||
}else{
|
||
//删除session的购物车商品
|
||
session('HYH_CARTS',null);
|
||
}
|
||
/*****************end******************/
|
||
Db::commit();
|
||
return WSTReturn("提交订单成功", 1,$orderunique);
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
// dump($e);
|
||
return WSTReturn($e->getMessage(),-1);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* [allocPromotioneMoney 计算订单活动金额]
|
||
* @param [type] $carts [购物车商品]
|
||
* @param [type] $isUseScore [是否用惠宝]
|
||
* @param [type] $useScore [使用惠宝数量]
|
||
* @param integer $uId [会员ID]
|
||
* @return [type] [返回惠宝抵用金额和抵用惠宝]
|
||
*/
|
||
public function allocPromotioneMoney($carts, $uId=0){
|
||
$orderPromotioneMap=[];
|
||
//计算优惠出来的信息
|
||
if($carts['promotionMoney']>0){
|
||
foreach ($carts['carts'] as $ckey =>$shopOrder){
|
||
|
||
//$orderPromotioneMap[$shopOrder['shopId']]['promotioneMoney'] = 0;
|
||
$orderPromotioneMap[$shopOrder['shopId']]['promotioneMoney'] = $this->round($carts['promotionMoney']*$shopOrder['goodsMoney']/($carts['goodsTotalMoney']),2);
|
||
// foreach($shopOrder as $value){
|
||
|
||
// // if(in_array($value['goodsId'],$coupon_info['ids'])){
|
||
// // $coupon_val['sum_money'] += $value['cartNum']*$value['shopPrice'];//商品
|
||
// // //50*150/(150+260)
|
||
|
||
// // }
|
||
// }
|
||
}
|
||
}
|
||
return $orderPromotioneMap;
|
||
}
|
||
/**
|
||
* [allocScoreMoney 计算订单可用惠宝和金额【惠宝支付使用】]
|
||
* @param [type] $carts [购物车商品]
|
||
* @param [type] $isUseScore [是否用惠宝]
|
||
* @param [type] $useScore [使用惠宝数量]
|
||
* @param integer $uId [会员ID]
|
||
* @return [type] [返回惠宝抵用金额和抵用惠宝]
|
||
*/
|
||
public function allocScoreMoney($carts,$isUseScore,$useScore, $uId=0){
|
||
//使用惠宝金额不能超过商品金额
|
||
//$tempScoreMoney = WSTScoreToMoney($carts['goodsTotalMoney']-$carts['promotionMoney'],true);//返回最大惠宝兑金额数量,传参实际金额即总价减去店铺要优惠的金额
|
||
/*
|
||
* 计算最大可用惠宝,添加验证批发价的惠宝可抵用 mark hsf 20171117
|
||
*/
|
||
$tempScoreMoney = 0;
|
||
foreach ($carts['carts'] as &$v){
|
||
foreach ($v['list'] as &$val) {
|
||
if(isset($val['isWhsle'])){//是批发价的
|
||
$tempScoreMoney += $this->round($val['shopPrice'] * $val['cartNum'] * HuiWhsleScale(),2);//可用惠宝默认抵10%
|
||
}else{
|
||
$tempScoreMoney += $this->round($val['shopPrice'] * $val['cartNum'] * HuiScale(),2);
|
||
}
|
||
}
|
||
}
|
||
/*
|
||
*----------end-------------
|
||
*/
|
||
$useScore = ($useScore>$tempScoreMoney)?$tempScoreMoney:$useScore;//
|
||
$orderScoreMap = [];
|
||
$scoreMoney = $this->getOrderScoreMoney($isUseScore, $useScore, $uId);//计算可用惠宝和抵扣金额 ['useScore'=>使用的惠宝,'useMoney'=>转换后的金额,因为不一定是1:1换算的];
|
||
$allocOrderMoney = $scoreMoney['useMoney'];//惠宝换算的金额
|
||
$allocOrderScore = $scoreMoney['useScore'];//使用的惠宝数量
|
||
$isLastOrder = false; //用来判断是否到最后一个订单
|
||
$totalShop = count($carts['carts']);//获取购物车产品有几个商家
|
||
$shopNum = 0;
|
||
foreach ($carts['carts'] as $ckey =>$shopOrder){
|
||
$orderScoreMap[$shopOrder['shopId']]['useMoney'] = 0;
|
||
$orderScoreMap[$shopOrder['shopId']]['useScore'] = 0;
|
||
$shopNum++;
|
||
if($scoreMoney['useMoney']>0){//使用惠宝
|
||
if($shopNum==$totalShop){//最后一个商家
|
||
$allocMoney = $allocOrderMoney;//余下的金额
|
||
$allocScore = $allocOrderScore;//余下的惠宝
|
||
}else{
|
||
$allocMoney = $this->allocOrderMoney($scoreMoney['useMoney'],$carts['goodsTotalMoney'],$shopOrder['goodsMoney']);//惠宝抵用金额*商品金额/订单总金额(不算运费)
|
||
$allocTmpMoney = $allocOrderMoney - $allocMoney;//惠宝抵用金额-店铺分配的金额,得到真实的金额
|
||
//有可能计算出来金额比实际上还要大,所以要修正一下.
|
||
if($allocTmpMoney<0){//真实的金额<0,是有误差
|
||
$allocMoney = $allocOrderMoney;//分配金额=惠宝抵用金额
|
||
}else{
|
||
$allocOrderMoney = $allocTmpMoney;//余下的金额
|
||
}
|
||
|
||
$allocScore = WSTScoreToMoney($allocMoney,true);//惠宝转换金额
|
||
$allocTmpScore = $allocOrderScore - $allocScore;//使用的惠宝数量-惠宝转换金额
|
||
//有可能计算出来金额比实际上还要大,修正分数
|
||
|
||
if($allocTmpScore<0){
|
||
$allocScore = $allocOrderScore;//使用的惠宝数量
|
||
}else{
|
||
$allocOrderScore = $allocTmpScore;//余下的惠宝
|
||
}
|
||
//echo $allocOrderScore.'qqq';
|
||
}
|
||
$orderScoreMap[$shopOrder['shopId']]['useMoney'] = $allocMoney;
|
||
$orderScoreMap[$shopOrder['shopId']]['useScore'] = $allocScore;
|
||
}
|
||
}
|
||
return $orderScoreMap;
|
||
}
|
||
|
||
/**
|
||
* 分配金额和惠宝
|
||
*/
|
||
public function allocOrderMoney($useMoney,$totalOrderMoney,$orderMoney){
|
||
if($useMoney>$totalOrderMoney)$useMoney = $totalOrderMoney;
|
||
return $this->round(($useMoney*$orderMoney)/$totalOrderMoney,2);
|
||
}
|
||
|
||
/**
|
||
* 计算可用惠宝和抵扣金额
|
||
*/
|
||
public function getOrderScoreMoney($isUseScore, $useScore, $uId=0){
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
if((int)WSTConf('CONF.isOpenScorePay')==1 && $isUseScore){
|
||
$uses = model('common/users')->getFieldsById($userId,'userScore');
|
||
//如果又要惠宝支付又传个0或者负数就默认为0...
|
||
if($useScore<=0)$useScore = 0;
|
||
if($uses['userScore']<$useScore)$useScore = $uses['userScore'];
|
||
$money = WSTScoreToMoney($useScore);
|
||
return ['useScore'=>$useScore,'useMoney'=>$money];
|
||
}
|
||
return ['useScore'=>0,'useMoney'=>0];
|
||
}
|
||
|
||
/**
|
||
* 根据订单唯一流水获取订单信息
|
||
*/
|
||
public function getByUnique($uId=0){
|
||
$orderNo = input('orderNo');
|
||
$isBatch = (int)input('isBatch/d',1);
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
if($isBatch==1){
|
||
$rs = $this->where(['userId'=>$userId,'orderunique'=>$orderNo])->field('orderId,orderNo,payType,needPay,orderunique,deliverMoney,userName,userPhone,userAddress')->select();
|
||
}else{
|
||
$rs = $this->where(['userId'=>$userId,'orderNo'=>$orderNo])->field('orderId,orderNo,payType,needPay,orderunique,deliverMoney,userName,userPhone,userAddress')->select();
|
||
}
|
||
|
||
$data = [];
|
||
$data['orderunique'] = $orderNo;
|
||
$data['list'] = [];
|
||
$payType = 0;
|
||
$totalMoney = 0;
|
||
$orderIds = [0];
|
||
foreach ($rs as $key =>$v){
|
||
if($v['payType']==1)$payType = 1;
|
||
$totalMoney = $totalMoney + $v['needPay'];
|
||
$orderIds[] = $v['orderId'];
|
||
$data['list'][] = $v;
|
||
}
|
||
$data['totalMoney'] = $totalMoney;
|
||
$data['payType'] = $payType;
|
||
//获取商品信息
|
||
$goods = Db::name('order_goods')->where(['orderId'=>['in',$orderIds]])->select();
|
||
foreach ($goods as $key =>$v){
|
||
if($v['goodsSpecNames']!=''){
|
||
$v['goodsSpecNames'] = explode('@@_@@',$v['goodsSpecNames']);
|
||
}else{
|
||
$v['goodsSpecNames'] = [];
|
||
}
|
||
$data['goods'][$v['orderId']][] = $v;
|
||
}
|
||
//如果是在线支付的话就要加载支付信息
|
||
if($data['payType']==1){
|
||
//获取支付信息
|
||
$payments = model('payments')->where(['isOnline'=>1,'enabled'=>1])->order('payOrder asc')->select();
|
||
$data['payments'] = $payments;
|
||
}
|
||
return $data;
|
||
}
|
||
/**
|
||
* 本看凭证
|
||
* @param [type] $isShop [1是商家]
|
||
* @return [type] [description]
|
||
*/
|
||
public function viewCertificate($isShop=0,$uId=0){
|
||
$orderId = (int)input('post.orderId');
|
||
if(1 == $isShop){
|
||
$shopId = session('WST_USER.shopId');
|
||
$order = $this->where(['orderId'=>$orderId,'shopId'=>$shopId,'dataFlag'=>1])->field('orderId')->find();
|
||
}else{
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->where(['orderId'=>$orderId,'userId'=>$userId,'dataFlag'=>1])->field('orderId')->find();
|
||
}
|
||
if(!$order) return WSTReturn('订单不存在',-1);
|
||
$rs = Db::name('order_certificate')->where(['orderId'=>$orderId])->order('id DESC')->find();
|
||
if($rs){
|
||
$rs['createTime'] = date('Y-m-d H:i:s',$rs['createTime']);
|
||
} //return WSTReturn('未找到相关数据',-1);
|
||
return WSTReturn('',1,$rs);
|
||
}
|
||
/**
|
||
* 上传凭证
|
||
* @return [type] [description]
|
||
*/
|
||
public function uploadCertificate($isShop=0,$uId=0){
|
||
$orderId = (int)input('post.orderId');
|
||
if( $orderId){
|
||
$content = input('post.content');
|
||
if(!$content) return WSTReturn('请填写凭证说明',-1);
|
||
$imgUrl = input('post.imgUrl');
|
||
if(!$imgUrl) return WSTReturn('请上传凭证照片',-1);
|
||
|
||
if(1 == $isShop){
|
||
$shopId = session('WST_USER.shopId');
|
||
$order = $this->where(['orderId'=>$orderId,'shopId'=>$shopId,'dataFlag'=>1])->field('orderId')->find();
|
||
}else{
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->where(['orderId'=>$orderId,'userId'=>$userId,'orderStatus'=>0,'dataFlag'=>1])->field('orderId')->find();
|
||
}
|
||
if(!$order) return WSTReturn('订单不存在',-1);
|
||
$createTime = time();
|
||
if(false !== Db::name('order_certificate')->insert(compact('isShop','orderId','content','imgUrl','createTime'))){
|
||
if(1 == $isShop){
|
||
return WSTReturn('上传凭证成功',1);
|
||
}else{
|
||
return WSTReturn('上传凭证成功,请等待商家确认',1);
|
||
}
|
||
}
|
||
}
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
//检查商家是否有凭证未上传
|
||
public function checkCertificate($userId){
|
||
$m = Model('common/Table');
|
||
$m->setTable('order_shop_certificate');
|
||
//已拒绝的凭证
|
||
$certificateInfo = $m->getInfo(['userId'=>$userId,'status'=>4],'id,shopId');
|
||
if($certificateInfo){
|
||
return WSTReturn('您上传的凭证已拒绝,请重新提交!',-666,$certificateInfo);
|
||
}
|
||
$m->setTable('shops');
|
||
$shopIds = $m->getColumn(['userId'=>$userId,'dataFlag'=>1],'shopId');
|
||
if($shopIds){
|
||
//未提交的凭证
|
||
$m->setTable('orders');
|
||
if(count($shopIds)>1){
|
||
$where['shopId']=['IN',$shopIds];
|
||
}else{
|
||
$where['shopId']=$shopIds[0];
|
||
}
|
||
$certificateInfo = $m->getInfo(array_merge($where,['orderStatus'=>2,'certificateStatus'=>0]),'orderId,shopId,receiveTime');
|
||
|
||
$start_date = date('Y-m-d',strtotime($certificateInfo['receiveTime']));
|
||
$end_date = date('Y-m-d');
|
||
$datetime_start = new \DateTime($start_date);
|
||
$datetime_end = new \DateTime($end_date);
|
||
$days = $datetime_start->diff($datetime_end)->days;
|
||
if($certificateInfo && (date('H') >= 21 || $days > 0)) {
|
||
return WSTReturn('您的订单需要上传凭证,请前往上传!',-555,$certificateInfo);
|
||
}
|
||
}
|
||
return WSTReturn('',1);
|
||
}
|
||
/**
|
||
* 查看未提交和已提交凭证
|
||
* @return [type] [description]
|
||
*/
|
||
public function getShopCertificate($sId=0){
|
||
$type = (int)input('post.type');
|
||
if(!in_array($type,[0,1])){
|
||
return WSTReturn('传值非法',-1);
|
||
}
|
||
$shopId = ($sId==0)?(int)session('WST_USER.shopId'):$sId;
|
||
if(0 == $type ){
|
||
$where = ['shopId'=>$shopId,'dataFlag'=>1];
|
||
$where['orderStatus'] = 2;
|
||
$where['certificateStatus'] = 0;
|
||
$data = $this->alias('o')->where($where)
|
||
->field('o.orderRemarks,o.noticeDeliver,o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,orderStatus,deliverType,deliverMoney,isAppraise,isRefund,o.deliverType deliverTypes
|
||
,payType,payFrom,o.userPhone,userAddress,orderStatus,isPay,isAppraise,userName,orderSrc,o.createTime,o.orderCode,o.productNum,o.couponsNum,o.wangNum,o.moneyNum,o.certificateStatus,o.receiveTime,o.payable')
|
||
->order('o.orderId', 'desc')
|
||
->select();
|
||
if($data){
|
||
$orderIds = [];
|
||
foreach ($data as $v){
|
||
$orderIds[] = $v['orderId'];
|
||
}
|
||
$goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
|
||
$goodsMap = [];
|
||
foreach ($goods as &$val){
|
||
$val['goodsSpecNames'] = str_replace('@@_@@','、',$val['goodsSpecNames']);
|
||
$goodsMap[$val['orderId']][] = $val;
|
||
}
|
||
foreach ($data as &$v){
|
||
$v['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
|
||
$v['list'] = $goodsMap[$v['orderId']];
|
||
$v['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$v['deliverTypeName'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$v['deliverType'] = $v['deliverType'];
|
||
$v['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
}
|
||
}
|
||
return WSTReturn('',1,$data);
|
||
}elseif(1 == $type){
|
||
$m = Model('common/Table');
|
||
$m->setTable('order_shop_certificate');
|
||
$page = $m->getSelect(['shopId'=>$shopId],'id,orderIds,createTime,status','id DESC');
|
||
foreach ($page['Rows'] as &$v) {
|
||
$v['createTime'] = date('Y-m-d H:i:s',$v['createTime']);
|
||
$v['statusStr'] = '';
|
||
switch ($v['status']) {
|
||
case 2:
|
||
$v['statusStr'] = '审核中';
|
||
break;
|
||
case 3:
|
||
$v['statusStr'] = '已通过';
|
||
break;
|
||
case 4:
|
||
$v['statusStr'] = '已拒绝';
|
||
break;
|
||
}
|
||
$m->setTable('orders');
|
||
$v['list'] = $m->getList(['orderId'=>['IN',$v['orderIds']]],'orderNo,payable');
|
||
}
|
||
return WSTReturn('',1,$page);
|
||
}
|
||
}
|
||
/**
|
||
* 店铺上传凭证
|
||
* @return [type] [description]
|
||
*/
|
||
public function uploadShopCertificate($sId=0,$uId=0){
|
||
$orderIds = input('post.orderIds');
|
||
if($orderIds){
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
$userId = ($uId==0)?session('WST_USER.userId'):$uId;
|
||
$content = input('post.content');
|
||
if(!$content) return WSTReturn('请填写凭证说明',-1);
|
||
$imgUrl = input('post.imgUrl');
|
||
if(!$imgUrl) return WSTReturn('请上传凭证照片',-1);
|
||
$createTime = time();
|
||
$id = (int)input('post.id');
|
||
$status = 2;
|
||
Db::startTrans();
|
||
try{
|
||
if($id){
|
||
$isSuccess = Db::name('order_shop_certificate')->where(['id'=>$id])->update(compact('content','imgUrl','createTime'));
|
||
}else{
|
||
$isSuccess = Db::name('order_shop_certificate')->insert(compact('userId','shopId','orderIds','content','imgUrl','createTime'));
|
||
}
|
||
if(false !== $isSuccess){
|
||
Db::name('orders')->where(['orderId'=>['IN',$orderIds]])->update(['certificateStatus'=>$status]);
|
||
Db::commit();
|
||
return WSTReturn('上传凭证成功,请等待管理员审核!');
|
||
}
|
||
//}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
/**
|
||
* 助购吧获取用户订单列表
|
||
*/
|
||
public function userZgOrdersByPage($orderStatus, $isAppraise = -1, $uId=0){
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$orderNo = input('post.orderNo');
|
||
$shopName = input('post.shopName');
|
||
$isRefund = (int)input('post.isRefund',-1);
|
||
$where = ['o.userId'=>$userId,'o.dataFlag'=>1];
|
||
if(is_array($orderStatus)){
|
||
$where['orderStatus'] = ['in',$orderStatus];
|
||
}else{
|
||
$where['orderStatus'] = $orderStatus;
|
||
}
|
||
if($isAppraise!=-1)$where['isAppraise'] = $isAppraise;
|
||
if($orderNo!=''){
|
||
$where['o.orderNo'] = ['like',"%$orderNo%"];
|
||
}
|
||
if($shopName != ''){
|
||
$where['s.shopName'] = ['like',"%$shopName%"];
|
||
}
|
||
if(in_array($isRefund,[0,1])){
|
||
$where['isRefund'] = $isRefund;
|
||
}
|
||
$where["o.goodsType"]=3;
|
||
$page = $this->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->join('__ORDER_COMPLAINS__ oc','oc.orderId=o.orderId','left')
|
||
->join('__ORDERS_ECT__ ore','ore.orderId=o.orderId','left')
|
||
->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and orf.refundStatus!=-1','left')
|
||
->where($where)
|
||
->field('ore.orderEctNum,o.pay_name,ore.ectPrice,o.orderRemarks,o.noticeDeliver,o.orderId,o.orderNo,o.shopConfirm,s.shopName,s.shopId,s.shopQQ,s.phone,s.shopWangWang,o.goodsMoney,o.totalMoney,o.realTotalMoney,
|
||
o.orderStatus,o.deliverType,o.helpUserId,o.helpUserLevel,o.goodsType,deliverMoney,isPay,payType,payFrom,o.orderStatus,needPay,isAppraise,isRefund,orderSrc,o.createTime,o.useScore,oc.complainId,orf.id refundId,o.orderCode')
|
||
->order('o.createTime', 'desc')
|
||
->paginate(input('pagesize/d'))->toArray();
|
||
if(count($page['Rows'])>0){
|
||
$orderIds = [];
|
||
foreach ($page['Rows'] as $v){
|
||
$orderIds[] = $v['orderId'];
|
||
}
|
||
$goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
|
||
$goodsMap = [];
|
||
foreach ($goods as $v){
|
||
$v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
|
||
$v['marketPrice'] = Db::name('goods')->where(['goodsId'=>$v['goodsId']])->value('marketPrice');//添加返回市场价 mark hsf 20180112
|
||
$goodsMap[$v['orderId']][] = $v;
|
||
}
|
||
foreach ($page['Rows'] as $key => $v){
|
||
$page['Rows'][$key]['allowRefund'] = 0;
|
||
//只要是已支付的,并且没有申请退款的,都可以申请退款操作
|
||
if($v['isPay']==1 && $v['refundId']==''){
|
||
$page['Rows'][$key]['allowRefund'] = 1;
|
||
}
|
||
if($v["helpUserId"]!=0){
|
||
$page['Rows'][$key]['helpUser']=Db::name('users')->where('userId','=',$v["helpUserId"])
|
||
->field("userName")->find();
|
||
}else{
|
||
$page['Rows'][$key]['helpUser']=["userName"=>''];
|
||
}
|
||
//货到付款中使用了惠宝支付的也可以申请退款
|
||
if($v['payType']==0 && $v['refundId']=='' && $v['useScore']>0){
|
||
$page['Rows'][$key]['allowRefund'] = 1;
|
||
}
|
||
$page['Rows'][$key]['list'] = $goodsMap[$v['orderId']];
|
||
$page['Rows'][$key]['isComplain'] = 1;
|
||
if(($v['complainId']=='') && ($v['payType']==0 || ($v['payType']==1 && $v['orderStatus']!=-2))){
|
||
$page['Rows'][$key]['isComplain'] = '';
|
||
}
|
||
$page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$page['Rows'][$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
$page['Rows'][$key]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
|
||
}
|
||
hook('afterQueryUserOrders',['page'=>&$page]);
|
||
}
|
||
return $page;
|
||
}
|
||
|
||
/**
|
||
* 获取用户订单列表
|
||
*/
|
||
public function userOrdersByPage($orderStatus, $isAppraise = -1, $uId=0){
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$orderNo = input('post.orderNo');
|
||
$shopName = input('post.shopName');
|
||
$isRefund = (int)input('post.isRefund',-1);
|
||
$where = ['o.userId'=>$userId,'o.dataFlag'=>1];
|
||
if(is_array($orderStatus)){
|
||
$where['orderStatus'] = ['in',$orderStatus];
|
||
}else{
|
||
$where['orderStatus'] = $orderStatus;
|
||
}
|
||
if($isAppraise!=-1)$where['isAppraise'] = $isAppraise;
|
||
if($orderNo!=''){
|
||
$where['o.orderNo'] = ['like',"%$orderNo%"];
|
||
}
|
||
if($shopName != ''){
|
||
$where['s.shopName'] = ['like',"%$shopName%"];
|
||
}
|
||
if(in_array($isRefund,[0,1])){
|
||
$where['isRefund'] = $isRefund;
|
||
}
|
||
|
||
$page = $this->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->join('__ORDER_COMPLAINS__ oc','oc.orderId=o.orderId','left')
|
||
->join('__ORDERS_ECT__ ore','ore.orderId=o.orderId','left')
|
||
->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and orf.refundStatus!=-1','left')
|
||
->where($where)
|
||
->field('ore.orderEctNum,o.pay_name,ore.ectPrice,o.orderRemarks,o.noticeDeliver,o.orderId,o.orderNo,o.shopConfirm,s.shopName,s.shopId,s.shopQQ,s.phone,s.shopWangWang,o.goodsMoney,o.totalMoney,o.realTotalMoney,
|
||
o.orderStatus,o.deliverType,o.helpUserId,o.helpUserLevel,o.goodsType,deliverMoney,isPay,payType,payFrom,o.orderStatus,needPay,isAppraise,isRefund,orderSrc,o.createTime,o.useScore,oc.complainId,orf.id refundId,o.orderCode')
|
||
->order('o.createTime', 'desc')
|
||
->paginate(input('pagesize/d'))->toArray();
|
||
if(count($page['Rows'])>0){
|
||
$orderIds = [];
|
||
foreach ($page['Rows'] as $v){
|
||
$orderIds[] = $v['orderId'];
|
||
}
|
||
$goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
|
||
$goodsMap = [];
|
||
foreach ($goods as $v){
|
||
$v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
|
||
$v['marketPrice'] = Db::name('goods')->where(['goodsId'=>$v['goodsId']])->value('marketPrice');//添加返回市场价 mark hsf 20180112
|
||
$goodsMap[$v['orderId']][] = $v;
|
||
}
|
||
foreach ($page['Rows'] as $key => $v){
|
||
$page['Rows'][$key]['allowRefund'] = 0;
|
||
//只要是已支付的,并且没有申请退款的,都可以申请退款操作
|
||
if($v['isPay']==1 && $v['refundId']==''){
|
||
$page['Rows'][$key]['allowRefund'] = 1;
|
||
}
|
||
$page['Rows'][$key]['helpUser']=["userName"=>''];
|
||
//货到付款中使用了惠宝支付的也可以申请退款
|
||
if($v['payType']==0 && $v['refundId']=='' && $v['useScore']>0){
|
||
$page['Rows'][$key]['allowRefund'] = 1;
|
||
}
|
||
$page['Rows'][$key]['list'] = $goodsMap[$v['orderId']];
|
||
$page['Rows'][$key]['isComplain'] = 1;
|
||
if(($v['complainId']=='') && ($v['payType']==0 || ($v['payType']==1 && $v['orderStatus']!=-2))){
|
||
$page['Rows'][$key]['isComplain'] = '';
|
||
}
|
||
$page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$page['Rows'][$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
$page['Rows'][$key]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
|
||
}
|
||
hook('afterQueryUserOrders',['page'=>&$page]);
|
||
}
|
||
return $page;
|
||
}
|
||
/**
|
||
* 获取商家订单
|
||
*/
|
||
public function shopOrderList($orderStatus, $sId=0, $shopConfirm=-1){
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
$where = ['shopId'=>$shopId,'dataFlag'=>1];
|
||
if(is_array($orderStatus)){
|
||
$where['orderStatus'] = ['in',$orderStatus];
|
||
}else{
|
||
$where['orderStatus'] = $orderStatus;
|
||
}
|
||
if($shopConfirm >= 0){
|
||
if(strpos($shopConfirm,',')){
|
||
$where['shopConfirm'] = ['in',$shopConfirm];
|
||
}else{
|
||
$where['shopConfirm'] = $shopConfirm;
|
||
}
|
||
}
|
||
$page = $this->alias('o')->where($where)
|
||
->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and refundStatus=0','left')
|
||
->field('o.orderRemarks,o.noticeDeliver,o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,orderStatus,deliverType,deliverMoney,isAppraise,isRefund,o.deliverType deliverTypes
|
||
,payType,payFrom,o.userPhone,o.shopConfirm,userAddress,orderStatus,isPay,isAppraise,userName,orderSrc,o.createTime,orf.id refundId,o.orderCode,o.productNum,o.couponsNum,o.wangNum,o.moneyNum')
|
||
->order('o.createTime', 'desc')
|
||
->paginate(input('post.pageSize/d',10))->toArray();
|
||
if(count($page['Rows'])>0){
|
||
$orderIds = [];
|
||
foreach ($page['Rows'] as $v){
|
||
$orderIds[] = $v['orderId'];
|
||
}
|
||
$goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
|
||
$goodsMap = [];
|
||
foreach ($goods as $v){
|
||
$v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
|
||
$goodsMap[$v['orderId']][] = $v;
|
||
}
|
||
foreach ($page['Rows'] as $key => $v){
|
||
$page['Rows'][$key]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
|
||
$page['Rows'][$key]['list'] = $goodsMap[$v['orderId']];
|
||
$page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$page['Rows'][$key]['deliverTypeName'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$page['Rows'][$key]['deliverType'] = $v['deliverType'];
|
||
$page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
}
|
||
}
|
||
return $page;
|
||
}
|
||
/**
|
||
* 获取商家订单
|
||
*/
|
||
public function shopOrdersByPage($orderStatus, $sId=0){
|
||
$orderNo = input('post.orderNo');
|
||
$shopName = input('post.shopName');
|
||
$payType = (int)input('post.payType');
|
||
$deliverType = (int)input('post.deliverType');
|
||
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
|
||
|
||
$where = ['shopId'=>$shopId,'dataFlag'=>1];
|
||
if(is_array($orderStatus)){
|
||
$where['orderStatus'] = ['in',$orderStatus];
|
||
}else{
|
||
$where['orderStatus'] = $orderStatus;
|
||
}
|
||
if($orderNo!=''){
|
||
$where['orderNo'] = ['like',"%$orderNo%"];
|
||
}
|
||
if($shopName!=''){
|
||
$where['shopName'] = ['like',"%$shopName%"];
|
||
}
|
||
if($payType > -1){
|
||
$where['payType'] = $payType;
|
||
}
|
||
if($deliverType > -1){
|
||
$where['deliverType'] = $deliverType;
|
||
}
|
||
$page = $this->alias('o')->where($where)
|
||
->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and refundStatus=0','left')
|
||
->join('__ORDERS_ECT__ ore','ore.orderId=o.orderId','left')
|
||
->field('ore.orderEctNum,ore.ectPrice,o.orderRemarks,o.noticeDeliver,o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,orderStatus,deliverType,deliverMoney,isAppraise,isRefund,o.deliverType deliverTypes
|
||
,payType,payFrom,userAddress,orderStatus,isPay,isAppraise,userName,orderSrc,o.createTime,orf.id refundId,o.orderCode')
|
||
->order('o.createTime', 'desc')
|
||
->paginate()->toArray();
|
||
if(count($page['Rows'])>0){
|
||
$orderIds = [];
|
||
foreach ($page['Rows'] as $v){
|
||
$orderIds[] = $v['orderId'];
|
||
}
|
||
$goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
|
||
$goodsMap = [];
|
||
foreach ($goods as $v){
|
||
$v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
|
||
$goodsMap[$v['orderId']][] = $v;
|
||
}
|
||
foreach ($page['Rows'] as $key => $v){
|
||
$page['Rows'][$key]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
|
||
$page['Rows'][$key]['list'] = $goodsMap[$v['orderId']];
|
||
$page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$page['Rows'][$key]['deliverTypeName'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$page['Rows'][$key]['deliverType'] = $v['deliverType'];
|
||
$page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
}
|
||
}
|
||
return $page;
|
||
}
|
||
/**
|
||
* 商家确认
|
||
*/
|
||
public function orderConfirm($sId=0){
|
||
$orderId = (int)input('post.id');
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
$confirmType = (int)input('post.confirmType');
|
||
if(!in_array($confirmType,[1,2])) return WSTReturn('请正确选择是否收款',-1);
|
||
$order = $this->where(['shopId'=>$shopId,'orderId'=>$orderId,'orderStatus'=>0])->field('orderId,orderNo,userId')->find();
|
||
if(!empty($order)){
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['shopConfirm'=>$confirmType];
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
//if(false != $result){
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
//}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
/**
|
||
* 商家发货
|
||
*/
|
||
public function deliver($uId=0, $sId=0){
|
||
$orderId = (int)input('post.id');
|
||
$expressId = (int)input('post.expressId');
|
||
$expressNo = input('post.expressNo');
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->where(['shopId'=>$shopId,'orderId'=>$orderId,'orderStatus'=>0])->field('orderId,orderNo,userId,shopConfirm')->find();
|
||
if(!empty($order)){
|
||
if(1 != $order['shopConfirm']) return WSTReturn('请先确认订单',-1);
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['orderStatus'=>1,'expressId'=>$expressId,'expressNo'=>$expressNo,'deliveryTime'=>date('Y-m-d H:i:s')];
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
if(false != $result){
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 1;
|
||
$logOrder['logContent'] = "商家已发货".(($expressNo!='')?",快递号为:".$expressNo:"");
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//发送一条用户信息
|
||
$tpl = WSTMsgTemplates('ORDER_DELIVERY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${EXPRESS_NO}'];
|
||
$replace = [$order['orderNo'],($expressNo=='')?'无':$expressNo];
|
||
WSTSendMsg($order['userId'],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$orderId]);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
if($expressId>0){
|
||
$express = model('express')->get($expressId);
|
||
$params['EXPRESS'] = $express->expressName;
|
||
$params['EXPRESS_NO'] = $expressNo;
|
||
}else{
|
||
$params['EXPRESS'] = '无';
|
||
$params['EXPRESS_NO'] = '无';
|
||
}
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
|
||
WSTWxMessage(['CODE'=>'WX_ORDER_DELIVERY','userId'=>$order['userId'],'URL'=>Url('wechat/orders/index',['type'=>'waitReceive'],true,true),'params'=>$params]);
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
/**
|
||
* 商家修改快递单号
|
||
*/
|
||
public function updateDeliver($uId=0, $sId=0){
|
||
$orderId = (int)input('post.orderId');
|
||
$expressId = (int)input('post.expressId');
|
||
$expressNo = input('post.expressNo');
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->where(['shopId'=>$shopId,'orderId'=>$orderId,'orderStatus'=>1])->field('orderId,orderNo,userId')->find();
|
||
if(!empty($order)){
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['expressId'=>$expressId,'expressNo'=>$expressNo];
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
if(false != $result){
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 1;
|
||
$logOrder['logContent'] = "商家修改快递单号".(($expressNo!='')?",快递号为:".$expressNo:"");
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//发送一条用户信息
|
||
$tpl = WSTMsgTemplates('ORDER_DELIVERY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${EXPRESS_NO}'];
|
||
$replace = [$order['orderNo'],($expressNo=='')?'无':$expressNo];
|
||
WSTSendMsg($order['userId'],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$orderId]);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
if($expressId>0){
|
||
$express = model('express')->get($expressId);
|
||
$params['EXPRESS'] = $express->expressName;
|
||
$params['EXPRESS_NO'] = $expressNo;
|
||
}else{
|
||
$params['EXPRESS'] = '无';
|
||
$params['EXPRESS_NO'] = '无';
|
||
}
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
|
||
WSTWxMessage(['CODE'=>'WX_ORDER_DELIVERY','userId'=>$order['userId'],'URL'=>Url('wechat/orders/index',['type'=>'waitReceive'],true,true),'params'=>$params]);
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
|
||
|
||
|
||
|
||
/**
|
||
* 用户收货[同时给外部虚拟商品收货调用]
|
||
*/
|
||
public function receive($orderId = 0,$userId = 0){
|
||
if($orderId==0 && $userId==0){
|
||
$orderId = (int)input('post.id');
|
||
$userId = (int)session('WST_USER.userId');
|
||
}
|
||
$order = $this->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->where(['o.userId'=>$userId,'o.orderId'=>$orderId,'o.orderStatus'=>1])
|
||
->field('o.orderId,o.orderNo,o.helpUserId,o.helpUserLevel,o.payType,s.userId,s.shopId,s.userId as sUserId,o.orderScore,o.payFrom,o.goodsMoney,o.realTotalMoney,o.goodsType,commissionFee')->find();
|
||
if(!empty($order)){
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['orderStatus'=>2,'receiveTime'=>date('Y-m-d H:i:s')];
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
if(false != $result){
|
||
//确认收货后执行钩子
|
||
//hook('afterUserReceive',['orderId'=>$orderId]);
|
||
//dump(WSTConf('CONF.statementType'));
|
||
if(WSTConf('CONF.statementType')==1){
|
||
//修改商家未计算订单数,先不用确认收货结算 mark hsf 20171118
|
||
// $prefix = config('database.prefix');
|
||
// $upSql = 'update '.$prefix.'shops set noSettledOrderNum=noSettledOrderNum+1,noSettledOrderFee=noSettledOrderFee-'.$order['commissionFee'].' where shopId='.$order['shopId'];
|
||
// Db::execute($upSql);
|
||
}else{
|
||
//即时结算
|
||
//调用钩子 ——张开心
|
||
//hook('afterOrderSettlements',['order'=>&$order,'status'=>2]);
|
||
if(isset($order['is_settlements']) && $order['is_settlements'] == 1){
|
||
|
||
}else{
|
||
//即时结算
|
||
model('common/Settlements')->speedySettlement($orderId);
|
||
}
|
||
}
|
||
$m = Model('common/Table');
|
||
$userInfo = getUserInfo(['userId'=>$userId],'userName,userType,buyHelpMoney,helpMaxSaleMoney');
|
||
// 计算 SUM(商品*优惠率) 的值
|
||
$calBaseNum = Db::table("__ORDERS__ o")->join("__ORDER_GOODS__ g", "g.orderId=o.orderId", 'inner')
|
||
->where(['o.orderId'=>$orderId])->sum('g.goodsPrice*g.goodsNum*g.discountRate*0.01');
|
||
if (2 == $order['goodsType']){//助微吧购物
|
||
if (1 == $userInfo['userType']){//是商户购物
|
||
//加助微吧购物金额
|
||
$m->setTable('users');
|
||
$m->incNum(['userId'=>$userId],'buyHelpMoney',$order['realTotalMoney']);
|
||
//加入记录
|
||
$m->setTable('user_ect_log');
|
||
$m->insertInfo(['userId'=>$userId,'ectNum'=>$order['realTotalMoney'],'ectType'=>1,'dataRemarks'=>'商户购物']);
|
||
//获取店铺最大等级
|
||
$m->setTable('shops');
|
||
$shopLevel = $m->getMax(['userId'=>$userId,'dataFlag'=>1],'shopLevel');
|
||
//换算为3级循环等级
|
||
$nowLevel = $shopLevel % 3;
|
||
//升级到下一级所需金额
|
||
// 助微吧再次销售限购物额为≥?元 @2020/09/19
|
||
$upgradeMoney = dataConf('helpUpgradeLevel1BuyMoney');
|
||
//获取助微吧购物金额
|
||
$buyHelpMoney = $userInfo['buyHelpMoney'] + $order['realTotalMoney'];
|
||
//查看是否够升级条件
|
||
if($buyHelpMoney >= $upgradeMoney){
|
||
//够条件,升级,并把buyHelpMoney值清0
|
||
$m->setTable('shops');
|
||
$m->incNum(['userId'=>$userId],'shopLevel',1);
|
||
//buyHelpMoney值清0
|
||
$m->setTable('users');
|
||
//购物值清零,总可销售额增加
|
||
$m->updateInfo(['userId'=>$userId],['buyHelpMoney'=>0,'helpMaxSaleMoney'=>($userInfo['helpMaxSaleMoney'] + $order['realTotalMoney'])]);
|
||
$m->setTable('user_ect_log');
|
||
$m->insertInfo(['userId'=>$userId,'ectNum'=>$buyHelpMoney,'ectType'=>2,'dataRemarks'=>'升级'.($nowLevel+1).'级清零前值']);
|
||
}
|
||
}else{
|
||
$m->insertInfo(['userId'=>$userId,'ectNum'=>$order['realTotalMoney'],'ectType'=>1,'dataRemarks'=>'购户购物']);
|
||
}
|
||
}
|
||
elseif (3 == $order['goodsType']){//助购吧购物
|
||
// foreach ($orderGoods as $orderGood) {
|
||
// // 在不考虑数据库变更的情况下,这两个值都是存储的数字类型,所以不做特殊处理
|
||
// $calBaseNum += (float)$orderGood['goodsPrice'] * (float)$orderGood['discountRate'] / 100;
|
||
// }
|
||
|
||
$sm = Model('common/SysSummary');
|
||
|
||
// step 2 商户支付优惠款给平台:10000×0.4=4000
|
||
// 10.15添加 优惠款 全额进入 代快付值
|
||
// 20.06.29 优惠款 90%进入 代快付值
|
||
// $sm->addSysSummary($calBaseNum*0.9,0,1,'助购吧购物,订单号ID['.$orderId.'],优惠款90%进入代快付值');
|
||
|
||
$vm = new UserVouchers();
|
||
|
||
|
||
|
||
// step 5 平台送自己:10000×N“助购预获”,
|
||
// 10000“预获产品券”;
|
||
// 10000×0.4×0.5×0.5=1000“预获优惠券”。
|
||
if ((int)$order["helpUserLevel"] === 1) {
|
||
$vm->insertHelpSaleNotice($userId, $orderId, $order['goodsMoney']*((int)$order["helpUserLevel"]),
|
||
'交易订单【'.$order['orderNo'].'】购户购物所得', 1);
|
||
} else {
|
||
$vm->insertHelpSaleNotice($userId, $orderId, $order['goodsMoney']*((int)$order["helpUserLevel"])*(float)dataConf("helpSaleCalBase"),
|
||
'交易订单【'.$order['orderNo'].'】购户购物所得', 1);
|
||
}
|
||
|
||
// step 8 平台送自己的上第N层:扣减“助购预获”、“预获产品券”各10000×0.4×0.5=2000,
|
||
// 同时添加10000×0.4×0.5=2000“已获产品券”。
|
||
if((int)$order["helpUserLevel"]!==0){
|
||
$vm->insertHelpSaleNotice($order["helpUserId"], $orderId, $calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100),
|
||
'预获助购转换所扣', 0);
|
||
$sm->addSysSummary($calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100),0,2,'订单【'.($order['orderNo']?:'--').'】被助购转换所扣');
|
||
$vm->insertVouchersNotice($order['helpUserId'], $orderId, $calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100), 0,
|
||
'预获产品券转换所扣',0);
|
||
$vm->insertAlreadyVouchersNotice($order['helpUserId'], $orderId, $calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100), 0,
|
||
'预获产品券转换所得',1);
|
||
}else{
|
||
$vm->insertHelpSaleNotice($order["helpUserId"], $orderId, 0,
|
||
'预获产品券转换所扣', 0);
|
||
}
|
||
|
||
// 9.26添加
|
||
//四级功能相关字:购户吉日获得“已获优惠券”为 00时 00分 15秒 ? 年2020? 月10? 日01
|
||
//四级功能相关字:购户吉日获得“已获优惠券”的留言?祝您及家人幸福安康
|
||
//四级功能相关字:购户吉日获得“已获优惠券”为“助购值”的?% 50
|
||
$sysConf = (new SCM())->getSysConfigs();
|
||
if (isset($sysConf['jiri_jiyan']) && isset($sysConf['jiri_get_percent']) && !empty(floatval($sysConf['jiri_get_percent'])) && isset($sysConf['jiri']) ) {
|
||
if (date('Y/m/d') == date('Y-m-d', strtotime($sysConf['jiri']))) {
|
||
$zhugou_value = $calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100);
|
||
$jiri_get_percent = floatval($sysConf['jiri_get_percent']);
|
||
$jiri_jiyan = $sysConf['jiri_jiyan'];
|
||
$vm->insertAlreadyVouchersNotice($userId, $orderId, 0, round($zhugou_value*$jiri_get_percent*100, 5), $jiri_jiyan);
|
||
}
|
||
}
|
||
|
||
// 10.15添加:助购户的 助购预获 减少的同时 代快付值等额减少
|
||
if ((int)$order["helpUserLevel"] === 1) {
|
||
Db::name("orders")->where(compact('orderId'))->update([
|
||
"helpGetCount"=>$order['goodsMoney']*((int)$order["helpUserLevel"]),
|
||
"helpGetCount2"=>$calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100),
|
||
]);}
|
||
else {
|
||
Db::name("orders")->where(compact('orderId'))->update([
|
||
"helpGetCount"=>$order['goodsMoney']*((int)$order["helpUserLevel"])*(float)dataConf("helpSaleCalBase"),
|
||
"helpGetCount2"=>$calBaseNum*((float)dataConf('helpSaleCouponsCalBase')/100),
|
||
]);
|
||
}
|
||
}
|
||
$vm = new UserVouchers();
|
||
$vm->insertVouchersNotice($userId, $orderId, $calBaseNum*((float)dataConf('couponPercentCanUsetGet')/100), 0,
|
||
'交易订单【'.$order['orderNo'].'】购户从优惠款中获得',1);
|
||
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 2;
|
||
$logOrder['logContent'] = "用户已收货";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_RECEIVE');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$order['orderNo']];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
//给用户增加惠宝
|
||
if(WSTConf("CONF.isOrderScore")==1 && $order['orderScore']>0){
|
||
$score = [];
|
||
$score['userId'] = $userId;
|
||
$score['score'] = $order['orderScore'];
|
||
$score['dataSrc'] = 1;
|
||
$score['dataId'] = $orderId;
|
||
$score['dataRemarks'] = "交易订单【".$order['orderNo']."】获得惠宝".$order['orderScore']."个";
|
||
$score['scoreType'] = 1;
|
||
model('UserScores')->add($score);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$params['ORDER_TIME'] = date('Y-m-d H:i:s');
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_RECEIVE','userId'=>$order['userId'],'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_RECEIVE";
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params] ;
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}else{
|
||
// 避免多次事物重叠
|
||
Db::rollback();
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();
|
||
errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
//用户延时收货
|
||
public function delay(){
|
||
$id=(int)input('id');
|
||
$find=Db::name('order_delay')->where('orderId',$id)->find();
|
||
if($find) return WSTReturn('您已经延迟收货过了');
|
||
$time = (int)WSTConf('CONF.autoAppraiseDays');
|
||
$delay=(int)($time+3)*60*60*24;
|
||
$deliveryTime=(int)strtotime($this->where('orderId',$id)->value('deliveryTime'));
|
||
Db::startTrans();
|
||
try{
|
||
$delayTime=$deliveryTime+$delay;
|
||
$data['orderId']=$id;
|
||
$data['delayTime']=$delayTime;
|
||
$data['createTime']=time();
|
||
db('order_delay')->insert($data);
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
/**
|
||
* 用户取消订单
|
||
*/
|
||
public function cancel($uId=0){
|
||
$orderId = (int)input('post.id');
|
||
hook('beforeCancelOrder',['orderId'=>$orderId]);
|
||
$reason = (int)input('post.reason');
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->where(['o.userId'=>$userId,'o.orderId'=>$orderId,'o.orderStatus'=>['in',[-2,0]]])
|
||
->field('o.orderId,o.orderNo,s.userId,s.shopId,o.orderCode,o.orderType,o.payType,o.orderStatus,o.useScore,o.scoreMoney,o.realTotalMoney')->find();
|
||
$reasonData = WSTDatas('ORDER_CANCEL',$reason);
|
||
if(empty($reasonData))return WSTReturn("无效的取消原因");
|
||
if(!empty($order)){
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['orderStatus'=>-1,'cancelReason'=>$reason];
|
||
//如果是货到付款取消的话,把实付金额设置为0
|
||
if($order['payType']==0)$data['realTotalMoney'] = 0;
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
if(false != $result){
|
||
//未付款状、货到付款取消订单态则直接退回惠宝
|
||
if(($order['orderStatus'] == -2 && $order['payType']==1 && $order['useScore']>0) || ($order['orderStatus'] == 0 && $order['payType']==0 && $order['useScore']>0)){
|
||
$score = [];
|
||
$score['userId'] = $userId;
|
||
$score['score'] = $order['useScore'];
|
||
$score['dataSrc'] = 1;
|
||
$score['dataId'] = $orderId;
|
||
$score['dataRemarks'] = "取消交易订单【".$order['orderNo']."】,退回惠宝".$order['useScore']."个";
|
||
$score['scoreType'] = 1;
|
||
model('UserScores')->add($score);
|
||
}
|
||
//正常订单商品库存处理
|
||
$goods = Db::name('order_goods')->alias('og')->join('__GOODS__ g','og.goodsId=g.goodsId','inner')
|
||
->where('orderId',$orderId)->field('og.*,g.isSpec')->select();
|
||
|
||
//返还商品库存
|
||
foreach ($goods as $key => $v){
|
||
//处理虚拟产品
|
||
if($v['goodsType']==1){
|
||
$extraJson = json_decode($v['extraJson'],true);
|
||
foreach ($extraJson as $ecard) {
|
||
Db::name('goods_virtuals')->where('id',$ecard['cardId'])->update(['orderId'=>0,'orderNo'=>'','isUse'=>0]);
|
||
}
|
||
$counts = Db::name('goods_virtuals')->where(['dataFlag'=>1,'goodsId'=>$v['goodsId'],'isUse'=>0])->count();
|
||
Db::name('goods')->where('goodsId',$v['goodsId'])->setField('goodsStock',$counts);
|
||
}else{
|
||
if($order['orderCode']=='order'){
|
||
//修改库存
|
||
if($v['isSpec']>0){
|
||
Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setInc('specStock',$v['goodsNum']);
|
||
}
|
||
Db::name('goods')->where('goodsId',$v['goodsId'])->setInc('goodsStock',$v['goodsNum']);
|
||
}
|
||
}
|
||
}
|
||
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = -1;
|
||
$logOrder['logContent'] = "用户取消订单,取消原因:".$reasonData['dataName'];
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//提交订单后执行钩子
|
||
hook('afterCancelOrder',['orderId'=>$orderId]);
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_CANCEL');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${REASON}'];
|
||
$replace = [$order['orderNo'],$reasonData['dataName']];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_CANCEL_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsCancelOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.cancelOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'cancel','');
|
||
}
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$goodsNames = [];
|
||
foreach ($goods as $gkey =>$g){
|
||
$goodsNames[] = $g['goodsName']."*".$g['goodsNum'];
|
||
}
|
||
$params['REASON'] = $reasonData['dataName'];
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_CANCEL','userId'=>$order['userId'],'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_CANCEL";
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>'WX_ORDER_CANCEL','URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxCancelOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$goodsNames = [];
|
||
foreach ($goods as $gkey =>$g){
|
||
$goodsNames[] = $g['goodsName']."*".$g['goodsNum'];
|
||
}
|
||
$params['REASON'] = $reasonData['dataName'];
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_CANCEL','userType'=>3,'userId'=>explode(',',WSTConf('CONF.cancelOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('订单取消成功',1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
/**
|
||
* 用户拒收订单
|
||
*/
|
||
public function reject($uId=0){
|
||
$orderId = (int)input('post.id');
|
||
$reason = (int)input('post.reason');
|
||
$content = input('post.content');
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$order = $this->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->where(['o.userId'=>$userId,'o.orderId'=>$orderId,'o.orderStatus'=>1])
|
||
->field('o.orderId,o.orderNo,o.shopId,s.userId,payType,o.userAddress,o.userName,o.realTotalMoney,o.scoreMoney')->find();
|
||
$reasonData = WSTDatas('ORDER_REJECT',$reason);
|
||
if(empty($reasonData))return WSTReturn("无效的拒收原因");
|
||
if($reason==10000 && $content=='')return WSTReturn("请输入拒收原因");
|
||
if(!empty($order)){
|
||
Db::startTrans();
|
||
try{
|
||
$data = ['orderStatus'=>-3,'rejectReason'=>$reason];
|
||
if($reason==10000)$data['rejectOtherReason'] = $content;
|
||
//如果是货到付款拒收的话,把实付金额设置为0
|
||
if($order['payType']==0)$data['realTotalMoney'] = 0;
|
||
$result = $this->where('orderId',$order['orderId'])->update($data);
|
||
if(false != $result){
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = -3;
|
||
$logOrder['logContent'] = "用户拒收订单,拒收原因:".$reasonData['dataName'].(($reason==10000)?"-".$content:"");
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_REJECT');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${REASON}'];
|
||
$replace = [$order['orderNo'],$reasonData['dataName'].(($reason==10000)?"-".$content:"")];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $order['shopId'];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_REJECT_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRejectOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.rejectOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'cancel','');
|
||
}
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$goods = Db::name('order_goods')->where('orderId',$order['orderId'])->select();
|
||
$goodsNames = [];
|
||
foreach ($goods as $gkey =>$goods){
|
||
$goodsNames[] = $goods['goodsName']."*".$goods['goodsNum'];
|
||
}
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
|
||
$params['REASON'] = $reasonData['dataName'].(($reason==10000)?"-".$content:"");
|
||
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_REJECT";
|
||
$msg["shopId"] = $order['shopId'];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxRejectOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$goods = Db::name('order_goods')->where('orderId',$order['orderId'])->select();
|
||
$goodsNames = [];
|
||
foreach ($goods as $gkey =>$goods){
|
||
$goodsNames[] = $goods['goodsName']."*".$goods['goodsNum'];
|
||
}
|
||
$params['GOODS'] = implode(',',$goodsNames);
|
||
$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
|
||
$params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
|
||
$params['REASON'] = $reasonData['dataName'].(($reason==10000)?"-".$content:"");
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REJECT','userType'=>3,'userId'=>explode(',',WSTConf('CONF.rejectOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
return WSTReturn('操作失败,请检查订单状态是否已改变');
|
||
}
|
||
/**
|
||
* 获取订单价格
|
||
*/
|
||
public function getMoneyByOrder($orderId = 0){
|
||
$orderId = ($orderId>0)?$orderId:(int)input('post.id');
|
||
$result= $this->where('orderId',$orderId)->field('orderId,orderNo,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney,payFrom,productNum,couponsNum,wangNum,moneyNum')->find();
|
||
if($result['payFrom']=="ect"){
|
||
$result['ectNum']=db('orders_ect')->where('orderId',$orderId)->value('orderEctNum');
|
||
}
|
||
$result['ectNum']=isset($result['ectNum'])?$result['ectNum']:"";
|
||
return $result;
|
||
}
|
||
|
||
|
||
/**
|
||
* 修改订单价格
|
||
*/
|
||
public function editOrderMoney($uId=0, $sId=0){
|
||
$orderId = input('post.id');
|
||
$orderMoney = (float)input('post.orderMoney');
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$shopId = ($sId==0)?session('WST_USER.shopId'):$sId;
|
||
if($orderMoney<0.01)return WSTReturn("订单价格不能小于0.01");
|
||
Db::startTrans();
|
||
try{
|
||
|
||
$data = array();
|
||
$data["realTotalMoney"] = $orderMoney;
|
||
$data["needPay"] = $orderMoney;
|
||
$data["payRand"] = array("exp","payRand+1");
|
||
$result = $this->where(['orderId'=>$orderId,'shopId'=>$shopId,'orderStatus'=>-2])->update($data);
|
||
|
||
if(false !== $result){
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = -2;
|
||
$logOrder['logContent'] = "商家修改订单价格为:".$orderMoney;
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
Db::commit();
|
||
return WSTReturn('操作成功',1);
|
||
}
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取订单详情
|
||
*/
|
||
public function getByView($orderId, $uId=0){
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
$shopId = ($uId==0)?(int)session('WST_USER.shopId'):$uId;
|
||
$orders = Db::name('orders')->alias('o')->join('__EXPRESS__ e','o.expressId=e.expressId','left')
|
||
->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->join('__ORDER_REFUNDS__ orf ','o.orderId=orf.orderId','left')
|
||
->where('o.dataFlag=1 and o.orderId='.$orderId.' and ( o.userId='.$userId.' or o.shopId='.$shopId.')')
|
||
->field('o.*,e.expressName,s.shopTel,s.shopName,s.shopQQ,s.shopWangWang,orf.id refundId,orf.refundRemark,orf.refundStatus,orf.refundTime,orf.backMoney,orf.backMoney')->find();
|
||
if(empty($orders))return WSTReturn("无效的订单信息");
|
||
|
||
//获取订单信息
|
||
$orders['log'] =Db::name('log_orders')->where('orderId',$orderId)->order('logId asc')->select();
|
||
//获取订单商品
|
||
$orders['goods'] = Db::name('order_goods')->alias('og')->join('__GOODS__ g','g.goodsId=og.goodsId','left')->where('orderId',$orderId)->field('og.*,g.goodsSn,g.marketPrice')->order('id asc')->select();//添加市场价返加 mark hsf 20180216
|
||
//如果是虚拟商品
|
||
if($orders['orderType']==1){
|
||
foreach ($orders['goods'] as $key => $v) {
|
||
$orders['goods'][$key]['extraJson'] = json_decode($v['extraJson'],true);
|
||
}
|
||
}
|
||
return $orders;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 根据订单id获取 商品信息跟商品评价
|
||
*/
|
||
public function getOrderInfoAndAppr($uId=0){
|
||
$orderId = (int)input('oId');
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
//添加凭证时用户验证 mark hsf 20171206
|
||
if(!Db::name('orders')->where(['orderId'=>$orderId,'userId'=>$userId])->find()){
|
||
throw new \Exception($userId.'没有权限');die;
|
||
}
|
||
//----end------
|
||
$goodsInfo = Db::name('order_goods')
|
||
->field('id,orderId,goodsName,goodsId,goodsSpecNames,goodsImg,goodsSpecId,goodsCode')
|
||
->where(['orderId'=>$orderId])
|
||
->select();
|
||
//根据商品id 与 订单id 取评价
|
||
$alreadys = 0;// 已评价商品数
|
||
$count = count($goodsInfo);//订单下总商品数
|
||
if($count>0){
|
||
foreach($goodsInfo as $k=>$v){
|
||
$goodsInfo[$k]['goodsSpecNames'] = str_replace('@@_@@', ';', $v['goodsSpecNames']);
|
||
$appraise = Db::name('goods_appraises')
|
||
->field('goodsScore,serviceScore,timeScore,content,images,createTime')
|
||
->where(['goodsId'=>$v['goodsId'],
|
||
'goodsSpecId'=>$v['goodsSpecId'],
|
||
'orderId'=>$orderId,
|
||
'dataFlag'=>1,
|
||
'isShow'=>1,
|
||
'userId'=>$userId,
|
||
'orderGoodsId'=>$v['id'],
|
||
])->find();
|
||
if(!empty($appraise)){
|
||
++$alreadys;
|
||
$appraise['images'] = ($appraise['images']!='')?explode(',', $appraise['images']):[];
|
||
}
|
||
$goodsInfo[$k]['appraise'] = $appraise;
|
||
}
|
||
}
|
||
return ['count'=>$count,'Rows'=>$goodsInfo,'alreadys'=>$alreadys];
|
||
|
||
}
|
||
|
||
/**
|
||
* 检查订单是否已支付
|
||
*/
|
||
public function checkOrderPay (){
|
||
$userId = (int)session('WST_USER.userId');
|
||
$orderNo = input("orderNo");
|
||
$isBatch = (int)input("isBatch");
|
||
$rs = array();
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
$rs = $this->field('orderId,orderNo')->where($where)->select();
|
||
if(count($rs)>0){
|
||
return WSTReturn('',1);
|
||
}else{
|
||
return WSTReturn('订单已支付',-1);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 检查订单是否已支付
|
||
*/
|
||
public function checkOrderPay2 ($obj){
|
||
$userId = $obj["userId"];
|
||
$orderNo = $obj["orderNo"];
|
||
$isBatch = $obj["isBatch"];
|
||
$rs = array();
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
$rs = $this->field('orderId,orderNo')->where($where)->select();
|
||
if(count($rs)>0){
|
||
return WSTReturn('',1);
|
||
}else{
|
||
return WSTReturn('订单已支付',-1);
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* 虚拟商品支付处理
|
||
*/
|
||
public function handleVirtualGoods($orderId){
|
||
$order= Db::name('orders')->alias('o')->join('__SHOPS__ s','o.shopId=s.shopId ','inner')
|
||
->where('orderId',$orderId)->field('orderId,orderNo,o.shopId,s.userId,o.userId ouserId,o.realTotalMoney,o.payFrom')
|
||
->find();
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $order['orderId'];
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "商家已发货";
|
||
$logOrder['logUserId'] = $order['userId'];
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $order['orderId'];
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "用户已收货";
|
||
$logOrder['logUserId'] = $order['ouserId'];
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//修改订单状态
|
||
Db::name('orders')->where('orderId',$order['orderId'])->update(['orderStatus'=>2,'deliveryTime'=>date('Y-m-d H:i:s'),'receiveTime'=>date('Y-m-d H:i:s')]);
|
||
//分配卡券号
|
||
$orderGoods = Db::name('order_goods')->where(['orderId'=>$order['orderId'],'goodsType'=>1])->field('id,goodsName,extraJson')->find();
|
||
$cardIds = [];
|
||
$extraJson = json_decode($orderGoods['extraJson'],true);
|
||
foreach ($extraJson as $ogextra) {
|
||
$cardIds[] = $ogextra['cardId'];
|
||
}
|
||
$cards = model('common/GoodsVirtuals')->where(['id'=>['in',$cardIds]])->field('id,cardNo,cardPwd')->select();
|
||
$cardmap = [];
|
||
foreach ($cards as $card) {
|
||
$cardmap[$card['id']] = $card;
|
||
}
|
||
$ogcards = [];
|
||
$extra = json_decode($orderGoods['extraJson'],true);
|
||
foreach ($extra as $ogextra) {
|
||
$ogextra['cardId'] = $cardmap[$ogextra['cardId']]['id'];
|
||
$ogextra['cardNo'] = $cardmap[$ogextra['cardId']]['cardNo'];
|
||
$ogextra['cardPwd'] = $cardmap[$ogextra['cardId']]['cardPwd'];
|
||
$ogextra['isUse'] = 0;
|
||
$ogcards[] = $ogextra;
|
||
}
|
||
Db::name('order_goods')->where('id',$orderGoods['id'])->update(['extraJson'=>json_encode($ogcards)]);
|
||
//即时结算
|
||
model('common/Settlements')->speedySettlement($orderId);
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_SHOP_AUTO_DELIVERY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${GOODS}'];
|
||
$replace = [$order['orderNo'],$orderGoods['goodsName']];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$order['orderId']];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
//发送一条用户信息
|
||
$tpl = WSTMsgTemplates('ORDER_USER_AUTO_DELIVERY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}','${GOODS}'];
|
||
$replace = [$order['orderNo'],$orderGoods['goodsName']];
|
||
WSTSendMsg($order["ouserId"],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$order['orderId']]);
|
||
}
|
||
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'handleVirtualGoods','');
|
||
}
|
||
}
|
||
//微信消息-已支付
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order['realTotalMoney'];
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order['payFrom']);
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_PAY','userId'=>$order["userId"],'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_PAY";
|
||
$msg["shopId"] = $order["shopId"];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxPayOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order['orderNo'];
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order['realTotalMoney'];
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order['payFrom']);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>3,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
/**
|
||
* 完成支付订单
|
||
*/
|
||
public function complatePay ($obj){
|
||
$trade_no = $obj["trade_no"];
|
||
$isBatch = (int)$obj["isBatch"];
|
||
$orderNo = $obj["out_trade_no"];
|
||
$userId = (int)$obj["userId"];
|
||
$payFrom = $obj["payFrom"];
|
||
$payMoney = (float)$obj["total_fee"];
|
||
if($payFrom!=''){
|
||
$cnt = model('orders')
|
||
->where(['payFrom'=>$payFrom,"userId"=>$userId,"tradeNo"=>$trade_no])
|
||
->count();
|
||
if($cnt>0){
|
||
return WSTReturn('订单已支付',-1);
|
||
}
|
||
}
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
|
||
$orders = model('orders')->where($where)->field('needPay,orderId,payType,orderType,orderNo,shopId,commissionFee,payFrom,realTotalMoney')->select();
|
||
if(count($orders)==0)return WSTReturn('无效的订单信息',-1);
|
||
|
||
$needPay = 0;
|
||
foreach ($orders as $key => $v) {
|
||
$needPay += $v['needPay'];
|
||
}
|
||
//if($needPay>$payMoney){
|
||
if(bccomp($needPay,$payMoney) == 1){
|
||
return WSTReturn('支付金额不正确',-1);
|
||
}
|
||
$sms_num = 0;
|
||
Db::startTrans();
|
||
try{
|
||
$data = array();
|
||
$data["needPay"] = 0;
|
||
$data["isPay"] = 1;
|
||
$data["orderStatus"] = 0;
|
||
$data["tradeNo"] = $trade_no;
|
||
$data["payFrom"] = $payFrom;
|
||
$data["payTime"] = date("Y-m-d H:i:s");
|
||
$rs = model('orders')->where($where)->update($data);
|
||
|
||
if($needPay>0 && false != $rs){
|
||
foreach ($orders as $key =>$v){
|
||
$orderId = $v["orderId"];
|
||
$shop = model('shops')->get($v->shopId);
|
||
|
||
//调用钩子 ——张开心
|
||
hook('afterOrderSettlements',['order'=>$v,'status'=>1]);
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
//创建一条充值流水记录
|
||
$lm = [];
|
||
$lm['targetType'] = 0;
|
||
$lm['targetId'] = $userId;
|
||
$lm['dataId'] = $orderId;
|
||
$lm['dataSrc'] = 1;
|
||
$lm['remark'] = '交易订单【'.$v['orderNo'].'】充值¥'.$needPay;
|
||
$lm['moneyType'] = 1;
|
||
$lm['money'] = $needPay;
|
||
$lm['payType'] = $payFrom;
|
||
$lm['tradeNo'] = $trade_no;
|
||
$lm['createTime'] = date('Y-m-d H:i:s');
|
||
model('LogMoneys')->create($lm);
|
||
//创建一条支出流水记录
|
||
$lm = [];
|
||
$lm['targetType'] = 0;
|
||
$lm['targetId'] = $userId;
|
||
$lm['dataId'] = $orderId;
|
||
$lm['dataSrc'] = 1;
|
||
$lm['remark'] = '交易订单【'.$v['orderNo'].'】支出¥'.$needPay;
|
||
$lm['moneyType'] = 0;
|
||
$lm['money'] = $needPay;
|
||
$lm['payType'] = 0;
|
||
$lm['createTime'] = date('Y-m-d H:i:s');
|
||
model('LogMoneys')->create($lm);
|
||
|
||
//虚拟商品处理
|
||
if($v['orderType']==1){
|
||
$this->handleVirtualGoods($v['orderId']);
|
||
}else{
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_HASPAY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$v['orderNo']];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $shop["shopId"];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$v['orderNo']]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'complatePay','');
|
||
}
|
||
}
|
||
//商家短信通知 mark hsf 20180421
|
||
if((int)WSTConf('CONF.smsOpen')==1 && WSTIsPhone($shop['telephone'])){
|
||
hook('afterOrderPay',['tplCode'=>'PHONE_SHOP_MSG','userId'=>$shop['userId'],"telephone"=>$shop['telephone'],'orderNo'=>$v['orderNo'],'orderStatus'=>0]);
|
||
}
|
||
$tpl = WSTMsgTemplates('PHONE_SHOP_MSG');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1' && $sms_num == 0){
|
||
$sms_num = 1;
|
||
$shopInfo = GetShopInfo($shop['shopId'],'telephone,userId');
|
||
if(WSTIsPhone($shopInfo['telephone'])){
|
||
// $params = ['tpl'=>$tpl,'params'=>['orderNo'=>$v['orderNo'],'orderStatue'=>'已付款']];
|
||
// $model_logsms = new LogSms();
|
||
// $model_logsms->sendShopSMS(0,$shopInfo['telephone'],$params,'pay','',$shopInfo['userId']);
|
||
}
|
||
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $v['orderNo'];
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $v['realTotalMoney'];
|
||
$params['PAY_SRC'] = WSTLangPayFrom($v['payFrom']);
|
||
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_PAY";
|
||
$msg["shopId"] = $shop["shopId"];
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxPayOrderTip')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $v['orderNo'];
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $v['realTotalMoney'];
|
||
$params['PAY_SRC'] = WSTLangPayFrom($v['payFrom']);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>3,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}else{
|
||
$data = array();
|
||
$data["userMoney"] = array("exp","userMoney+".$payMoney);
|
||
Db::name('users')->where("userId",$userId)->update($data);
|
||
//创建一条充值流水记录
|
||
$lm = [];
|
||
$lm['targetType'] = 0;
|
||
$lm['targetId'] = $userId;
|
||
$lm['dataId'] = $orderNo;
|
||
$lm['dataSrc'] = 1;
|
||
$lm['remark'] = '交易订单充值¥'.$payMoney;
|
||
$lm['moneyType'] = 1;
|
||
$lm['money'] = $payMoney;
|
||
$lm['payType'] = $payFrom;
|
||
$lm['tradeNo'] = $trade_no;
|
||
$lm['createTime'] = date('Y-m-d H:i:s');
|
||
model('LogMoneys')->create($lm);
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('支付成功',1);
|
||
}catch (\Exception $e) {
|
||
dump($e);
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('操作失败',-1);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取支付订单信息
|
||
*/
|
||
public function getPayOrders ($obj){
|
||
$userId = (int)$obj["userId"];
|
||
$orderNo = $obj["orderNo"];
|
||
$isBatch = (int)$obj["isBatch"];
|
||
$needPay = 0;
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
$data = array();
|
||
$needPay = model('orders')->where($where)->sum('needPay');
|
||
$payRand = model('orders')->where($where)->max('payRand');
|
||
$data["needPay"] = $needPay;
|
||
$data["payRand"] = $payRand;
|
||
return $data;
|
||
}
|
||
|
||
/**
|
||
* 导出订单
|
||
*/
|
||
public function toExport(){
|
||
$name='订单表';
|
||
$where = ['o.dataFlag'=>1];
|
||
$orderStatus = (int)input('orderStatus',0);
|
||
if($orderStatus==0){
|
||
$name='待发货订单表';
|
||
}else if($orderStatus==-2){
|
||
$name='待付款订单表';
|
||
}else if($orderStatus==1){
|
||
$name='配送中订单表';
|
||
}else if($orderStatus==-1){
|
||
$name='取消订单表';
|
||
}else if($orderStatus==-3){
|
||
$name='拒收订单表';
|
||
}else if($orderStatus==2){
|
||
$name='已收货订单表';
|
||
}else if($orderStatus==10000){
|
||
$name='取消/拒收订单表';
|
||
}else if($orderStatus==20000){
|
||
$name='待收货订单表';
|
||
}
|
||
$shopId = session('WST_USER.shopId');
|
||
$where = ['o.shopId'=>$shopId];
|
||
$orderNo = input('orderNo');
|
||
$shopName = input('shopName');
|
||
|
||
$type = (int)input('type',-1);
|
||
$payType = $type>0?$type:(int)input('payType',-1);
|
||
$deliverType = (int)input('deliverType');
|
||
if($orderStatus == 10000)$orderStatus = [-1,-3];
|
||
if($orderStatus == 20000)$orderStatus = [0,1];
|
||
if(is_array($orderStatus)){
|
||
$where['o.orderStatus'] = ['in',$orderStatus];
|
||
}else{
|
||
$where['o.orderStatus'] = $orderStatus;
|
||
}
|
||
if($orderNo!=''){
|
||
$where['orderNo'] = ['like',"%$orderNo%"];
|
||
}
|
||
if($shopName!=''){
|
||
$where['shopName'] = ['like',"%$shopName%"];
|
||
}
|
||
if($payType > -1){
|
||
$where['payType'] = $payType;
|
||
}
|
||
if($deliverType > -1){
|
||
$where['deliverType'] = $deliverType;
|
||
}
|
||
$page = $this->alias('o')->where($where)->join('__SHOPS__ s','o.shopId=s.shopId','left')
|
||
->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and refundStatus=0','left')
|
||
->join('__LOG_ORDERS__ lo','lo.orderId=o.orderId and lo.orderStatus in (-1,-3) ','left')
|
||
->join('__ORDER_GOODS__ og','og.orderId=o.orderId','left')
|
||
->field('o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,o.orderStatus,deliverType,deliverMoney,isAppraise,o.deliverMoney,lo.logContent
|
||
,payType,o.userName,o.userAddress,o.userPhone,o.orderRemarks,o.invoiceClient,o.receiveTime,o.deliveryTime,orderSrc,o.createTime,orf.id refundId,og.goodsNum,og.goodsName')
|
||
->order('o.createTime', 'desc')
|
||
->select();
|
||
if(count($page)>0){
|
||
foreach ($page as $key => $v){
|
||
$page[$key]['payTypeName'] = WSTLangPayType($v['payType']);
|
||
$page[$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
|
||
$page[$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
|
||
}
|
||
}
|
||
Loader::import('phpexcel.PHPExcel.IOFactory');
|
||
$objPHPExcel = new \PHPExcel();
|
||
// 设置excel文档的属性
|
||
$objPHPExcel->getProperties()->setCreator("WSTMart")//创建人
|
||
->setLastModifiedBy("WSTMart")//最后修改人
|
||
->setTitle($name)//标题
|
||
->setSubject($name)//题目
|
||
->setDescription($name)//描述
|
||
->setKeywords("订单")//关键字
|
||
->setCategory("Test result file");//种类
|
||
|
||
// 开始操作excel表
|
||
$objPHPExcel->setActiveSheetIndex(0);
|
||
// 设置工作薄名称
|
||
$objPHPExcel->getActiveSheet()->setTitle(iconv('gbk', 'utf-8', 'Sheet'));
|
||
// 设置默认字体和大小
|
||
$objPHPExcel->getDefaultStyle()->getFont()->setName(iconv('gbk', 'utf-8', ''));
|
||
$objPHPExcel->getDefaultStyle()->getFont()->setSize(11);
|
||
$styleArray = array(
|
||
'font' => array(
|
||
'bold' => true,
|
||
'color'=>array(
|
||
'argb' => 'ffffffff',
|
||
)
|
||
),
|
||
'borders' => array (
|
||
'outline' => array (
|
||
'style' => \PHPExcel_Style_Border::BORDER_THIN, //设置border样式
|
||
'color' => array ('argb' => 'FF000000'), //设置border颜色
|
||
)
|
||
)
|
||
);
|
||
//设置宽
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(12);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(50);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(25);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(25);
|
||
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(35);
|
||
$objPHPExcel->getActiveSheet()->getStyle('A1:S1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
|
||
$objPHPExcel->getActiveSheet()->getStyle('A1:S1')->getFill()->getStartColor()->setARGB('333399');
|
||
|
||
$objPHPExcel->getActiveSheet()->setCellValue('A1', '订单编号')->setCellValue('B1', '订单状态')->setCellValue('C1', '收货人')->setCellValue('D1', '收货地址')->setCellValue('E1', '联系方式')
|
||
->setCellValue('F1', '支付方式')->setCellValue('G1', '配送方式')->setCellValue('H1', '买家留言')->setCellValue('I1', '发票信息')->setCellValue('J1', '订单总金额')->setCellValue('K1', '运费')
|
||
->setCellValue('L1', '实付金额')->setCellValue('M1', '下单时间')->setCellValue('N1', '发货时间')->setCellValue('O1', '收货时间')->setCellValue('P1', '取消/拒收原因')->setCellValue('Q1', '商品名称')->setCellValue('R1', '商品数量');
|
||
$objPHPExcel->getActiveSheet()->getStyle('A1:P1')->applyFromArray($styleArray);
|
||
|
||
for ($row = 0; $row < count($page); $row++){
|
||
$i = $row+2;
|
||
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $page[$row]['orderNo'])->setCellValue('B'.$i, $page[$row]['status'])->setCellValue('C'.$i, $page[$row]['userName'])->setCellValue('D'.$i, $page[$row]['userAddress'])
|
||
->setCellValue('E'.$i, $page[$row]['userPhone'])->setCellValue('F'.$i, $page[$row]['payTypeName'])->setCellValue('G'.$i, $page[$row]['deliverType'])->setCellValue('H'.$i, $page[$row]['orderRemarks'])->setCellValue('I'.$i, $page[$row]['invoiceClient'])
|
||
->setCellValue('J'.$i, $page[$row]['totalMoney'])->setCellValue('K'.$i, $page[$row]['deliverMoney'])->setCellValue('L'.$i, $page[$row]['realTotalMoney'])->setCellValue('M'.$i, $page[$row]['createTime'])->setCellValue('N'.$i, $page[$row]['deliveryTime'])
|
||
->setCellValue('O'.$i, $page[$row]['receiveTime'])->setCellValue('P'.$i, $page[$row]['logContent'])
|
||
->setCellValue('Q'.$i, $page[$row]['goodsName'])->setCellValue('R'.$i, $page[$row]['goodsNum']);
|
||
}
|
||
|
||
//输出EXCEL格式
|
||
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
|
||
// 从浏览器直接输出$filename
|
||
header('Content-Type:application/csv;charset=UTF-8');
|
||
header("Pragma: public");
|
||
header("Expires: 0");
|
||
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
|
||
header("Content-Type:application/force-download");
|
||
header("Content-Type:application/vnd.ms-excel;");
|
||
header("Content-Type:application/octet-stream");
|
||
header("Content-Type:application/download");
|
||
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
|
||
header("Content-Transfer-Encoding:binary");
|
||
$objWriter->save('php://output');
|
||
}
|
||
|
||
|
||
public function addPayLog($txt){
|
||
$logOrder = [];
|
||
$logOrder['txt'] = $txt;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('pay_log')->insert($logOrder);
|
||
}
|
||
|
||
/**
|
||
* 源宝支付
|
||
*/
|
||
public function payByWallet($uId=0){
|
||
$payPwd = input('payPwd');
|
||
if(!$payPwd) return WSTReturn('密码不能为空');
|
||
// if($uId==0){// 大于0表示来自app端
|
||
// $decrypt_data = WSTRSA($payPwd);
|
||
// if($decrypt_data['status']==1){
|
||
// $payPwd = $decrypt_data['data'];
|
||
// }else{
|
||
// return WSTReturn('支付失败');
|
||
// }
|
||
// }
|
||
$key = input('key');
|
||
$key = WSTBase64url($key,false);
|
||
$base64 = new \org\Base64();
|
||
$key = $base64->decrypt($key,"WSTMart");
|
||
$key = explode('_',$key);
|
||
if(count($key)>1){
|
||
$orderNo = $key[0];
|
||
$isBatch = (int)$key[1];
|
||
}else{
|
||
$orderNo = input('orderNo');
|
||
$isBatch = (int)input('isBatch');
|
||
}
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
//判断是否开启源宝支付
|
||
$isEnbalePay = model('Payments')->isEnablePayment('wallets');
|
||
if($isEnbalePay==0)return WSTReturn('非法的支付方式',-1);
|
||
//判断订单状态
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
$orders = $this->field('orderId,orderNo,orderType,needPay,shopId,payFrom,payType,commissionFee,realTotalMoney')->where($where)->select();
|
||
if(count($orders)==0)return WSTReturn('您的订单已支付',-1);
|
||
//判断订单金额是否正确
|
||
$needPay = 0;
|
||
foreach ($orders as $v) {
|
||
$needPay += $v->needPay;
|
||
}
|
||
//获取用户钱包
|
||
$user = model('users')->get($userId);
|
||
if($user->payPwd=='')return WSTReturn('您未设置支付密码,请先设置密码',-1);
|
||
if($user->payPwd!=md5($payPwd.$user->loginSecret))return WSTReturn('您的支付密码不正确',-1);
|
||
if($needPay > $user->userMoney)return WSTReturn('您的钱包源宝不足',-1);
|
||
$userMoney = $user->userMoney;
|
||
$rechargeMoney = $user->rechargeMoney;
|
||
$sms_num = 0;
|
||
Db::startTrans();
|
||
try{
|
||
//循环处理每个订单
|
||
foreach ($orders as $order) {
|
||
//处理订单信息
|
||
$tmpNeedPay = $order->needPay;
|
||
$lockCashMoney = ($rechargeMoney>$tmpNeedPay)?$tmpNeedPay:$rechargeMoney;
|
||
$order->needPay = 0;
|
||
$order->isPay = 1;
|
||
$order->payTime = date('Y-m-d H:i:s');
|
||
$order->orderStatus = 0;
|
||
$order->payFrom = 'wallets';
|
||
$order->lockCashMoney = $lockCashMoney;
|
||
$result = $order->save();
|
||
if(false != $result){
|
||
|
||
$shop = model('shops')->get($order->shopId);
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $order->orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
|
||
//创建一条支出流水记录
|
||
$lm = [];
|
||
$lm['targetType'] = 0;
|
||
$lm['targetId'] = $userId;
|
||
$lm['dataId'] = $order->orderId;
|
||
$lm['dataSrc'] = 1;
|
||
$lm['remark'] = '交易订单【'.$order->orderNo.'】支出¥'.$tmpNeedPay;
|
||
$lm['moneyType'] = 0;
|
||
$lm['money'] = $tmpNeedPay;
|
||
$lm['payType'] = 'wallets';
|
||
model('LogMoneys')->add($lm);
|
||
//修改用户充值金额
|
||
model('users')->where(["userId"=>$userId])->setDec("rechargeMoney",$lockCashMoney);
|
||
//调用钩子 ——张开心
|
||
hook('afterOrderSettlements',['order'=>$order,'status'=>1]);
|
||
//虚拟商品处理
|
||
if($order->orderType==1){
|
||
$this->handleVirtualGoods($order->orderId);
|
||
}else{
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_HASPAY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$order->orderNo];
|
||
//WSTSendMsg($shop->userId,$msgContent,['from'=>1,'dataId'=>$order->orderId]);
|
||
$msg = array();
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$order->orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order->orderNo]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'payByWallet','');
|
||
}
|
||
}
|
||
//商家短信通知 mark hsf 20180421
|
||
if((int)WSTConf('CONF.smsOpen')==1 && WSTIsPhone($shop['telephone'])){
|
||
hook('afterOrderPay',['tplCode'=>'PHONE_SHOP_MSG','userId'=>$shop['userId'],"telephone"=>$shop['telephone'],'orderNo'=>$order['orderNo'],'orderStatus'=>0]);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_PAY','userId'=>$shop->userId,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_PAY";
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxPayOrderTip')==1){
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>3,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('订单支付成功',1);
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
// dump($e);die;
|
||
return WSTReturn('订单支付失败');
|
||
}
|
||
}
|
||
/**
|
||
* 全亮共支付
|
||
*/
|
||
public function payByQlg($uId=0){
|
||
$payPwd = input('payPwd');
|
||
// if($uId==0){// 大于0表示来自app端
|
||
// $decrypt_data = WSTRSA($payPwd);
|
||
// if($decrypt_data['status']==1){
|
||
// $payPwd = $decrypt_data['data'];
|
||
// }else{
|
||
// return WSTReturn('支付失败');
|
||
// }
|
||
// }
|
||
|
||
$key = input('key');
|
||
$key = WSTBase64url($key,false);
|
||
$base64 = new \org\Base64();
|
||
$key = $base64->decrypt($key,"WSTMart");
|
||
$key = explode('_',$key);
|
||
if(count($key)>1){
|
||
$orderNo = $key[0];
|
||
$isBatch = (int)$key[1];
|
||
}else{
|
||
$orderNo = input('orderNo');
|
||
$isBatch = (int)input('isBatch');
|
||
}
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
//判断是否开启源宝支付
|
||
$isEnbalePay = model('Payments')->isEnablePayment('qlgpay');
|
||
if($isEnbalePay==0)return WSTReturn('非法的支付方式qlg',-1);
|
||
|
||
//判断订单状态
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
|
||
$orders = $this->field('orderId,orderNo,goodsType,orderType,needPay,shopId,payFrom,commissionFee,realTotalMoney')->where($where)->select();
|
||
if(count($orders)==0)return WSTReturn('您的订单已支付',-4);
|
||
|
||
//判断订单金额是否正确
|
||
$needPay = 0;
|
||
foreach ($orders as $v) {
|
||
$needPay += $v->needPay;
|
||
}
|
||
//获取用户钱包
|
||
$user = model('users')->get($userId);
|
||
if($user->payPwd=='')return WSTReturn('您未设置支付密码,请先设置密码',-2);
|
||
if($user->payPwd!=md5($payPwd.$user->loginSecret))return WSTReturn('您的支付密码不正确',-3);
|
||
$needPay = $needPay > 0 ? $needPay : 0;
|
||
//if($needPay > $user->userECT)return WSTReturn('您的钱包ECT不足',-1);
|
||
//$userECT = $user->userECT;
|
||
// $sms_num = 0;
|
||
Db::startTrans();
|
||
try{
|
||
//循环处理每个订单
|
||
foreach ($orders as $order) {
|
||
//if($order->pay_name!=1) {
|
||
//throw new Exception("此订单不可用ECT支付");
|
||
// return WSTReturn('此订单不可用ECT支付');
|
||
//}
|
||
|
||
//处理订单信息
|
||
$tmpNeedPay = $order->needPay;
|
||
|
||
//$tmpNeedPay = $this->round($tmpNeedPay/$ect_rmb_price,2);
|
||
$order->needPay = 0;
|
||
$order->isPay = 1;
|
||
$order->payTime = date('Y-m-d H:i:s');
|
||
$order->orderStatus = 0;
|
||
$order->payFrom = 'qlgpay';
|
||
$pay = $this->getPayMoney($userId,$tmpNeedPay);
|
||
$order->productNum = $pay['product']['useProduct'];
|
||
$order->couponsNum = $pay['coupons']['useCoupons'];
|
||
$order->wangNum = $pay['wang']['useWang'];
|
||
$order->moneyNum = $pay['money']['useMoney'];
|
||
$order->productHandlingFee = isset($pay['product']['useProductHandlingFee']) ? $pay['product']['useProductHandlingFee'] : 0;//产品券手续费
|
||
$order->productTaxFee = isset($pay['product']['useProductTaxFee']) ? $pay['product']['useProductTaxFee'] : 0;//产品券税费
|
||
$order->couponsHandlingFee = isset($pay['coupons']['useCouponsHandlingFee']) ? $pay['coupons']['useCouponsHandlingFee'] : 0;
|
||
$order->couponsTaxFee = isset($pay['coupons']['useCouponsTaxFee']) ? $pay['coupons']['useCouponsTaxFee'] : 0;
|
||
$result = $order->save();
|
||
|
||
if(false != $result){
|
||
|
||
$shop = model('shops')->get($order->shopId);
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $order->orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
$nowTime = date('Y-m-d H:i:s');
|
||
//记录各个券支出
|
||
//产品券
|
||
if($order->productNum > 0){
|
||
Model('common/LogMoneys')->addMoneyLog(0,$userId,$order->orderId,1,'交易订单【'.$order->orderNo.'】支出¥'.$order->productNum,0,$order->productNum,'qlgpay',1);
|
||
}
|
||
//优惠券
|
||
if($order->couponsNum > 0){
|
||
Model('common/LogMoneys')->addMoneyLog(0,$userId,$order->orderId,1,'交易订单【'.$order->orderNo.'】支出¥'.$order->couponsNum,0,$order->couponsNum,'qlgpay',2);
|
||
}
|
||
//旺旺券
|
||
if($order->wangNum > 0){
|
||
Model('common/LogMoneys')->addMoneyLog(0,$userId,$order->orderId,1,'交易订单【'.$order->orderNo.'】支出¥'.$order->wangNum,0,$order->wangNum,'qlgpay',3);
|
||
}
|
||
//现金
|
||
if($order->moneyNum > 0){
|
||
Model('common/LogMoneys')->addMoneyLog(0,$userId,$order->orderId,1,'交易订单【'.$order->orderNo.'】支出¥'.$order->moneyNum,0,$order->moneyNum,'qlgpay',4);
|
||
//$lmm->insert($lm);//加入记录,不扣减
|
||
}
|
||
//创建一条支出流水记录
|
||
// $lm = [];
|
||
// $lm['targetType'] = 0;
|
||
// $lm['targetId'] = $userId;
|
||
// $lm['dataId'] = $order->orderId;
|
||
// $lm['dataSrc'] = 1;
|
||
// $lm['remark'] = '交易订单【'.$order->orderNo.'】支出¥'.$tmpNeedPay;
|
||
// $lm['moneyType'] = 0;
|
||
// $lm['money'] = $tmpNeedPay;
|
||
// $lm['payType'] = 'ect';
|
||
// model('LogMoneys')->add($lm);
|
||
// //插入订单支付ECT数量
|
||
// Db::name('orders_ect')->insert(['orderId'=>$order->orderId,'orderEctNum'=>$tmpNeedPay,'ectPrice'=>$ect_rmb_price]);
|
||
//虚拟商品处理
|
||
if($order->orderType==1){
|
||
// $this->handleVirtualGoods($order->orderId);
|
||
}else{
|
||
|
||
if(2 == $order->goodsType){//助微吧
|
||
$tm = Model('common/Table');
|
||
//添加已销售额
|
||
$tm->setTable('shops');
|
||
$tm->incNum(['shopId'=>$order->shopId],'helpSaleMoney',$order['realTotalMoney']);
|
||
}
|
||
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_HASPAY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$order->orderNo];
|
||
//WSTSendMsg($shop->userId,$msgContent,['from'=>1,'dataId'=>$order->orderId]);
|
||
$msg = array();
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$order->orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order->orderNo]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'payByQlg','');
|
||
}
|
||
}
|
||
//商家短信通知 mark hsf 20180421
|
||
if((int)WSTConf('CONF.smsOpen')==1 && WSTIsPhone($shop['telephone'])){
|
||
hook('afterOrderPay',['tplCode'=>'PHONE_SHOP_MSG','userId'=>$shop['userId'],"telephone"=>$shop['telephone'],'orderNo'=>$order['orderNo'],'orderStatus'=>0]);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_PAY','userId'=>$shop->userId,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_PAY";
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxPayOrderTip')==1){
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>3,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('订单支付成功,如有现金支付请上传凭证给商户。',1);
|
||
}catch (\Exception $e) {
|
||
// dump($e);
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('订单支付失败');
|
||
}
|
||
}
|
||
/**
|
||
* ECT支付
|
||
*/
|
||
public function payByEct($uId=0){
|
||
$payPwd = input('payPwd');
|
||
// if($uId==0){// 大于0表示来自app端
|
||
// $decrypt_data = WSTRSA($payPwd);
|
||
// if($decrypt_data['status']==1){
|
||
// $payPwd = $decrypt_data['data'];
|
||
// }else{
|
||
// return WSTReturn('支付失败');
|
||
// }
|
||
// }
|
||
|
||
$key = input('key');
|
||
$key = WSTBase64url($key,false);
|
||
$base64 = new \org\Base64();
|
||
$key = $base64->decrypt($key,"WSTMart");
|
||
$key = explode('_',$key);
|
||
if(count($key)>1){
|
||
$orderNo = $key[0];
|
||
$isBatch = (int)$key[1];
|
||
}else{
|
||
$orderNo = input('orderNo');
|
||
$isBatch = (int)input('isBatch');
|
||
}
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
//判断是否开启源宝支付
|
||
$isEnbalePay = model('Payments')->isEnablePayment('ect');
|
||
if($isEnbalePay==0)return WSTReturn('非法的支付方式',-1);
|
||
|
||
//判断订单状态
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
|
||
$orders = $this->field('orderId,orderNo,orderType,needPay,shopId,payFrom,commissionFee,realTotalMoney')->where($where)->select();
|
||
if(count($orders)==0)return WSTReturn('您的订单已支付',-1);
|
||
|
||
//判断订单金额是否正确
|
||
$needPay = 0;
|
||
foreach ($orders as $v) {
|
||
$needPay += $v->needPay;
|
||
}
|
||
//获取用户钱包
|
||
$user = model('users')->get($userId);
|
||
if($user->payPwd=='')return WSTReturn('您未设置支付密码,请先设置密码',-1);
|
||
if($user->payPwd!=md5($payPwd.$user->loginSecret))return WSTReturn('您的支付密码不正确',-1);
|
||
$ect_rmb_price = session('ect_rmb_price');
|
||
if($ect_rmb_price<0.05){
|
||
return WSTReturn('ECT价格出错!');
|
||
}
|
||
$needPay = $this->round($needPay/$ect_rmb_price,2);
|
||
$needPay = $needPay > 0 ? $needPay : 0;
|
||
if($needPay > $user->userECT)return WSTReturn('您的钱包ECT不足',-1);
|
||
$userECT = $user->userECT;
|
||
$sms_num = 0;
|
||
Db::startTrans();
|
||
try{
|
||
//循环处理每个订单
|
||
foreach ($orders as $order) {
|
||
//if($order->pay_name!=1) {
|
||
//throw new Exception("此订单不可用ECT支付");
|
||
// return WSTReturn('此订单不可用ECT支付');
|
||
//}
|
||
|
||
//处理订单信息
|
||
$tmpNeedPay = $order->needPay;
|
||
$tmpNeedPay = $this->round($tmpNeedPay/$ect_rmb_price,2);
|
||
$order->needPay = 0;
|
||
$order->isPay = 1;
|
||
$order->payTime = date('Y-m-d H:i:s');
|
||
$order->orderStatus = 0;
|
||
$order->payFrom = 'ect';
|
||
$result = $order->save();
|
||
if(false != $result){
|
||
|
||
$shop = model('shops')->get($order->shopId);
|
||
//新增订单日志
|
||
$logOrder = [];
|
||
$logOrder['orderId'] = $order->orderId;
|
||
$logOrder['orderStatus'] = 0;
|
||
$logOrder['logContent'] = "订单已支付,下单成功";
|
||
$logOrder['logUserId'] = $userId;
|
||
$logOrder['logType'] = 0;
|
||
$logOrder['logTime'] = date('Y-m-d H:i:s');
|
||
Db::name('log_orders')->insert($logOrder);
|
||
|
||
//创建一条支出流水记录
|
||
$lm = [];
|
||
$lm['targetType'] = 0;
|
||
$lm['targetId'] = $userId;
|
||
$lm['dataId'] = $order->orderId;
|
||
$lm['dataSrc'] = 1;
|
||
$lm['remark'] = '交易订单【'.$order->orderNo.'】支出¥'.$tmpNeedPay;
|
||
$lm['moneyType'] = 0;
|
||
$lm['money'] = $tmpNeedPay;
|
||
$lm['payType'] = 'ect';
|
||
model('LogMoneys')->add($lm);
|
||
//插入订单支付ECT数量
|
||
Db::name('orders_ect')->insert(['orderId'=>$order->orderId,'orderEctNum'=>$tmpNeedPay,'ectPrice'=>$ect_rmb_price]);
|
||
//虚拟商品处理
|
||
if($order->orderType==1){
|
||
$this->handleVirtualGoods($order->orderId);
|
||
}else{
|
||
//发送一条商家信息
|
||
$tpl = WSTMsgTemplates('ORDER_HASPAY');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${ORDER_NO}'];
|
||
$replace = [$order->orderNo];
|
||
//WSTSendMsg($shop->userId,$msgContent,['from'=>1,'dataId'=>$order->orderId]);
|
||
$msg = array();
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = ['from'=>1,'dataId'=>$order->orderId];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
|
||
//判断是否需要发送管理员短信
|
||
$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
|
||
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order->orderNo]];
|
||
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
|
||
for($i=0;$i<count($staffs);$i++){
|
||
if($staffs[$i]['staffPhone']=='')continue;
|
||
$m = new LogSms();
|
||
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'payByWallet','');
|
||
}
|
||
}
|
||
//商家短信通知 mark hsf 20180421
|
||
if((int)WSTConf('CONF.smsOpen')==1 && WSTIsPhone($shop['telephone'])){
|
||
hook('afterOrderPay',['tplCode'=>'PHONE_SHOP_MSG','userId'=>$shop['userId'],"telephone"=>$shop['telephone'],'orderNo'=>$order['orderNo'],'orderStatus'=>0]);
|
||
}
|
||
//微信消息
|
||
if((int)WSTConf('CONF.wxenabled')==1){
|
||
$params = [];
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
//WSTWxMessage(['CODE'=>'WX_ORDER_PAY','userId'=>$shop->userId,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params]);
|
||
$msg = array();
|
||
$tplCode = "WX_ORDER_PAY";
|
||
$msg["shopId"] = $order->shopId;
|
||
$msg["tplCode"] = $tplCode;
|
||
$msg["msgType"] = 4;
|
||
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
|
||
$msg["msgJson"] = "";
|
||
model("common/MessageQueues")->add($msg);
|
||
|
||
//判断是否需要发送给管理员消息
|
||
if((int)WSTConf('CONF.wxPayOrderTip')==1){
|
||
$params['ORDER_NO'] = $order->orderNo;
|
||
$params['PAY_TIME'] = date('Y-m-d H:i:s');
|
||
$params['MONEY'] = $order->realTotalMoney;
|
||
$params['PAY_SRC'] = WSTLangPayFrom($order->payFrom);
|
||
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>3,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('订单支付成功',1);
|
||
}catch (\Exception $e) {
|
||
Db::rollback();errLog($e);
|
||
return WSTReturn('订单支付失败');
|
||
}
|
||
}
|
||
/**
|
||
* 获取订单金额以及用户钱包金额
|
||
*/
|
||
public function getOrderPayInfo($obj){
|
||
$userId = (int)$obj["userId"];
|
||
$orderNo = $obj["orderNo"];
|
||
$isBatch = (int)$obj["isBatch"];
|
||
$needPay = 0;
|
||
$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
|
||
if($isBatch==1){
|
||
$where['orderunique'] = $orderNo;
|
||
}else{
|
||
$where['orderNo'] = $orderNo;
|
||
}
|
||
$orders = model('orders')->where($where)->field('needPay,payRand,shopId')->select();
|
||
if(empty($orders))return [];
|
||
$needPay = 0;
|
||
$payRand = 0;
|
||
foreach($orders as $order){
|
||
$needPay += $order['needPay'];
|
||
if($payRand<$order['payRand'])$payRand = $order['payRand'];
|
||
}
|
||
$data = array();
|
||
$data["needPay"] = $needPay;
|
||
$data["payRand"] = $payRand;
|
||
$shopId = $orders[0]['shopId'];
|
||
foreach ($orders as $_) {
|
||
if ($shopId != $_['shopId']) {
|
||
$shopId = -1;
|
||
}
|
||
}
|
||
if ($shopId>0) $data["shopId"] = $shopId;
|
||
return $data;
|
||
}
|
||
|
||
public function getOrderPayFrom($out_trade_no){
|
||
$rs = $this->where(['dataFlag'=>1,'orderNo|orderunique'=>$out_trade_no])->field('orderId,userId,orderNo,orderunique')->find();
|
||
if(!empty($rs)){
|
||
$rs['isBatch'] = ($rs['orderunique'] == $out_trade_no)?1:0;
|
||
}
|
||
return $rs;
|
||
}
|
||
/**
|
||
* 用户-提醒发货
|
||
*/
|
||
public function noticeDeliver($uId=0){
|
||
$orderId = (int)input('id');
|
||
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
|
||
Db::startTrans();
|
||
try{
|
||
$rs = $this->where(['userId'=>$userId,'orderId'=>$orderId])->setField('noticeDeliver',1);
|
||
if($rs!==false){
|
||
$info = $this->alias('o')->field('shopId,orderNo')->where(['userId'=>$userId,'orderId'=>$orderId])->find();
|
||
//发送商城消息提醒卖家
|
||
$tpl = WSTMsgTemplates('ORDER_REMINDER');
|
||
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
|
||
$find = ['${LOGIN_NAME}','${ORDER_NO}'];
|
||
$replace = [session('WST_USER.loginName'),$info['orderNo']];
|
||
|
||
$msg = array();
|
||
$msg["shopId"] = $info['shopId'];
|
||
$msg["tplCode"] = $tpl["tplCode"];
|
||
$msg["msgType"] = 1;
|
||
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
|
||
$msg["msgJson"] = [];
|
||
model("common/MessageQueues")->add($msg);
|
||
}
|
||
}
|
||
Db::commit();
|
||
return WSTReturn('提醒成功',1);
|
||
}catch(\Exception $e){
|
||
Db::rollback();errLog($e);
|
||
}
|
||
return WSTReturn('提醒失败',-1);
|
||
}
|
||
function round($num, $n=2){//保留2位小数
|
||
$result = intval($num * pow(10, $n))/ pow(10, $n);
|
||
return $result;
|
||
}
|
||
function getPayMoney($userId,$needPay){
|
||
|
||
$pay['product']['useProduct'] = 0;
|
||
$pay['coupons']['useCoupons'] = 0;
|
||
$pay['wang']['useWang'] = 0;
|
||
$pay['money']['useMoney'] = $needPay;
|
||
//实际应用最大的产品券
|
||
$userInfo = getUserInfo(['userId'=>$userId],'authType,couponsNum,productNum,wangNum');
|
||
//未认证会员不可以使用
|
||
if(0 == $userInfo['authType']) return $pay;
|
||
$pay['money']['useMoney'] = 0;
|
||
//合作认证不可以使用产品券和优惠券
|
||
if(2 == $userInfo['authType']){
|
||
$pay['product']['useProductOk'] = 0;
|
||
$pay['coupons']['useCouponsOk'] = 0;
|
||
}else{
|
||
//产品券
|
||
$buyerMaxProductScale = $this->round(dataConf('buyerMaxProductScale')*0.01,2);
|
||
$pay['maxProduct'] = $this->round($needPay * $buyerMaxProductScale,2);//最大可用产品券
|
||
$pay['productHandlingFee'] = $this->round(dataConf('useHasHandlingFee')*0.01,2);//产品券手续费
|
||
$pay['productTaxFee'] = $this->round(dataConf('useHasTaxFee')*0.01,2);//产品券税费
|
||
//获取最大可用券值
|
||
//$allProductNum = $this->getMaxNum($pay['maxProduct'],(1-$pay['productHandlingFee']-$pay['productTaxFee'] ));
|
||
$allProductNum = $this->round($pay['maxProduct'] + ($pay['maxProduct'] / (1 - $pay['productHandlingFee'] - $pay['productTaxFee'])) * ($pay['productHandlingFee']+ $pay['productTaxFee']),2);
|
||
//x*(0.2/(1-0.1-0.2));
|
||
//金额不够
|
||
if($userInfo['productNum'] < $allProductNum){
|
||
$allProductNum = $userInfo['productNum'];
|
||
|
||
//$this->round($userInfo['productNum'] + ($userInfo['productNum'] * ($pay['productHandlingFee']+ $pay['productTaxFee'])),2);
|
||
}
|
||
$pay['product']['useProduct'] = $allProductNum;//加上手续费,税费最多扣除产品券
|
||
$pay['product']['useProductHandlingFee'] = $this->round($pay['product']['useProduct'] * $pay['productHandlingFee'],2);//产品券手续费
|
||
$pay['product']['useProductTaxFee'] = $this->round($pay['product']['useProduct'] * $pay['productTaxFee'],2);
|
||
$pay['product']['useProductOk'] = $this->round($pay['product']['useProduct'] - $pay['product']['useProductHandlingFee'] - $pay['product']['useProductTaxFee'],3);
|
||
//优惠券
|
||
$pay['coupousHandlingFee'] = $this->round(dataConf('useHasHandlingFee')*0.01,2);//优惠券手续费
|
||
$pay['coupousTaxFee'] = $this->round(dataConf('useHasTaxFee')*0.01,2);//优惠券税费
|
||
$pay['maxCoupons'] = $this->round($needPay - $pay['product']['useProductOk'],2) ;//最大可用其他券,优惠券+旺旺券+现金券
|
||
//获取最大可用券值
|
||
//$allCouponsNum = $this->getMaxNum($pay['maxCoupons'],(1-$pay['coupousHandlingFee']-$pay['coupousTaxFee'] ));
|
||
$allCouponsNum = $this->round($pay['maxCoupons'] + ($pay['maxCoupons'] / (1 - $pay['coupousHandlingFee'] - $pay['coupousTaxFee'])) * ($pay['coupousHandlingFee']+ $pay['coupousTaxFee']),2);//加上手续费,税费最多扣除优惠券
|
||
//金额不够
|
||
if($userInfo['couponsNum'] < $allCouponsNum){
|
||
$allCouponsNum = $userInfo['couponsNum'];
|
||
}
|
||
//实际应用最大的优惠券
|
||
$pay['coupons']['useCoupons'] = $allCouponsNum;
|
||
$pay['coupons']['useCouponsHandlingFee'] = $this->round($pay['coupons']['useCoupons'] * $pay['coupousHandlingFee'],2);//产品券手续费
|
||
$pay['coupons']['useCouponsTaxFee'] = $this->round($pay['coupons']['useCoupons'] * $pay['coupousTaxFee'],2);
|
||
$pay['coupons']['useCouponsOk'] = $this->round($pay['coupons']['useCoupons'] - $pay['coupons']['useCouponsHandlingFee'] - $pay['coupons']['useCouponsTaxFee'],3);
|
||
}
|
||
|
||
$remNum = $this->round($needPay - $pay['product']['useProductOk'] - $pay['coupons']['useCouponsOk'],2);
|
||
if($remNum > 0 ){
|
||
//旺旺券
|
||
$pay['wang']['useWang'] = $this->round($userInfo['wangNum'] >= $remNum ? $remNum : $userInfo['wangNum'],2);
|
||
$remNum = $this->round($needPay - $pay['product']['useProductOk'] - $pay['coupons']['useCouponsOk']-$pay['wang']['useWang'],2);
|
||
if($remNum > 0 ){
|
||
$pay['money']['useMoney'] = $remNum;
|
||
}
|
||
}
|
||
return $pay;
|
||
}
|
||
/**
|
||
* 获取除去比例的最大值
|
||
* @param [type] $num [description]
|
||
* @param [type] $scale [description]
|
||
* @return [type] [description]
|
||
*/
|
||
private function getMaxNum($num,$scale){
|
||
return $this->round($num/$scale,2);
|
||
}
|
||
/**
|
||
* 获取昨日购物数据
|
||
* @param [type] $userId [description]
|
||
* @return [type] [description]
|
||
*/
|
||
function getYesterdayBuyMoney($userId,$totalField='realTotalMoney'){
|
||
Db::name('orders')->where('userId='.((int)$userId).' AND DATEDIFF(createTime,NOW())=-1')->sum($totalField);
|
||
}
|
||
}
|