用PHP做了一个领取优惠券活动的示例代码


Posted in PHP onJuly 05, 2019

业务需求

优惠券活动,具体还是要根据自己的需求。以下是最近实现的优惠券活动,主要的业务需求:根据后端设置优惠券模板,用户类型设置,优惠券活动的开始与结束时间,最后生成不同的优惠券活动链接。

代码环境

源码主要laravel5.8,一整个活动要贴的代码很多,下面主要贴核心代码,仅供参考。主要还是要根据自己的业务需求来实现功能吧。

以下是后端截图,做成模块化

用PHP做了一个领取优惠券活动的示例代码

前端需要做的设置与限制:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
1.PHP简介
Oct 09 PHP
php代码收集表单内容并写入文件的代码
Jan 29 PHP
基于MySQL分区性能的详细介绍
May 02 PHP
解析php中call_user_func_array的作用
Jun 07 PHP
ini_set的用法介绍
Jan 07 PHP
PHP使用imagick读取PDF生成png缩略图的两种方法
Mar 20 PHP
一个图片地址分解程序(用于PHP小偷程序)
Aug 23 PHP
实例讲解PHP设计模式编程中的简单工厂模式
Feb 29 PHP
php rsa 加密,解密,签名,验签详解
Dec 06 PHP
ThinkPHP实现附件上传功能
Apr 27 PHP
基于php双引号中访问数组元素报错的解决方法
Feb 01 PHP
如何让PHP编码更加好看利于阅读
May 12 PHP
php无限极分类实现方法分析
Jul 04 #PHP
php常用日期时间函数实例小结
Jul 04 #PHP
JS操作XML中DTD介绍及使用方法分析
Jul 04 #PHP
PHP操作XML中XPath的应用示例
Jul 04 #PHP
PHP实现财务审核通过后返现金额到客户的功能
Jul 04 #PHP
PHP使用DOM对XML解析处理操作示例
Jul 04 #PHP
PHP创建XML接口示例
Jul 04 #PHP
You might like
Zend的MVC机制使用分析(一)
2013/05/02 PHP
nginx+thinkphp下解决不支持pathinfo模式
2015/07/01 PHP
PHP共享内存用法实例分析
2016/02/12 PHP
php web环境和命令行环境下查找php.ini的位置
2019/07/17 PHP
使用tp框架和SQL语句查询数据表中的某字段包含某值
2019/10/18 PHP
IE iframe的onload方法分析小结
2010/01/07 Javascript
document.getElementById介绍
2011/09/13 Javascript
jQuery.buildFragment使用方法及思路分析
2013/01/07 Javascript
SwfUpload在IE10上不出现上传按钮的解决方法
2013/06/25 Javascript
jQuery实现的fixedMenu下拉菜单效果代码
2015/08/24 Javascript
js实现无缝滚动特效
2015/12/20 Javascript
基于JavaScript实现瀑布流布局(二)
2016/01/26 Javascript
js判断上传文件后缀名是否合法
2016/01/28 Javascript
JavaScript必知必会(十) call apply bind的用法说明
2016/06/08 Javascript
利用js编写响应式侧边栏
2016/09/17 Javascript
JavaScript使用delete删除数组元素用法示例【数组长度不变】
2017/01/17 Javascript
浅谈angular2的http请求返回结果的subcribe注意事项
2017/03/01 Javascript
Vue非父子组件通信详解
2017/06/12 Javascript
js+cavans实现图片滑块验证
2020/09/29 Javascript
在漏洞利用Python代码真的很爽
2007/08/26 Python
Python 稀疏矩阵-sparse 存储和转换
2017/05/27 Python
Python解决N阶台阶走法问题的方法分析
2017/12/28 Python
TensorFlow 实战之实现卷积神经网络的实例讲解
2018/02/26 Python
Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例
2018/07/18 Python
Python对CSV、Excel、txt、dat文件的处理
2018/09/18 Python
Python合并同一个文件夹下所有PDF文件的方法
2019/03/11 Python
浅谈Python爬虫基本套路
2019/03/25 Python
基于python实现破解滑动验证码过程解析
2020/05/28 Python
解决Keras使用GPU资源耗尽的问题
2020/06/22 Python
菲律宾旅游网站:Expedia菲律宾
2017/10/11 全球购物
周仰杰(JIMMY CHOO)英国官方网站:闻名世界的鞋子品牌
2018/10/28 全球购物
日本订房网站,预订日本星级酒店/温泉旅馆:Relux(支持中文)
2020/01/03 全球购物
如何利用XMLHTTP检测URL及探测服务器信息
2013/11/10 面试题
入党积极分子十八届四中全会思想汇报
2014/10/23 职场文书
2015年语文教师工作总结
2015/05/25 职场文书
Python机器学习之决策树和随机森林
2021/07/15 Javascript