用PHP做了一个领取优惠券活动的示例代码(2)
用户领取优惠券并发放优惠券
/** * Function:用户领取活动 * Author:cyw0413 * @param $user_type */ public function getCouponSuccess($user_type,$user,$coupon,$mobile) { if(count($coupon) > 0){ switch ($user_type){ case 1: //新用户领取,如果从来没注册过就要新增用户 $res = $this->addUser($mobile,$coupon); return [ 'result' => $res, 'status' => 200 ]; break; case 2: //老用户领取 $res = $this->insertUserCoupon($user,$coupon); return [ 'result' => $res, 'status' => 200 ]; break; default: //新老用户领取,判断是新用户还是老用户,这里的$user是有无配送单,有则为老用户; if(empty($user)){ $res = $this->addUser($mobile,$coupon); }else{ $res = $this->insertUserCoupon($user,$coupon); //老用户,直接发放优惠券 } return [ 'result' => $res, 'status' => 200 ]; break; } }else{ throw new \Exception("优惠券不存在或者已经停用"); } }
领取成功,则发放优惠券
/** * Function:发放优惠券 * Author:cyw0413 * @param $user * @param $coupon */ public function insertUserCoupon($user,$coupon) { $relate = []; foreach($coupon as $item){ $res = CouponConfigSendBaseModel::where([ 'config_id'=>$item['config_id'], 'status' => 0, ])->first(); if(empty($res) || (!empty($res) && $res['is_send'] == 0) ){ throw new \Exception("优惠券未发放,暂不可领取"); } //发放优惠券,有多少张就添加多少张,这里扣除优惠券时,主要用不同的coupon_sn来区别 $onlyCoupon = $this->getCouponName($item['config_id']); if ($onlyCoupon['expire_type'] == 0) { $start_time = $onlyCoupon['expire_start_time']; $end_time = $onlyCoupon['expire_end_time']; } else { $start_time = date('Y-m-d H:i:s'); $end_time = date('Y-m-d H:i:s', time()+86400*$onlyCoupon['expire_type']); } $result = [ 'user_id' => $user['user_id'], 'config_id' => $item['config_id'], 'name' => $onlyCoupon['name'], 'get_type' => $onlyCoupon['get_type'], 'amount' => $onlyCoupon['amount'], 'require_price' => $onlyCoupon['require_price'], 'status' => 1, 'start_time' => $start_time, 'end_time' => $end_time, ]; for($i=0; $i < $item['quantity'];$i++){ $result['coupon_sn'] = 'B'.mt_rand(1, 10000) . strtoupper(uniqid(mt_rand(1, 10000))); $userCoupon = UserCouponBaseModel::create($result); } //扣除相应的优惠券数量,这里用到了锁表,防止并发时,优惠券为-1 $couponConfig = CouponConfigBaseModel::where('config_id',$item['config_id'])->lockForUpdate()->first(); if($couponConfig->left_quantity > 0 ){ if($couponConfig->left_quantity >= $item['quantity']){ $couponConfig->left_quantity = $couponConfig->left_quantity-$item['quantity']; $couponConfig->save(); }else{ throw new \Exception("优惠券剩余数量不够扣减"); } } $relate = [ 'coupon_id' => $userCoupon->coupon_id, 'user_id' => $user['user_id'], 'config_id' => $item['config_id'], 'activity_id' => $item['activity_id'] ]; ActivityCouponUserRelateBaseModel::create($relate); $relate[] = $this->getUserCouponRate($user['user_id'],$item['activity_id']); } return $relate; }
内容版权声明:除非注明,否则皆为本站原创文章。