検索
ホームページバックエンド開発PHPの問題PHPクーポンの実装とは何ですか

PHPクーポンの実装とは何ですか

Dec 01, 2021 am 09:54 AM
phpクーポンを入手する

php クーポンの実装方法: 1. フロントエンド ファイルを作成し、クーポンが存在するか無効化されているかを確認します。 2. PHP サンプル ファイルを作成します。 3. 「パブリック関数 doCoupon($params){ ...}" およびクーポン収集状況を処理するその他のメソッド。

PHPクーポンの実装とは何ですか

この記事の動作環境:Windows7システム、PHP7.4バージョン、DELL G3コンピュータ

導入方法とはphp クーポンの?

PHP を使用して、クーポン アクティビティを受信するためのサンプル コードを作成します。

ビジネス要件

クーポン アクティビティの詳細は次のとおりです。自分のニーズに合わせて。最近実装されたクーポン アクティビティの主なビジネス要件は次のとおりです。バックエンドに応じたクーポン テンプレートの設定、ユーザー タイプ、クーポン アクティビティの開始時間と終了時間の設定、そして最後にさまざまなクーポン アクティビティ リンクの生成です。

コード環境

ソースコードはlaravel5.8を中心に、アクティビティ全体で投稿するコードが多くなります。以下にコアコードを中心に掲載しますので、参考程度にしてください。主なことは、独自のビジネス ニーズに応じて機能を実装することです。

以下は、モジュール化されたバックエンドのスクリーンショットです。

フロントで行う必要がある設定と制限-end:

1 クーポンが存在するか無効になっているかを確認します。
2 イベント開始時間とクーポン開始時間を確認します。

その後、クーポンを受け取るにはイベント クーポンについては、次の状況を判断する必要があります。
1 アクティビティは終了しました
2 アクティビティは開始中です
3 アクティビティは新規ユーザーが受け取るものであり、受け取ったユーザーは古いユーザーですusers
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[&#39;mobile&#39;]);
    //主要是过滤掉领取优惠券为0的,用laravel的同学注意看看
    $detail = $activity_link->each(function($item,$index) use ($showUser) {

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

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

    }

    $collection_coupon = collect($detail);
    $collection_coupon = $collection_coupon->where(&#39;diff&#39;, &#39;<=&#39; ,&#39;0&#39;);  //去除优惠券剩余数量为0,或者领取优惠券数量-剩余数量 > 0

  }
  //判断活动开始时间与优惠券开始时间
  $act_coupon = ActivityCouponBaseModel::where(&#39;activity_id&#39;,$activity[&#39;activity_id&#39;])->first();
  $check_time = $this-> checkCouponTime($act_coupon[&#39;start_time&#39;],$activity_link);
  if($check_time == &#39;error&#39;){
    throw new \Exception("优惠券领取时间未开始,暂不可领取");
  }

  //领取活动有以下几种情况
  //1: 活动已结束
  if($activity[&#39;end_time&#39;] < date("Y-m-d H:i:s") || $activity[&#39;status&#39;] == 1){
    $result = [
      &#39;code&#39; => 1,
    ];
    return $result;
  }

  //6 活动为开始时
  if($activity[&#39;start_time&#39;] > date("Y-m-d H:i:s") || $activity[&#39;status&#39;] == 1){
    $result = [
      &#39;code&#39; => 6,
    ];
    return $result;

  }

  $checkUser = $this->haveUser($params[&#39;mobile&#39;]); //检查是新用户,还是老用户 根据自己的业务需求做,这个方法就不贴了
  //2: 活动为新用户领取,而领取的用户是老用户
  if($activity[&#39;user_type&#39;] == 1 && !empty($checkUser)){
    $result = [
      &#39;code&#39; => 2,
    ];
    return $result;
  }

  //3:活动为老用户领取,而领取的用户是新用户
  if($activity[&#39;user_type&#39;]==2 && empty($checkUser)){
    $result = [
      &#39;code&#39; => 3,
    ];
    return $result;
  }


  //4:优惠券是否领取完
  $coupon = $this->getCouponExpire($collection_coupon,$params[&#39;mobile&#39;]); //这里提示有一个优惠券列表,根据自己的业务需求做,这个方法就不贴了
  //return $coupon;
  if($coupon == 1){
    $result = [
      &#39;code&#39; => 4,
    ];
    return $result;
  }

  //5:已领取过优惠券提示
  $userCoupon = &#39;&#39;;
  $userRate = &#39;&#39;;
  if(!empty($checkUser)){
    //user存在则为老用户,再检查是否领取过
    $userCoupon = $this->getUserCoupon($collection_coupon,$checkUser[&#39;user_id&#39;]);
    $userRate = $this->getUserCouponRate($checkUser[&#39;user_id&#39;],$activity[&#39;activity_id&#39;]);
  }else{
    //新用户,检查是否注册过
    $var_user = UserBaseModel::where(&#39;user_name&#39;,$params[&#39;mobile&#39;])->first();
    if(!empty($var_user)){
      $userCoupon = $this->getUserCoupon($collection_coupon,$var_user[&#39;user_id&#39;]);
      $userRate = $this->getUserCouponRate($var_user[&#39;user_id&#39;],$activity[&#39;activity_id&#39;]);
    }
  }

  //return $userRate;

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

  //5:领取成功
  //如果活动规定是新老用户0,新用户1,老用户2
  $getCouponSuccess = $this->getCouponSuccess($activity[&#39;user_type&#39;],$checkUser,$collection_coupon,$params[&#39;mobile&#39;]);
  //return $getCouponSuccess;
  if($getCouponSuccess[&#39;status&#39;] == 200){
    $result = [
      &#39;code&#39; => 5,
      &#39;phone&#39;=> $str_mobile,
      &#39;coupon&#39; => $getCouponSuccess[&#39;result&#39;][0],
      &#39;is_get&#39; => 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 [
          &#39;result&#39; => $res,
          &#39;status&#39; => 200
        ];
        break;
      case 2:
        //老用户领取
        $res = $this->insertUserCoupon($user,$coupon);
        return [
          &#39;result&#39; => $res,
          &#39;status&#39; => 200
        ];
        break;
      default:
        //新老用户领取,判断是新用户还是老用户,这里的$user是有无配送单,有则为老用户;
        if(empty($user)){
          $res = $this->addUser($mobile,$coupon);
        }else{

          $res = $this->insertUserCoupon($user,$coupon); //老用户,直接发放优惠券
        }
        return [
          &#39;result&#39; => $res,
          &#39;status&#39; => 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([
      &#39;config_id&#39;=>$item[&#39;config_id&#39;],
      &#39;status&#39;  => 0,
    ])->first();

    if(empty($res) || (!empty($res) && $res[&#39;is_send&#39;] == 0) ){
      throw new \Exception("优惠券未发放,暂不可领取");
    }

    //发放优惠券,有多少张就添加多少张,这里扣除优惠券时,主要用不同的coupon_sn来区别
    $onlyCoupon = $this->getCouponName($item[&#39;config_id&#39;]);
    if ($onlyCoupon[&#39;expire_type&#39;] == 0) {
      $start_time = $onlyCoupon[&#39;expire_start_time&#39;];
      $end_time = $onlyCoupon[&#39;expire_end_time&#39;];
    } else {
      $start_time = date(&#39;Y-m-d H:i:s&#39;);
      $end_time = date(&#39;Y-m-d H:i:s&#39;, time()+86400*$onlyCoupon[&#39;expire_type&#39;]);
    }

    $result = [
      &#39;user_id&#39;  => $user[&#39;user_id&#39;],
      &#39;config_id&#39; => $item[&#39;config_id&#39;],
      &#39;name&#39;   => $onlyCoupon[&#39;name&#39;],
      &#39;get_type&#39; => $onlyCoupon[&#39;get_type&#39;],
      &#39;amount&#39;  => $onlyCoupon[&#39;amount&#39;],
      &#39;require_price&#39; => $onlyCoupon[&#39;require_price&#39;],
      &#39;status&#39;    => 1,
      &#39;start_time&#39;  => $start_time,
      &#39;end_time&#39;   => $end_time,
    ];
    for($i=0; $i < $item[&#39;quantity&#39;];$i++){
      $result[&#39;coupon_sn&#39;] = &#39;B&#39;.mt_rand(1, 10000) . strtoupper(uniqid(mt_rand(1, 10000)));
      $userCoupon = UserCouponBaseModel::create($result);
    }

    //扣除相应的优惠券数量,这里用到了锁表,防止并发时,优惠券为-1
    $couponConfig = CouponConfigBaseModel::where(&#39;config_id&#39;,$item[&#39;config_id&#39;])->lockForUpdate()->first();
    if($couponConfig->left_quantity > 0 ){
      if($couponConfig->left_quantity >= $item[&#39;quantity&#39;]){
        $couponConfig->left_quantity = $couponConfig->left_quantity-$item[&#39;quantity&#39;];
        $couponConfig->save();
      }else{
        throw new \Exception("优惠券剩余数量不够扣减");
      }

    }


    $relate = [
      &#39;coupon_id&#39; => $userCoupon->coupon_id,
      &#39;user_id&#39;  => $user[&#39;user_id&#39;],
      &#39;config_id&#39; => $item[&#39;config_id&#39;],
      &#39;activity_id&#39; => $item[&#39;activity_id&#39;]
    ];

    ActivityCouponUserRelateBaseModel::create($relate);

    $relate[] = $this->getUserCouponRate($user[&#39;user_id&#39;],$item[&#39;activity_id&#39;]);


  }

  return $relate;
}

推奨学習: 「

PHP ビデオ チュートリアル

以上がPHPクーポンの実装とは何ですかの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
酸とベースデータベース:違いとそれぞれを使用するタイミング。酸とベースデータベース:違いとそれぞれを使用するタイミング。Mar 26, 2025 pm 04:19 PM

この記事では、酸とベースのデータベースモデルを比較し、その特性と適切なユースケースを詳述しています。酸は、財務およびeコマースアプリケーションに適したデータの整合性と一貫性を優先し、ベースは可用性に焦点を当て、

PHPセキュアファイルアップロード:ファイル関連の脆弱性の防止。PHPセキュアファイルアップロード:ファイル関連の脆弱性の防止。Mar 26, 2025 pm 04:18 PM

この記事では、コードインジェクションのような脆弱性を防ぐために、PHPファイルのアップロードを確保することについて説明します。ファイルタイプの検証、セキュアストレージ、およびアプリケーションセキュリティを強化するエラー処理に焦点を当てています。

PHP入力検証:ベストプラクティス。PHP入力検証:ベストプラクティス。Mar 26, 2025 pm 04:17 PM

記事では、組み込み関数、ホワイトリストアプローチ、サーバー側の検証などの手法に焦点を当てたセキュリティを強化するためのPHP入力検証のベストプラクティスについて説明します。

PHP APIレート制限:実装戦略。PHP APIレート制限:実装戦略。Mar 26, 2025 pm 04:16 PM

この記事では、Token BucketやLeaky BucketなどのアルゴリズムやSymfony/Rate-Limiterなどのライブラリを使用するなど、PHPでAPIレート制限を実装するための戦略について説明します。また、監視、動的に調整されたレートの制限、および手をカバーします

PHPパスワードハッシュ:password_hashおよびpassword_verify。PHPパスワードハッシュ:password_hashおよびpassword_verify。Mar 26, 2025 pm 04:15 PM

この記事では、パスワードを保護するためにPHPでpassword_hashとpassword_verifyを使用することの利点について説明します。主な議論は、これらの関数が自動塩の生成、強力なハッシュアルゴリズム、およびSecurを通じてパスワード保護を強化するということです

OWASPトップ10 PHP:共通の脆弱性を説明し、軽減します。OWASPトップ10 PHP:共通の脆弱性を説明し、軽減します。Mar 26, 2025 pm 04:13 PM

この記事では、PHPおよび緩和戦略におけるOWASPトップ10の脆弱性について説明します。重要な問題には、PHPアプリケーションを監視および保護するための推奨ツールを備えたインジェクション、認証の壊れ、XSSが含まれます。

PHP XSS予防:XSSから保護する方法。PHP XSS予防:XSSから保護する方法。Mar 26, 2025 pm 04:12 PM

この記事では、PHPでのXSS攻撃を防ぐための戦略について説明し、入力の消毒、出力エンコード、セキュリティを向上させるライブラリとフレームワークの使用に焦点を当てています。

PHPインターフェイスvs抽象クラス:それぞれを使用する時期。PHPインターフェイスvs抽象クラス:それぞれを使用する時期。Mar 26, 2025 pm 04:11 PM

この記事では、PHPでのインターフェイスと抽象クラスの使用について説明し、それぞれをいつ使用するかに焦点を当てています。インターフェイスは、無関係なクラスや複数の継承に適した、実装なしで契約を定義します。抽象クラスは共通の機能を提供します

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール