How to implement php coupons: 1. Create a front-end file and determine whether the coupon exists or is deactivated; 2. Create a PHP sample file; 3. Through "public function doCoupon($params){ ...}" and other methods to handle the coupon collection situation.

The operating environment of this article: windows7 system, PHP7.4 version, DELL G3 computer
What is the implementation method of php coupons ?
Use PHP to make a sample code for receiving coupon activities
Business requirements
Coupon activities, the specifics are According to your own needs. The following are the main business requirements of the recently implemented coupon activity: setting the coupon template according to the backend, setting the user type, starting and ending time of the coupon activity, and finally generating different coupon activity links.
Code environment:
The source code is mainly laravel5.8. There is a lot of code to be posted for a whole activity. The core code is mainly posted below. It is only for refer to. The main thing is to implement the functions according to your own business needs.
The following are screenshots of the backend, made into modules

The settings and restrictions that need to be made on the front-end:
1 Determine whether the coupon exists or is disabled
2 Determine the event start time and coupon start time
To then receive the event coupon, you need to determine the following situations:
1 The activity has ended
2 The activity is at the beginning
3 The activity is for new users to receive, and the users who receive it are old users
4 The activity is for old users to receive, and the users who receive it are new users
5 Whether the coupon has been collected
6 Already received the coupon prompt
7 Received successfully
The following core code implements
/**
* 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;
}
}User receives the coupon And issue coupons
/**
* 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("优惠券不存在或者已经停用");
}
}If the receipt is successful, coupons
/**
* 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;
}will be issued. Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is the implementation of php coupons. For more information, please follow other related articles on the PHP Chinese website!
ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PMThe article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and
PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PMThe article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.
PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PMArticle discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.
PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PMThe article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand
PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PMThe article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur
OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PMThe article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.
PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PMThe article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.
PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PMThe article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment






