用PHP做了一個領取優惠券活動的示例代碼

這篇文章主要介紹了用PHP做了一個領取優惠券活動的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

業務需求

優惠券活動,具體還是要根據自己的需求。以下是最近實現的優惠券活動,主要的業務需求:根據後端設置優惠券模板,用戶類型設置,優惠券活動的開始與結束時間,最後生成不同的優惠券活動鏈接。

代碼環境

源碼主要laravel5.8,一整個活動要貼的代碼很多,下面主要貼核心代碼,僅供參考。主要還是要根據自己的業務需求來實現功能吧。

以下是後端截圖,做成模塊化

前端需要做的設置與限制:

1 判斷優惠券是否存在或者停用
2 判斷活動開始時間與優惠券開始時間

接着領取活動優惠券,需要判斷以下情況:
1 活動已結束
2 活動爲開始時
3 活動爲新用戶領取,而領取的用戶是老用戶
4 活動爲老用戶領取,而領取的用戶是新用戶
5 優惠券是否領取完
6 已領取過優惠券提示
7 領取成功

下面核心代碼實現

/**
 * Function:優惠券領取處理
 * Author:cyw0413
 * @param $params
 * @return array
 * @throws \Exception
 */
public function doCoupon($params)
{
  $activity_id = $params['activity_id'];
  if(!$params){
    throw new \Exception("參數錯誤!");
  }

  $preg_phone = '/^1[34578]\d{9}$/ims';
  $is_mobile = preg_match ($preg_phone, $params['mobile']);
  if ($is_mobile == 0) {
    throw new \Exception("手機號碼不正確!");
  }

  //隱藏手機號碼中間4位
  $str_mobile = substr_replace($params['mobile'],'****',3,4);

  $activity = $this->find($activity_id);
  if(empty($activity)){
    throw new \Exception("不存在此活動");
  }

  $activity_link = $activity->activityLink->where('coupon_status',0); //只選擇不停用的優惠券
  if(count($activity_link) <= 0){
    throw new \Exception("優惠券不存在或者已經停用");

  }else{

    //查找註冊用戶ID
    $showUser = $this->showUser($params['mobile']);
    //主要是過濾掉領取優惠券爲0的,用laravel的同學注意看看
    $detail = $activity_link->each(function($item,$index) use ($showUser) {

      $diffCouponQuantity = $this->diffCouponQuantity($item['config_id'],$item['quantity'],$item['activity_id'],$showUser);
      $item->title = $this->getCouponName($item['config_id'])['name'];
      $item->number = $item['quantity'];
      $item->msg  = $diffCouponQuantity ['msg'];
      $item->diff   = $diffCouponQuantity ['diff'];
      $item->code   = $diffCouponQuantity ['code'];
    })->toArray();

    if(count($detail) == 1){
      foreach($detail as $val){
        if($val['diff'] == 1 && $val['code'] == '400'){
          throw new \Exception($detail[0]['msg']);
        }
      }

    }

    $collection_coupon = collect($detail);
    $collection_coupon = $collection_coupon->where('diff', '<=' ,'0');  //去除優惠券剩餘數量爲0,或者領取優惠券數量-剩餘數量 > 0

  }
  //判斷活動開始時間與優惠券開始時間
  $act_coupon = ActivityCouponBaseModel::where('activity_id',$activity['activity_id'])->first();
  $check_time = $this-> checkCouponTime($act_coupon['start_time'],$activity_link);
  if($check_time == 'error'){
    throw new \Exception("優惠券領取時間未開始,暫不可領取");
  }

  //領取活動有以下幾種情況
  //1: 活動已結束
  if($activity['end_time'] < date("Y-m-d H:i:s") || $activity['status'] == 1){
    $result = [
      'code' => 1,
    ];
    return $result;
  }

  //6 活動爲開始時
  if($activity['start_time'] > date("Y-m-d H:i:s") || $activity['status'] == 1){
    $result = [
      'code' => 6,
    ];
    return $result;

  }

  $checkUser = $this->haveUser($params['mobile']); //檢查是新用戶,還是老用戶 根據自己的業務需求做,這個方法就不貼了
  //2: 活動爲新用戶領取,而領取的用戶是老用戶
  if($activity['user_type'] == 1 && !empty($checkUser)){
    $result = [
      'code' => 2,
    ];
    return $result;
  }

  //3:活動爲老用戶領取,而領取的用戶是新用戶
  if($activity['user_type']==2 && empty($checkUser)){
    $result = [
      'code' => 3,
    ];
    return $result;
  }


  //4:優惠券是否領取完
  $coupon = $this->getCouponExpire($collection_coupon,$params['mobile']); //這裏提示有一個優惠券列表,根據自己的業務需求做,這個方法就不貼了
  //return $coupon;
  if($coupon == 1){
    $result = [
      'code' => 4,
    ];
    return $result;
  }

  //5:已領取過優惠券提示
  $userCoupon = '';
  $userRate = '';
  if(!empty($checkUser)){
    //user存在則爲老用戶,再檢查是否領取過
    $userCoupon = $this->getUserCoupon($collection_coupon,$checkUser['user_id']);
    $userRate = $this->getUserCouponRate($checkUser['user_id'],$activity['activity_id']);
  }else{
    //新用戶,檢查是否註冊過
    $var_user = UserBaseModel::where('user_name',$params['mobile'])->first();
    if(!empty($var_user)){
      $userCoupon = $this->getUserCoupon($collection_coupon,$var_user['user_id']);
      $userRate = $this->getUserCouponRate($var_user['user_id'],$activity['activity_id']);
    }
  }

  //return $userRate;

  if($userCoupon == 1){
    $result = [
      'code' => 5,
      'phone'=> $str_mobile,
      'coupon' => $userRate,
      'is_get' => false,
    ];
    return $result;
  }

  //5:領取成功
  //如果活動規定是新老用戶0,新用戶1,老用戶2
  $getCouponSuccess = $this->getCouponSuccess($activity['user_type'],$checkUser,$collection_coupon,$params['mobile']);
  //return $getCouponSuccess;
  if($getCouponSuccess['status'] == 200){
    $result = [
      'code' => 5,
      'phone'=> $str_mobile,
      'coupon' => $getCouponSuccess['result'][0],
      'is_get' => true,
    ];
    return $result;
  }


}

用戶領取優惠券併發放優惠券

/**
 * 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;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章