1017 lines
34 KiB
PHP
Raw Normal View History

<?php
namespace app\common\model\school\activity\order;
use addons\epay\library\Service;
use app\common\model\BaseModel;
use app\common\model\school\activity\Activity;
use app\common\model\school\activity\Refund;
use app\common\model\User;
use bw\Common;
use fast\Random;
use think\Cache;
use think\Model;
use traits\model\SoftDelete;
class Order extends BaseModel
{
use SoftDelete;
// 表名
protected $name = 'school_activity_order';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'integer';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = 'deletetime';
// 追加属性
protected $append = [
'pay_type_text',
'status_text',
'before_status_text',
'server_status_text',
'canceltime_text',
'paytime_text',
'auth_time_text',
'reservation_time_text',
'finishtime_text',
'refundtime_text',
'auth_status_text',
'refundsendtime_text'
];
public function getPayTypeList()
{
return ['yue' => __('Pay_type yue'), 'wechat' => __('Pay_type wechat')];
}
public function getStatusList()
{
return ['-3' => __('Status -3'), '0' => __('Status 0'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '5' => __('Status 5'), '6' => __('Status 6'), '9' => __('Status 9')];
}
public function getBeforeStatusList()
{
return ['-3' => __('Before_status -3'), '0' => __('Before_status 0'), '2' => __('Before_status 2'), '3' => __('Before_status 3'), '4' => __('Before_status 4'), '6' => __('Before_status 6'), '9' => __('Before_status 9')];
}
public function getServerStatusList()
{
return ['0' => __('Server_status 0'), '3' => __('Server_status 3'), '6' => __('Server_status 6')];
}
public function getAuthStatusList()
{
return ['0' => __('Auth_status 0'), '1' => __('Auth_status 1'), '2' => __('Auth_status 2')];
}
public function getPayTypeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
$list = $this->getPayTypeList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getStatusTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
$list = $this->getStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getBeforeStatusTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['before_status']) ? $data['before_status'] : '');
$list = $this->getBeforeStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getServerStatusTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['server_status']) ? $data['server_status'] : '');
$list = $this->getServerStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getCanceltimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getPaytimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getAuthTimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['auth_time']) ? $data['auth_time'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getReservationTimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['reservation_time']) ? $data['reservation_time'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getFinishtimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['finishtime']) ? $data['finishtime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getRefundtimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['refundtime']) ? $data['refundtime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getAuthStatusTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['auth_status']) ? $data['auth_status'] : '');
$list = $this->getAuthStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
public function getRefundsendtimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['refundsendtime']) ? $data['refundsendtime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
protected function setCanceltimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setPaytimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setAuthTimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setReservationTimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setFinishtimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setRefundtimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
protected function setRefundsendtimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
public function user()
{
return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
public function activity()
{
return $this->belongsTo(Activity::class, 'activity_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
public function detail()
{
return $this->belongsTo(OrderDetail::class, 'activity_order_detail_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
public function ordercode()
{
return $this->hasMany(OrderCode::class,'activity_order_id');
}
/**得到基础条件
* @param $status
* @param null $model
* @param string $alisa
*/
public static function getBaseWhere($whereData = [], $model = null, $alisa = '',$with = false)
{
if (!$model) {
$model = new static;
if ($alisa&&!$with) $model = $model->alias($alisa);
}
if ($alisa) $alisa = $alisa . '.';
$tableFields = (new static)->getTableFields();
foreach ($tableFields as $fields)
{
if(in_array($fields, ['status',"auth_status","server_status",'activity_id','user_id','activity_order_detail_id']))continue;
// if (isset($whereData[$fields]) && $whereData[$fields]) $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
if (isset($whereData[$fields]) && $whereData[$fields]){
if(is_array($whereData[$fields])){
$model = $model->where("{$alisa}{$fields}", $whereData[$fields][0], $whereData[$fields][1]);
}else{
$model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
}
}
}
if (isset($whereData['status'])) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
if (isset($whereData['not_status'])) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);
if (isset($whereData['server_status']) && $whereData['server_status']!=="") $model = $model->where("{$alisa}server_status", 'in', $whereData['server_status']);
if (isset($whereData['not_server_status'])&& $whereData['not_server_status']!=="") $model = $model->where("{$alisa}server_status", 'not in', $whereData['not_server_status']);
if (isset($whereData['auth_status']) && $whereData['auth_status']!=="") $model = $model->where("{$alisa}auth_status", 'in', $whereData['auth_status']);
if (isset($whereData['not_auth_status'])&& $whereData['not_auth_status']!=="") $model = $model->where("{$alisa}auth_status", 'not in', $whereData['not_auth_status']);
if (isset($whereData['keywords'])&&$whereData['keywords']){
$model = $model->where("{$alisa}order_no|{$alisa}pay_no|user.nickname|user.realname|user.mobile|detail.title|detail.address|detail.address_detail", 'LIKE', "%{$whereData['keywords']}%" );
}
if (isset($whereData['time'])&&$whereData['time']){
$model = $model->time(["{$alisa}createtime",$whereData['time']]);
}
if (isset($whereData['user_id']) && $whereData['user_id']) $model = $model->where("{$alisa}user_id", '=', $whereData['user_id']);
if (isset($whereData['activity_ids']) && $whereData['activity_ids']) $model = $model->where("{$alisa}activity_id", 'in', $whereData['activity_ids']);
if (isset($whereData['activity_id']) && $whereData['activity_id']) $model = $model->where("{$alisa}activity_id", 'in', $whereData['activity_id']);
if (isset($whereData['activity_order_detail_id']) && $whereData['activity_order_detail_id']) $model = $model->where("{$alisa}activity_order_detail_id", 'in', $whereData['activity_order_detail_id']);
// if (isset($whereData['has_evaluate'])&&$whereData['has_evaluate']){
// //1查已评价 2查未评价
// if($whereData['has_evaluate'] == 1){
// //1查已评价
// $model = $model->where("{$alisa}classes_evaluate_id", '<>', 0);
// }else{
// //2查未评价
// $model = $model->whereExists(function ($query) use ($alisa) {
// $order_table_name = (new \app\common\model\school\classes\hourorder\Order())->getQuery()->getTable();
// $query->table($order_table_name)->where($order_table_name . '.classes_order_id=' . $alisa . 'id')->where('status', '=', '3');
// })->where("{$alisa}classes_evaluate_id", '=', 0);
//
// }
// }
return $model;
}
public static function allList($user_id,$page, $limit,$keywords,$status,$activity_id=[],$has_evaluate=0,$server_status="",$params=[]){
$with_field = [
'user'=>['nickname','mobile','avatar','realname'],
'base'=>['*'],
'detail'=>['*'],
'ordercode'=>['*'],
];
$CANCEL = '-3';
$NOPAY = '0';
$PAYED = '2';
$RESERV = '3';
$REFUND = '6';
$FINISH = '9';
$IN_SERVICE = '4';
$IN_REFUND = '5';
$alisa = (new self)->getWithAlisaName();
$sort = "field({$alisa}.status,'{$NOPAY}','{$PAYED}','{$RESERV}','{$FINISH}','{$REFUND}','{$IN_SERVICE}','{$CANCEL}' ,'{$IN_REFUND}') asc,{$alisa}.id desc";
$serch_where = ['status'=>$status,'user_id'=>$user_id,'keywords'=>$keywords,"activity_id"=>$activity_id,"has_evaluate"=>$has_evaluate,"server_status"=>$server_status];
// if($type)$serch_where['type'] = $type;
return (new self)->getBaseList(array_merge($serch_where,$params), $page, $limit,$sort,$with_field);
}
public static function baseCount($where = []){
$CANCEL = '-3';
$NOPAY = '0';
$PAYED = '2';
$RESERV = '3';
$REFUND = '6';
$FINISH = '9';
$IN_SERVICE = '4';
$IN_REFUND = '5';
$cancel_number = self::getBaseWhere(array_merge(['status'=>$CANCEL],$where))->count();
$nopay_number = self::getBaseWhere(array_merge(['status'=>$NOPAY],$where))->count();
$payed_number = self::getBaseWhere(array_merge(['status'=>$PAYED],$where))->count();
$reserv_number = self::getBaseWhere(array_merge(['status'=>$RESERV],$where))->count();
$retund_number = self::getBaseWhere(array_merge(['status'=>$REFUND],$where))->count();
$in_retund_number = self::getBaseWhere(array_merge(['status'=>$IN_REFUND],$where))->count();
$finish_number = self::getBaseWhere(array_merge(['status'=>$FINISH],$where))->count();
$in_service_number = self::getBaseWhere(array_merge(['status'=>$IN_SERVICE],$where))->count();
return compact('cancel_number','nopay_number','payed_number','in_service_number','retund_number','in_retund_number','finish_number','reserv_number');
}
/**订单数量统计
* @param int $user_id
* @return array
*/
public static function orderCount($user_id = 0,$activity_id=[],$params=[]){
return self::baseCount(array_merge(['user_id'=>$user_id,"activity_id"=>$activity_id],$params));
}
public static function workList($user_id,$page, $limit,$keywords,$status,$activity_id=[],$activity_ids=[],$has_evaluate=0,$server_status="",$params=[]){
if(!$activity_ids) $activity_ids = [-5];
$with_field = [
'user'=>['nickname','mobile','avatar','realname'],
'base'=>['*'],
'detail'=>['*'],
'ordercode'=>['*'],
];
$CANCEL = '-3';
$NOPAY = '0';
$PAYED = '2';
$RESERV = '3';
$REFUND = '6';
$FINISH = '9';
$IN_SERVICE = '4';
$IN_REFUND = '5';
$alisa = (new self)->getWithAlisaName();
$sort = "field({$alisa}.status,'{$NOPAY}','{$PAYED}','{$RESERV}','{$FINISH}','{$REFUND}','{$IN_SERVICE}','{$CANCEL}','{$IN_REFUND}') asc,{$alisa}.id desc";
$serch_where = ['status'=>$status,'keywords'=>$keywords,"activity_id"=>$activity_id,"activity_ids"=>$activity_ids,"server_status"=>$server_status];
// if($type)$serch_where['type'] = $type;
return (new self)->getBaseList(array_merge($serch_where,$params), $page, $limit,$sort,$with_field);
}
/**订单数量统计
* @param int $user_id
* @return array
*/
public static function workCount($activity_id=[],$activity_ids=[],$params=[]){
if(!$activity_ids) $activity_ids = [-5];
return self::baseCount(array_merge(["activity_id"=>$activity_id,"activity_ids"=>$activity_ids],$params));
}
/**得到订单详情
* @param $order_no
*/
public static function getDetail($order_no,$activity_id = []){
$model = self::where('order_no|id|pay_no',$order_no);
if($activity_id)$model = $model->where("activity_id","in",$activity_id);
$data = $model->find();
if(!$data) return $data;
//加载订单详情
$data->detail;
//订单用户
// $data->user;
$data->user->visible(['id','nickname','mobile','avatar','realname']);
//规格信息
$data->ordercode;
return $data;
}
/**展示订单信息
* @param $order_no
* @param $price_info
* @return array
*/
public static function showInfo($order_no, $price_info = []){
$data = [];
$data['order_no'] =$order_no;
$data['order_info'] = self::getDetail($order_no);
return array_merge($data,$price_info);
}
/**得到订单
* @param $order_no
* @return array|false|\PDOStatement|string|Model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function getOrder($order_no){
$order = self::where('order_no|id|pay_no',$order_no)->find();
if(!$order)throw new \Exception("订单不存在");
return $order;
}
/**
* 设置订单缓存
* @param $uid
* @param $data
* @return bool
*/
public static function setOrderCache($uid, $data)
{
//缓存名 = uid + order_no
$cacheNmae = 'activity_order_cache' . $uid . $data['order_no'];
// 缓存在3600秒之后过期
return Cache::set($cacheNmae, $data, config("site.unpaid_activity_expire_time"));
}
/**
* 得到订单缓存
* @param $uid
* @param $order_no
* @return mixed
*/
public static function getOrderCache($uid, $order_no)
{
//缓存名 = uid + order_no
$cacheNmae = 'activity_order_cache' . $uid . $order_no;
// 缓存在3600秒之后过期
return Cache::get($cacheNmae);
}
/**
* 删除订单缓存
* @param $uid
* @param $order_no
* @return mixed
*/
public static function deleteOrderCache($uid, $order_no)
{
//缓存名 = uid + order_no
$cacheNmae = 'activity_order_cache' . $uid . $order_no;
// 缓存在3600秒之后过期
return Cache::rm($cacheNmae);
}
/**订单校验
* @param $user_id 用户id
* @param $classes_lib_id 课程id
* @param $order_no 订单号
* @param $param 表单扩展参数
* @return bool
*/
public function orderVaild($user_id,$activity_id,$num, $order_no, $param,$check=false){
if(!$user_id||!$activity_id )throw new \Exception("缺少必要参数");
//更新活动状态
(new Activity)->updateStatus($activity_id);
//校验订单参数
//课程活动是否存在并上架
$activity = Activity::where('id',$activity_id)->find();
if(!$activity || $activity['status']!='2' || $activity['auth_status']!='1') throw new \Exception("该活动不在可报名时间段!");
//默认校验订单是否已创建
if($check){
//此为创建订单时判断
//判断订单是否已创建
$order_info = self::where(['order_no'=>$order_no])->find();
if($order_info) throw new \Exception("订单已生成,如需重新下单请退出页面重新进入!");
//下单必须传规格id
$num = (int)$num;
if(!$num) throw new \Exception("请选择报名人数!");
$activity_max_people = config("site.activity_max_people");
if($activity_max_people){
if($num > $activity_max_people || $num < 1) throw new \Exception("单次报名人数不能超过{$activity_max_people}人!");
}
//判断数量是否超出库存
$sale = Activity::activitySale($activity_id,$num);//活动销量
if($sale > $activity['stock']){
//判断超了几人
$sub = $sale - $activity['stock'];
throw new \Exception("活动人数已超{$sub}人!无法下单!");
}
}
//用户存不存在
$user_info = User::where('id',$user_id)->find();
if(!$user_info) throw new \Exception("用户不存在!");
return true;
}
public static function getCost($user_id,$activity_id,$num=1,$param=[],$other_params=[],$check = false){
//用户
$user_info = User::get($user_id);
$user_data = [
"nickname"=>$user_info["nickname"],
"realname"=>$user_info["realname"],
"avatar"=>$user_info["avatar"],
"mobile"=>$user_info["mobile"],
"money" =>$user_info["money"],
"score" =>$user_info["score"],
];
//课程
$activity_info = Activity::get($activity_id);
$activity_info = $activity_info->toArray();
$activity_info["activity_id"] = $activity_id;
$activity_info["activity_order_id"] = 0;
$activity_info["refund_scale_json"] = "";
$activity_info["refund_status"]= "1";
$refund = Refund::get($activity_info["refund_id"]);
if($refund){
$activity_info["refund_scale_json"]= $refund["refund_scale_json"];
$activity_info["refund_status"]= $refund["refund_status"];
}
// $activity_info['use_num'] = 0;//已使用课时
// $activity_info['sub_num'] = $activity_info['classes_num'];//剩余课时
// //单价 = 课程价格/总课时
// $activity_info["unit_price"] = bcdiv($activity_info['price'],$activity_info['classes_num'],2);
// $activity_info["used_price"] = 0;
$totalprice = bcmul($num,$activity_info["price"],2);
//组装订单下单数据
$order_data = [];
$order_data["user_id"] = $user_id;
$order_data["activity_id"] = $activity_id;
$order_data["activity_order_detail_id"] = 0;
$order_data["num"] = $num;
$order_data["fee_scale"] = $activity_info["fee_scale"];
$order_data["beforeprice"] = $totalprice;
$order_data["totalprice"] = $totalprice;
$order_data["payprice"] = 0;
$order_data["status"] = '0';
return compact('order_data','activity_info','user_data',"num");
}
/** 订单确认(订单计算)
* @param $user_id 下单用户
* @param $order_no 订单号(缓存标识)
* @param $activity_id 課程活动id
* @param $num 人数
* @param $param 額外参数(扩展用)
* @param bool $is_compute 是否重新计算订单
* @return array
*/
public function confirm($user_id, $activity_id,$num,$order_no,$param=[], $is_compute = false)
{
if ($order_no && !$is_compute) {
//得到缓存
$data = self::getOrderCache($user_id, $order_no);
if (!$data) throw new \Exception('请您完善参加信息!');
$price_info = $data['price_info'];
} else {
//订单信息计算
// if(!$param) throw new \Exception('缺少必要信息');
$this->orderVaild($user_id,$activity_id,$num,$order_no, $param);
//订单支付信息
$price_info = $this->getCost($user_id,$activity_id,$num,$param);
//生成订单号
if (!$order_no) $order_no = get_order_sn();
//生成缓存
$data = compact('user_id', 'activity_id','num','param', 'order_no', 'price_info');
self::setOrderCache($user_id, $data);
}
\think\Hook::listen('activity_order_create_before', $data);
//下单数据展示
return $this->showInfo($order_no, $price_info);
}
/**得到待支付订单
* @param $order_no
* @return array|false|\PDOStatement|string|Model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function getNopayOrder($order_no){
$order = self::where('order_no|id|pay_no',$order_no)->where("status",'0')->find();
if(!$order)throw new \Exception("待支付订单不存在");
return $order;
}
/**调用订单支付成功事件
* @param $order_no
* @param $pay_type
* @param $price
* @param $price_check
* @param bool $trans
* @return bool
* @throws \Exception
*/
public function paySuccess($order_no,$notify=[],$price=0,$price_check=false,$trans=false){
$order = self::getNopayOrder($order_no);
//金额校验 :第三方支付时回调入口判断
if($price_check){
if(bccomp($price,$order['totalprice'])==-1)throw new \Exception("支付金额与订单需要支付金额对应不上,回调失败!");
}
//判断逻辑
if($trans){
self::beginTrans();
}
$res = true;
try{
//事务逻辑
//不拆分订单,直接执行
self::paySetData($order,$notify);
// //如果需要快捷预约
// $classes_lib_spec_id = $order['classes_lib_spec_id'];
// if($classes_lib_spec_id){
// //记录代下单人信息
// $param = [
// "type" =>'2',
// "help_user_id" =>$order["user_id"] ,
// "help_type" => 'admin',
// ];
//
// //确认订单
// $res = (new \app\common\model\school\classes\hourorder\Order)->confirm($order["user_id"],$order['id'],null, $classes_lib_spec_id,$param, true);
// $remark = "订单支付完成同时快捷预约一个课时";
// //创建订单
// $result = (new \app\common\model\school\classes\hourorder\Order)->cacheCreateOrder($res['order_no'], $order["user_id"],$remark);
//
// }
if($trans){
self::commitTrans();
}
}catch (\Exception $e){
if($trans){
self::rollbackTrans();
}
throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
}
return $res;
}
public static function updatePay($order,$notify=[]){
if(is_string($order)||is_numeric($order))$order = self::getNopayOrder($order);
$order->status ='2';
$order->paytime = time();
$order->pay_no = $notify['transaction_id'] ?? null;
$order->pay_json = $notify['payment_json'] ?? '{}';
$order->pay_type = $notify['pay_type'] ?? 'yue';
//如果订单创建时间大于预约时间,则等于预约时间
// if($order['createtime']>$order['starttime'])$order['createtime'] = $order['starttime'];
switch ($order->pay_type) {
case "offline": //线下付款,线上不需要支付
break;
default:
$order->payprice = $notify['pay_fee'] ?? $order->totalprice;
}
$order->platform = $notify['platform'] ?? 'miniapp';
$order->sub_refundprice = $order->payprice; //剩余未退 = 支付金额
$order->save();
return $order;
}
public static function paySetData($order,$notify=[]){
//订单支付更新
$order = self::updatePay($order,$notify);
//生成订单一维码和二维码
$order = self::buildCode($order);
//记录订单日志
OrderLog::log($order['id'],"活动订单支付成功,核销码生成,等待核销",'user',$order['user_id']);
//调用支付成功事件
$data = ['order' => self::where("id",$order['id'])->find()];
\think\Hook::listen('activity_order_payed_after', $data);
//更新订单数据
self::statisticsAndUpdateClassesNumber($order);
return true;
}
public static function buildCode($order){
if(is_string($order)||is_numeric($order))$order = self::getNopayOrder($order);
$num = $order['num'];
for ($i=0;$i<$num;$i++){
$params = [
"activity_order_id"=>$order["id"],
"status" =>'3',
"activity_id"=>$order['activity_id'],
];
$orderCode = OrderCode::create($params);
$orderCode["code"] = en_code($orderCode["id"]);
$orderCode["miniurl"] = self::getMiniQrcodeLink(["order_id"=>$order['id'],"code"=>$orderCode["code"]]);
//生成核销二维码和一维码
// //生成二维码和一维码
// //二维码
// $orderCode->codeimage = (Common::getQrcode([
// 'text' => $orderCode["miniurl"],
// 'size' => 200,
// ]))['url'];
// //一维码
// $orderCode->codeoneimage = (Common::getBarcode([
// 'text' => $orderCode["miniurl"],
// 'size' => 200,
// ]))['url'];
$orderCode->save();
}
return $order;
}
public static function getPath($params=[],$expression = '{{KEYWORD}}'){
$path = config("site.activity_verification_url");
if(!$path) throw new \Exception("请先配置小程序路径");
// 参数替换
$template = Common::parsePrintTemplateString($path,$params,$expression);
return $template;
}
public static function getMiniQrcodeLink($params=[],$expression = '{{KEYWORD}}',$qrcode=false){
$path = self::getPath($params,$expression);
//如果路径开头有斜杠则去除
if(substr($path,0,1) == "/"){
$path = substr($path,1);
}
//解析该路径获取url参数和除去参数的url
$url_params = [];
$url = "";
if(strpos($path,"?") !== false){
$url_params = explode("?",$path);
$url = $url_params[0];
$url_params = $url_params[1];
}else{
$url = $path;
}
$q_params = [];
//生成小程序二维码
$query = $url_params;
$q_params["path"] = $url;
if($query)$q_params["query"] = $query;
// 实例对应的接口对象
$scheme = new \WeMini\Scheme(Service::wechatConfig());
$res= $scheme->urlLink($q_params);
if(!isset($res["url_link"]))throw new \Exception("生成小程序二维码失败");
$url_link = $res["url_link"];
if(!$qrcode)return $url_link;
//链接生成二维码
//二维码
$response = Common::getQrcode([
'text' => $url_link,
'size' => 200,
],false,false,true);
//全返回
return compact("url_link","response");
}
/**
* 根据缓存创建订单
*/
public function cacheCreateOrder($order_no, $user_id,$remark="", $trans = false)
{
//得到缓存
$orderInfo = self::getOrderCache($user_id, $order_no); //得到下单信息
if (!$orderInfo) throw new \Exception('请您完善预约信息');
if ($trans) {
self::beginTrans();
}
try {
//'classes_activity_id','classes_activity_item_id'
//1订单执行创建
$order = $this->createOrder($user_id,$orderInfo['activity_id'],$orderInfo['num'],$order_no,$orderInfo['param'],$remark);
$orderitem = $order->detail;
//如果是免费订单,则直接调用支付完成
if ($orderitem['feel'] == '1' || $order['totalprice'] == 0) {
//调用订单支付成功事件
$this->paySuccess($order_no,['platform'=>"miniapp",'pay_type'=>'yue']);
}
//5删除缓存
self::deleteOrderCache($user_id, $order_no);
if ($trans) {
self::commitTrans();
}
} catch (\Exception $e) {
if ($trans) {
self::rollbackTrans();
}
throw new \Exception($e->getMessage().$e->getFile() . $e->getLine());
}
return self::showInfo($order_no);
}
public function createOrder($user_id,$activity_id,$num,$order_no,$param,$remark='',$other_params=[]){
$this->orderVaild($user_id,$activity_id,$num, $order_no, $param,true);
//订单支付信息
$order_info = self::getCost($user_id,$activity_id,$num,$param,$other_params,true);
//组装订单数据 compact('order_data','activity_info','user_data',"activity_info");
$order_data = $order_info['order_data'];
$order_data["order_no"] = $order_no;
$res1 = self::create($order_data);
if (!$res1) throw new \Exception('创建订单失败');
$activity_info = $order_info["activity_info"];
if(!$activity_info)throw new \Exception('订单未选活动!');
//課程详情
$activity_info = $order_info['activity_info'];
$order_detail_data = [];
$order_detail_data = array_merge($order_detail_data,$activity_info);
$order_detail_data["activity_id"] = $activity_info['id'];
$order_detail_data["activity_order_id"] = $res1['id'];
unset($order_detail_data['id']);
unset($order_detail_data['createtime']);
$orderDetail = (new OrderDetail());
$orderDetail->allowField(true)->save($order_detail_data);
// $order_item_data = [];
// $order_item_data = array_merge($order_item_data,$classes_activity_item->toArray());
// $order_item_data["classes_activity_item_id"] = $classes_activity_item['id'];
// $order_item_data["classes_activity_order_id"] = $res1['id'];
//
// unset($order_item_data['id']);
// unset($order_item_data['createtime']);
// $orderItem = (new OrderItem());
// $orderItem->allowField(true)->save($order_item_data);
//更新订单详情id
$res1->activity_order_detail_id = $orderDetail->id;
$res1->save();
//记录订单日志
OrderLog::log($res1['id'],"活动订单创建成功,等待下一步操作(如果付费需去支付)",'user',$user_id);
//7事件
$data = ['order' => self::where("id",$res1['id'])->find()];
\think\Hook::listen('activity_order_create_after', $data);
//更新订单数据
self::statisticsAndUpdateClassesNumber($res1);
return $res1;
}
//统计并更新活动数等相关统计数据
public static function statisticsAndUpdateClassesNumber($order){
if(is_string($order)||is_numeric($order))$order = self::getOrder($order);
// $detail = $order->detail;
// if(!$detail)throw new \think\Exception("订单信息缺失!");
//
// //课程下单时已核销人数更新
// $lib = $order->activity;
// if($lib){
//
// }
//将课程信息和课时信息同步到所有已下单的订单信息中
Activity::update_classes($order["activity_id"]);
//如果有评价执行评价更新
return $order;
}
}