jh-admin/addon/coupon/api/controller/Coupon.php

574 lines
25 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* SaaSMall商城系统 - 团队十年电商经验汇集巨献!
* =========================================================
* Copy right 2019-2029 成都SAAS云科技有限公司, 保留所有权利。
* ----------------------------------------------
* 官方网址: https://www.gobuysaas.com
* =========================================================
*/
namespace addon\coupon\api\controller;
use addon\coupon\model\CouponWeChat;
use app\api\controller\BaseApi;
use addon\coupon\model\Coupon as CouponModel;
use addon\coupon\model\CouponType as CouponTypeModel;
use addon\coupon\model\MemberCoupon;
use think\facade\Db;
use think\facade\Log;
/**
* 优惠券
*/
class Coupon extends BaseApi
{
// 优惠券类型信息
public function typeinfo()
{
try {
// 参数获取
$coupon_type_id = $this->params['coupon_type_id'] ?? 0;
$app_type = $this->params['app_type'] ?? 'h5';
if (empty($coupon_type_id)) return $this->response($this->error('', 'REQUEST_COUPON_TYPE_ID'));
$coupon_model = new CouponModel();
$condition = [
['coupon_type_id', '=', $coupon_type_id],
['is_show', '=', 1],
['site_id', '=', $this->site_id]
];
$coupon_type_model = new CouponTypeModel();
$qrcode = $coupon_type_model->qrcode($coupon_type_id, $app_type, $this->site_id)['data'];
$info = $coupon_model->getCouponTypeInfo($condition);
if (!empty($info['data']) && !empty($qrcode)) $info['data']['qrcode'] = $qrcode['path'];
$info['data']['activeTime'] = date('Y-m-d H:i:s');
switch ($info['data']["validity_type"]) {
case 0:
$info['data']['expireTime'] = date('Y-m-d H:i:s', $info['data']['end_time']);
break;
case 1:
$info['data']['expireTime'] = date('Y-m-d H:i:s', time() + $info['data']["fixed_term"] * 24 * 60 * 60);
break;
default:
$info['data']['expireTime'] = date('Y-m-d H:i:s', time() + 10 * 365 * 24 * 60 * 60);
break;
}
$config_model = new \addon\aliapp\model\Config();
$config_info = $config_model->getAppConfig($this->site_id)['data'];
$info['data']['url'] = isset($config_info['appid']) ? 'alipays://platformapi/startapp?appId=' . $config_info['appid'] : '';
// 微信小程序领券信息处理
if ($info['data']['app_type'] == 'weapp') {
$couponWeChatModel = new CouponWeChat($info['data']['site_id']);
$info['data']['weapp_config'] = $couponWeChatModel->getWeAppConfig($info['data']);
}
return $this->response($info);
} catch (\Exception $e) {
return $this->response(error('FAIL', $e->getMessage()));
}
}
/**
* 列表信息
*/
public function memberpage()
{
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response($token);
$page = isset($this->params['page']) ? $this->params['page'] : 1;
$page_size = isset($this->params['page_size']) ? $this->params['page_size'] : PAGE_LIST_ROWS;
$state = isset($this->params['state']) ? $this->params['state'] : 0;//优惠券状态 0=全部 1已领用未使用 2已使用 3已过期
$coupon_model = new CouponModel();
$condition = [
['npc.member_id', '=', $token['data']['member_id']],
];
if ($state > 0) $condition[] = ['npc.state', '=', $state];
//按类型筛选
$type = isset($this->params['type']) ? $this->params['type'] : '';
$related_id = isset($this->params['related_id']) ? $this->params['related_id'] : 0;
switch ($type) {
case "reward"://满减
$condition[] = ["npc.type", "=", "reward"];
break;
case "discount"://折扣
$condition[] = ["npc.type", "=", "discount"];
break;
case "no_threshold"://无门槛
$condition[] = ["npc.at_least", "=", 0];
break;
}
if (!empty($related_id)) {
$condition[] = ['related_id', '=', $related_id];
}
$list = $coupon_model->getMemberCouponPageList($condition, $page, $page_size);
return $this->response($list);
}
/**
* 优惠券类型列表
*/
public function typelists()
{
$num = isset($this->params['num']) ? $this->params['num'] : 0;
$coupon_type_id_arr = isset($this->params['coupon_type_id_arr']) ? $this->params['coupon_type_id_arr'] : '';//coupon_type_id数组
$can_receive = isset($this->params['can_receive']) ? $this->params['can_receive'] : 0;// 是否只查询可领取的
$this->checkToken();
$coupon_model = new CouponModel();
$condition = [
['status', '=', 1],
['is_show', '=', 1],
['site_id', '=', $this->site_id]
];
//按类型查询
$type = isset($this->params['type']) ? $this->params['type'] : '';
switch ($type) {
case "reward"://满减
$condition[] = ["type", "=", "reward"];
break;
case "discount"://折扣
$condition[] = ["type", "=", "discount"];
break;
case "no_threshold"://无门槛
$condition[] = ["at_least", "=", 0];
break;
}
if (!empty($coupon_type_id_arr)) {
$condition[] = ['coupon_type_id', 'in', $coupon_type_id_arr];
}
$field = 'coupon_type_id,type,site_id,coupon_name,money,discount,max_fetch,at_least,end_time,image,validity_type,fixed_term,status,is_show,goods_type,discount_limit,count,lead_count,IF(count < 0 or count - lead_count > 0, 1, 0) as is_remain,alipay_pass_template_id,channel,app_type,weapp_channel,weapp_stock_id,weapp_status';
if ($can_receive == 1) {
$condition[] = [['count', '<>', Db::raw('lead_count')]];
}
$order = Db::raw('IF(count < 0 or count - lead_count > 0, 1, 0) DESC,sort ASC');
$list = $coupon_model->getCouponTypeList($condition, $field, $order, $num);
if (!empty($list['data']) && $this->member_id) {
foreach ($list['data'] as $k => $v) {
$list['data'][$k]['member_coupon_num'] = $coupon_model->getCouponCount([
['get_type', '=', 2],
['member_id', '=', $this->member_id],
['coupon_type_id', '=', $v['coupon_type_id']]
])['data'];
}
}
$url = '';
if ($this->params['app_type'] == 'aliapp') {
$config_model = new \addon\aliapp\model\Config();
$config_info = $config_model->getAppConfig($this->site_id)['data'];
if (isset($config_info['appid'])) {
$url = 'alipays://platformapi/startapp?appId=' . $config_info['appid'];
}
}
if ($this->params['app_type'] == 'weapp') {
$config_model = new \addon\wechatpay\model\Config();
$config_info = $config_model->getPayConfig($this->site_id)['data']['value'];
if ($config_info['v3_pay_signkey']) {
try {
$couponWeChatModel = new CouponWeChat($this->site_id);
foreach ($list['data'] as $k => $v) {
$list['data'][$k]['activeTime'] = date('Y-m-d H:i:s');
switch ($list['data'][$k]["validity_type"]) {
case 0:
$list['data'][$k]['expireTime'] = date('Y-m-d H:i:s', $list['data'][$k]['end_time']);
break;
case 1:
$list['data'][$k]['expireTime'] = date('Y-m-d H:i:s', time() + $list['data'][$k]["fixed_term"] * 24 * 60 * 60);
break;
default:
$list['data'][$k]['expireTime'] = date('Y-m-d H:i:s', time() + 10 * 365 * 24 * 60 * 60);
break;
}
$list['data'][$k]['url'] = $url;
// 微信优惠券领取信息处理
if ($v['app_type'] == 'weapp') $list['data'][$k]['weapp_config'] = $couponWeChatModel->getWeAppConfig($v);
}
}catch (\Exception $e){
}
}
}
return $this->response($list);
}
/**
* Common: 优惠券类型分页列表
* Time: 2023/07/10 9:38
* @return false|string
* @throws \think\Exception
*/
public function typepagelists()
{
$token = $this->checkToken();
// 参数获取
$app_type = isset($this->params['app_type']) ? $this->params['app_type'] : '';
$page = isset($this->params['page']) ? $this->params['page'] : 1;
$page_size = isset($this->params['page_size']) ? $this->params['page_size'] : PAGE_LIST_ROWS;
$coupon_type_id_arr = isset($this->params['coupon_type_id_arr']) ? $this->params['coupon_type_id_arr'] : '';//coupon_type_id数组
$can_receive = isset($this->params['can_receive']) ? $this->params['can_receive'] : 0;// 是否只查询可领取的
$type = isset($this->params['type']) ? $this->params['type'] : '';
// 查询条件生成
$coupon_model = new CouponModel();
$condition = [
['status', '=', 1],
['is_show', '=', 1],
['site_id', '=', $this->site_id]
];
// 按照渠道端查询
$appTypeCondition = '';
if ($app_type == 'weapp') $appTypeCondition = " OR (app_type = 'weapp' and (weapp_channel = 'store' or (weapp_channel = 'voucher' and weapp_status = 1)))";// 显示微信端优惠券
else if ($app_type == 'aliapp') $appTypeCondition = " OR (app_type = 'aliapp')";// 显示支付宝端优惠券
$condition[] = ['', "exp", Db::raw("((app_type = '' or app_type is null) {$appTypeCondition} )")];
//按类型查询
switch ($type) {
case "reward"://满减
$condition[] = ["type", "=", "reward"];
break;
case "discount"://折扣
$condition[] = ["type", "=", "discount"];
break;
case "no_threshold"://无门槛
$condition[] = ["at_least", "=", 0];
break;
}
if (!empty($coupon_type_id_arr)) $condition[] = ['coupon_type_id', 'in', $coupon_type_id_arr];
$field = 'coupon_type_id,type,site_id,coupon_name,money,discount,max_fetch,at_least,end_time,image,validity_type,fixed_term,status,is_show,goods_type,discount_limit,count,lead_count,IF(count < 0 or count - lead_count > 0, 1, 0) as is_remain,alipay_pass_template_id,channel,app_type,weapp_channel,weapp_stock_id,weapp_status';
if ($can_receive == 1) $condition[] = [['count', '<>', Db::raw('lead_count')]];
if ($this->member_id) {
$prefix = config('database.connections.mysql.prefix');
$field .= ', (select count(coupon_id) from ' . $prefix . 'promotion_coupon pc where pc.coupon_type_id = ct.coupon_type_id and pc.get_type=2 and pc.member_id=' . $this->member_id . ') as member_coupon_num';
}
$order = Db::raw('IF(count < 0 or count - lead_count > 0, 1, 0) DESC,sort ASC');
$list = $coupon_model->getCouponTypePageList($condition, $page, $page_size, $order, $field, 'ct');
$config_model = new \addon\aliapp\model\Config();
$config_info = $config_model->getAppConfig($this->site_id)['data'];
$url = '';
if (isset($config_info['appid'])) $url = 'alipays://platformapi/startapp?appId=' . $config_info['appid'];
// 循环处理数据
$couponWeChatModel = new CouponWeChat($this->site_id);
foreach ($list['data']['list'] as $k => &$v) {
// 基本信息处理
$v['activeTime'] = date('Y-m-d H:i:s');
switch ($v["validity_type"]) {
case 0:
$v['expireTime'] = date('Y-m-d H:i:s', $v['end_time']);
break;
case 1:
$v['expireTime'] = date('Y-m-d H:i:s', time() + $v["fixed_term"] * 24 * 60 * 60);
break;
default:
$v['expireTime'] = date('Y-m-d H:i:s', time() + 10 * 365 * 24 * 60 * 60);
break;
}
$v['url'] = $url;
// 微信小程序领券信息处理
if ($v['app_type'] == 'weapp') $v['weapp_config'] = $couponWeChatModel->getWeAppConfig($v);
}
return $this->response($list);
}
/**
* 会员优惠券数量
* @return string
*/
public function num()
{
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response($token);
$state = $this->params['state'] ?? 1;
$coupon_model = new MemberCoupon();
$count = $coupon_model->getMemberCouponNum($token['data']['member_id'], $state);
return $this->response($count);
}
/**
* 是否可以领取
*/
public function receivedNum()
{
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response($token);
$coupon_type_id = isset($this->params['coupon_type_id']) ? $this->params['coupon_type_id'] : 0;
$coupon_model = new MemberCoupon();
$res = $coupon_model->receivedNum($coupon_type_id, $this->member_id);
return $this->response($res);
}
/**
* 查询商品可用的优惠券
* @param int $id
* @return false|string
*/
public function goodsCoupon($id = 0)
{
$this->checkToken();
$coupon_model = new CouponModel();
$goods_id = $this->params['goods_id'] ?? 0;
$app_type = isset($this->params['app_type']) ? $this->params['app_type'] : '';
if (!empty($id)) $goods_id = $id;
$condition = [
['site_id', '=', $this->site_id],
['status', '=', 1],
['is_show', '=', 1],
['goods_type', '=', 1]
];
$goods_condition = [
['site_id', '=', $this->site_id],
['status', '=', 1],
['is_show', '=', 1],
['goods_type', '=', 2],
['goods_ids', 'like', "%,$goods_id,%"]
];
// 按照渠道端查询
$appTypeCondition = '';
if ($app_type == 'weapp') $appTypeCondition = " OR (app_type = 'weapp' and (weapp_channel = 'store' or (weapp_channel = 'voucher' and weapp_status = 1)))";// 显示微信端优惠券
else if ($app_type == 'aliapp') $appTypeCondition = " OR (app_type = 'aliapp')";// 显示支付宝端优惠券
$condition[] = $goods_condition[] = ['', "exp", Db::raw("((app_type = '' or app_type is null) {$appTypeCondition} )")];
$field = 'count,lead_count,coupon_type_id,coupon_type_id as type_id,type,site_id,coupon_name,money,discount,max_fetch,at_least,end_time,validity_type,fixed_term,goods_type,discount_limit,alipay_pass_template_id,channel,app_type,weapp_channel,weapp_stock_id,weapp_status';
if ($this->member_id) {
$prefix = config('database.connections.mysql.prefix');
$field .= ',(select count(coupon_id) from ' . $prefix . 'promotion_coupon pc where pc.coupon_type_id = type_id and pc.get_type=2 and pc.member_id=' . $this->member_id . ') as member_coupon_num';
}
$list = $coupon_model->getCouponTypeList($condition, $field, "money desc", null, 'ct');
$goods_coupon = $coupon_model->getCouponTypeList($goods_condition, $field, "money desc", null, 'ct');
if (!empty($goods_coupon['data'])) $list['data'] = array_merge($list['data'], $goods_coupon['data']);
if ($list['data'] && $this->member_id) {
try {
$couponWeChatModel = new CouponWeChat($this->site_id);
foreach ($list['data'] as $k => $v) {
if ($v['count'] == $v['lead_count']) unset($list['data'][$k]);// 已抢光
elseif ($v['max_fetch'] != 0 && $v['member_coupon_num'] > 0 && $v['member_coupon_num'] >= $v['max_fetch']) unset($list['data'][$k]);// 已领取
// 微信小程序领券信息处理
if ($v['app_type'] == 'weapp') $list['data'][$k]['weapp_config'] = $couponWeChatModel->getWeAppConfig($v);
}
$list['data'] = array_values($list['data']);
} catch (\Exception $e) {
return $this->response(error('FAIL', $e->getMessage()));
}
}
return $this->response($list);
}
/**
* 查询优惠券通过优惠券类型id
*/
public function couponById()
{
$id = $this->params['id'] ?? 0;
$coupon_model = new CouponModel();
$condition = [
['site_id', '=', $this->site_id],
['status', '=', 1],
['coupon_type_id', 'in', $id]
];
$list = $coupon_model->getCouponTypeList($condition, "coupon_type_id,type,site_id,coupon_name,money,discount,max_fetch,at_least,end_time,validity_type,fixed_term,goods_type,discount_limit", "money desc", "");
return $this->response($list);
}
// 获取用户优惠劵详情
public function memberCouponDetail()
{
// 用户登录
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response($token);
// 参数获取
$couponId = (int)$this->params['coupon_id'] ?? 0;
if ($couponId <= 0) return $this->response($this->error('', '参数错误'));
// 信息获取
$condition = [
['npc.member_id', '=', $this->member_id],
['npc.coupon_id', '=', $couponId],
];
$field = 'npc.coupon_name,npc.goods_type,npc.type,npc.use_order_id,npc.coupon_id,npc.coupon_type_id,npc.site_id,npc.coupon_code,npc.member_id,npc.discount_limit,npc.alipay_serial_number,
npc.at_least,npc.money,npc.discount,npc.state,npc.get_type,npc.fetch_time,npc.use_time,npc.start_time,npc.end_time,mem.nickname,on.order_no,mem.nickname,mem.headimg,mem.mobile';
$join = [
['member mem', 'npc.member_id = mem.member_id', 'inner'],
['order on', 'npc.use_order_id = on.order_id', 'left']
];
$info = model("promotion_coupon")->getInfo($condition, $field, 'npc', $join);
return $this->response($this->success($info));
}
public function alipayCallback()
{
Log::write('支付宝回调通知-优惠券-alipayCallback' . json_encode($this->params, JSON_UNESCAPED_UNICODE));
$extInfo = json_decode(urldecode(urldecode($this->params['extInfo'])), TRUE);
if (empty($extInfo)) {
return $this->response([
"success" => "false",
"passId" => "your_passId",
"resultDesc" => "发券失败-用户extInfo校验失败"
]);
}
$alipayUserToken = $this->params['token'];
$this->params['token'] = $extInfo['user_token'];
$this->params['get_type'] = $extInfo['get_type'];
$this->params['coupon_id'] = $extInfo['coupon_id'] ?? 0;
// 用户登录
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response([
"success" => "false",
"passId" => "your_passId",
"resultDesc" => "发券失败-用户Token校验失败"
]);
$site_id = $this->site_id;
$templateId = isset($this->params['templateId']) ? $this->params['templateId'] : 0;
$coupon_type_id = model("promotion_coupon_type")->getInfo([['alipay_pass_template_id', '=', $templateId], ['site_id', '=', $site_id]], 'coupon_type_id');
$get_type = isset($this->params['get_type']) ? $this->params['get_type'] : 2;//获取方式:1订单2.直接领取3.活动领取
if (empty($coupon_type_id)) {
return $this->response([
"success" => "false",
"passId" => "your_passId",
"resultDesc" => "发券失败-无系统优惠券"
]);
}
$coupon_type_id = $coupon_type_id['coupon_type_id'];
$coupon_model = new CouponModel();
//系统已领取优惠券 补领卡包优惠券
if ($this->params['coupon_id'] > 0) {
$res = [
'code' => 0,
'data' => $this->params['coupon_id']
];
} else {
$res = $coupon_model->receiveCoupon($coupon_type_id, $site_id, $token['data']['member_id'], $get_type);
}
$res['data'] = [
'coupon_id' => $res['data'],
'coupon_type_id' => $coupon_type_id
];
//判断一下用户是否拥有当前优惠券
$coupon_result = $coupon_model->getCouponInfo([['coupon_type_id', '=', $coupon_type_id], ['site_id', '=', $site_id], ['member_id', '=', $token['data']['member_id']]], 'coupon_id');
$coupon = $coupon_result['data'];
// $res[ 'data' ][ 'is_exist' ] = empty($coupon) ? 0 : 1;
//支付宝发券
if ($res['code'] >= 0) {
$memberInfo = model('member')->getInfo([['member_id', '=', $token['data']['member_id']]]);
$couponInfo = model('promotion_coupon')->getInfo([['coupon_id', '=', $res['data']['coupon_id']]]);
$couponInfo['activeTime'] = date('Y-m-d H:i:s', $couponInfo['fetch_time']);
$couponInfo['expireTime'] = date('Y-m-d H:i:s', $couponInfo['end_time']);
$config_model = new \addon\aliapp\model\Config();
$config_info = $config_model->getAppConfig($this->site_id)['data'];
$url = '';
if (isset($config_info['appid'])) {
$url = 'alipays://platformapi/startapp?appId=' . $config_info['appid'];
}
$couponInfo['url'] = $url;
$data = [
'tpl_id' => $templateId,
'activeTime' => $couponInfo['activeTime'],
'expireTime' => $couponInfo['expireTime'],
'url' => $couponInfo['url'],
'user_id' => $memberInfo['ali_openid'],
'user_token' => $alipayUserToken,
];
$alipayCoupon = $coupon_model->alipayPassInstanceAdd($site_id, $data);
if ($alipayCoupon['code'] < 0) {
//回收
(new MemberCoupon())->recoveryCoupon([$res['data']], $this->site_id);
return $this->response([
"success" => "false",
"passId" => "your_passId",
"resultDesc" => json_encode($alipayCoupon)
]);
}
Log::write('支付宝回调通知-优惠券结果-alipayCallback' . json_encode($alipayCoupon, JSON_UNESCAPED_UNICODE));
$data['alipay_coupon'] = json_decode($alipayCoupon['data']['result'], TRUE);
Log::write('支付宝回调通知-优惠券结果-alipayCallback' . json_encode($data, JSON_UNESCAPED_UNICODE));
// if($data['alipay_coupon']['errorCode'] != "SUCCESS"){
// //回收
// (new MemberCoupon())->recoveryCoupon([$res['data']], $this->site_id);
// return $this->response([
// "success" => "false",
// "passId" => "your_passId",
// "resultDesc" => json_encode($alipayCoupon)
// ]);
// }
model('promotion_coupon')->update([
'alipay_serial_number' => $data['alipay_coupon']['serialNumber'],
'alipay_pass_id' => $data['alipay_coupon']['passId']
], [['coupon_id', '=', $res['data']['coupon_id']]]);
Log::write('支付宝回调通知-优惠券结果-alipayCallback' . json_encode($alipayCoupon, JSON_UNESCAPED_UNICODE));
return $this->response([
"success" => "true",
"passId" => $data['alipay_coupon']['passId'],
"resultDesc" => "发券成功"
]);
}
return $this->response([
"success" => "false",
"passId" => "your_passId",
"resultDesc" => "发券失败-系统发券失败"
]);
}
/**
* 获取支付商家信息
*
*/
public function getPayShopInfo()
{
$shop_info = model('pay_shop')->getInfo(['site_id' => $this->site_id], 'merchant_smid');
$shop_info['uuid'] = substr((new CouponTypeModel())->uuid(), 0, 20);
return $this->response($this->success($shop_info));
}
/**
* Common: 用户领取优惠券
* Author: wu-hui
* Time: 2023/07/10 11:37
* @return false|string
*/
public function receive()
{
// 用户登录信息
$token = $this->checkToken();
if ($token['code'] < 0) return $this->response($token);
// 参数信息获取
$this->params['site_id'] = $this->site_id;
$this->params['member_id'] = $token['data']['member_id'] ?? 0;
// 优惠券领取
$couponModel = new CouponModel();
$result = $couponModel->newReceiveCoupon($this->params);
if (!is_array($result['data'])) $result['data'] = [];
$result['data']['is_exist'] = 1;
// $result=[
// 'coupon_type_id'=>'51',
// 'id'=>'307',
// 'is_exist'=>'1',
// ];
// $this->success($result)
return $this->response($result);
}
}