namespace app\logic;
use app\library\Tools;
use think\Db;
use think\exception\DbException;
class VipLogic
{
protected $db;
public function __construct()
{
$this->db = db();
}
public function createOrder($userId, $vipPackageId)
{
$this->db->startTrans();
try{
$user = db("user")->where("user_id", $userId)->find();
if(!$user){
throw new \Exception("会员信息错误");
}
$mobile = $user["mobile"];
$package = db("vip_package")->where("vip_package_id", $vipPackageId)->where("status", 0)->find();
if(!$package){
throw new \Exception("所选会员套餐无效");
}
$packageId = $package["vip_package_id"];
$orderAmount = $package["price"];
$productName = $package["name"];
$packageDay = $package["day"];
if($package["price"] <= 0.01){
throw new \Exception("系统配置异常,暂时无法充值");
}
$orderSn = Tools::buildOrderSn();
$orderInsert = [
"order_sn" => $orderSn,
"user_id" => $userId,
"mobile" => $mobile,
"order_amount" => $orderAmount,
"order_gold" => 0,
"order_status" => 0,
"pay_channel" => 1,
"agent" => 3,
"create_at" => time(),
];
$result1 = db("order")->insert($orderInsert);
if(!$result1){
throw new \Exception("充值失败,写入订单失败");
}
$orderId = db('order')->getLastInsID();
$orderProduct = [
"order_id" => $orderId,
"user_id" => $userId,
"product_name" => $productName,
"product_desc" => '会员充值',
"product_price" => $orderAmount,
"product_type" => 1,
"product_gold" => 0,
"product_fee_type" => 0,
];
$result2 = db("order_product")->insert($orderProduct);
if(!$result2){
throw new \Exception("充值失败,写入产品失败");
}
$orderVip = [
"order_id" => $orderId,
"user_id" => $userId,
"package_id" => $packageId,
"package_name" => $productName,
"package_prcie" => $orderAmount,
"package_day" => $packageDay,
"expire_type" => 1,
"package_gold" => 0,
"status" => 0,
];
$result3 = db("order_vip")->insert($orderVip);
if(!$result3){
throw new \Exception("充值失败,写入业务失败");
}
$this->db->commit();
return $orderSn;
}catch(\Throwable $e){
$this->db->rollback();
throw new \Exception($e->getMessage());
}
}
}
事务有时候能提交有时候没反应,try catch也没有异常,有没玩tp5.0经验丰富的大神指导下。这样写有没什么问题?
最佳答案