PHP 쿠폰 구현 방법: 1. 프런트엔드 파일을 생성하고 쿠폰이 존재하는지 또는 비활성화되었는지 확인합니다. 2. PHP 샘플 파일을 생성합니다. 3. "공용 함수 doCoupon($params){...}을 통해; ” 등의 쿠폰수집 상황 처리 방법을 안내해 드립니다.
본 글의 운영 환경: Windows 7 시스템, PHP 버전 7.4, DELL G3 컴퓨터
PHP 쿠폰 구현 방법은 무엇인가요?
PHP를 사용하여 쿠폰 수집을 위한 샘플 코드 만들기
비즈니스 요구
쿠폰 활동, 특정 요구는 자신의 요구에 따라야 합니다. 최근 구현된 쿠폰 활동에 대한 주요 비즈니스 요구 사항은 다음과 같습니다. 백엔드에 따른 쿠폰 템플릿 설정, 사용자 유형 설정, 쿠폰 활동 시작 및 종료 시간, 최종적으로 다양한 쿠폰 활동 링크 생성.
코드 환경:
소스 코드는 주로 laravel5.8입니다. 전체 활동에 대해 게시할 코드가 많습니다. 핵심 코드는 주로 참고용으로 아래에 게시됩니다. 가장 중요한 것은 자신의 비즈니스 요구에 따라 기능을 구현하는 것입니다.
다음은 모듈식으로 만든 백엔드의 스크린샷입니다.
프런트 엔드에서 설정해야 하는 설정 및 제한 사항:
1 쿠폰이 존재하는지 또는 비활성화되었는지 확인
2 이벤트 시작 시간 및 쿠폰 시작 시간을 결정합니다
그런 다음 이벤트 쿠폰을 받으려면 다음 상황을 판단해야 합니다.
1 이벤트가 종료되었습니다.
2 이벤트가 시작되었습니다.
3 이벤트가 시작되었습니다. 신규 유저가 받을 수 있는 이벤트이고, 받는 유저는 기존 유저입니다
4 기존 유저가 받을 수 있는 이벤트이고, 받은 유저는 신규 유저입니다
5 쿠폰을 받았나요? 프롬프트
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 비디오 튜토리얼 "
위 내용은 PHP 쿠폰 구현은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사는 산 및 기본 데이터베이스 모델을 비교하여 특성과 적절한 사용 사례를 자세히 설명합니다. 산은 금융 및 전자 상거래 애플리케이션에 적합한 데이터 무결성 및 일관성을 우선시하는 반면 Base는 가용성 및

이 기사는 코드 주입과 같은 취약점을 방지하기 위해 PHP 파일 업로드 보안에 대해 설명합니다. 파일 유형 유효성 검증, 보안 저장 및 오류 처리에 중점을 두어 응용 프로그램 보안을 향상시킵니다.

기사는 내장 함수 사용, 화이트리스트 접근 방식 및 서버 측 유효성 검사와 같은 기술에 중점을 둔 보안을 향상시키기 위해 PHP 입력 유효성 검증에 대한 모범 사례를 논의합니다.

이 기사는 토큰 버킷 및 누출 된 버킷과 같은 알고리즘을 포함하여 PHP에서 API 요율 제한을 구현하고 Symfony/Rate-Limiter와 같은 라이브러리 사용 전략에 대해 설명합니다. 또한 모니터링, 동적 조정 요율 제한 및 손도 다룹니다.

이 기사에서는 PHP에서 암호를 보호하기 위해 PHP에서 Password_hash 및 Password_Verify 사용의 이점에 대해 설명합니다. 주요 주장은 이러한 기능이 자동 소금 생성, 강한 해싱 알고리즘 및 Secur를 통해 암호 보호를 향상 시킨다는 것입니다.

이 기사는 PHP 및 완화 전략의 OWASP Top 10 취약점에 대해 설명합니다. 주요 문제에는 PHP 응용 프로그램을 모니터링하고 보호하기위한 권장 도구가 포함 된 주입, 인증 파손 및 XSS가 포함됩니다.

이 기사는 PHP의 XSS 공격을 방지하기위한 전략, 입력 소독, 출력 인코딩 및 보안 향상 라이브러리 및 프레임 워크 사용에 중점을 둔 전략에 대해 설명합니다.

이 기사는 각각의 사용시기에 중점을 둔 PHP의 인터페이스 및 추상 클래스 사용에 대해 설명합니다. 인터페이스는 관련없는 클래스 및 다중 상속에 적합한 구현없이 계약을 정의합니다. 초록 클래스는 일반적인 기능을 제공합니다


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
