1.缺失信息提交

This commit is contained in:
2025-05-07 12:10:19 +08:00
parent 066c3c3420
commit 4da5dc858a
17 changed files with 2209 additions and 6 deletions

57
app/api/cache/TokenCache.php vendored Normal file
View File

@ -0,0 +1,57 @@
<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | gitee下载https://gitee.com/likeshop_gitee
// | github下载https://github.com/likeshop-github
// | 访问官网https://www.likeshop.cn
// | 访问社区https://home.likeshop.cn
// | 访问手册http://doc.likeshop.cn
// | 微信公众号likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用未经许可不能去除前后端官方版权标识
// | likeshop系列产品收费版本务必购买商业授权购买去版权授权后方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的,任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------
namespace app\api\cache;
use app\common\cache\CacheBase;
use think\facade\Db;
use think\facade\Config;
class TokenCache extends CacheBase
{
public function setTag()
{
return 'token';
}
/**
* 子类实现查出数据
* @return mixed
*/
public function setData()
{
//刷新token过期时间
$time = time();
$expire_time = $time + Config::get('project.token_expire_time');
Db::name('session')
->where(['token' => $this->extend['token']])
->update(['update_time' => $time, 'expire_time' => $expire_time]);
//返回用户信息
$user_info = Db::name('user u')
->join('session s', 'u.id=s.user_id')
->where(['s.token' => $this->extend['token']])
->field('u.*,s.token,s.client')
->find();
return $user_info;
}
}

View File

@ -21,7 +21,7 @@
namespace app\api\controller;
use app\api\logic\LoginLogic;
use app\api\validate\WechatLoginValidate;
use app\common\server\ConfigServer;
use app\common\service\ConfigServer;
class AccountController extends BaseApiController
{
@ -250,10 +250,10 @@ class AccountController extends BaseApiController
{
$post = $this->request->post();
if (empty($post['code']) || empty($post['nickname'])) {
$this->_error('参数缺失');
return $this->fail('参数缺失');
}
$data = LoginLogic::authLogin($post);
$this->_success($data['msg'], $data['data'], $data['code'], $data['show']);
return $this->success("登录成功",$data);
}
/**

View File

@ -0,0 +1,642 @@
<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | gitee下载https://gitee.com/likeshop_gitee
// | github下载https://github.com/likeshop-github
// | 访问官网https://www.likeshop.cn
// | 访问社区https://home.likeshop.cn
// | 访问手册http://doc.likeshop.cn
// | 微信公众号likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用未经许可不能去除前后端官方版权标识
// | likeshop系列产品收费版本务必购买商业授权购买去版权授权后方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的,任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\logic\AccountLogLogic;
use app\common\model\{AccountLog, AfterSale, DistributionOrder, NoticeSetting, Order, User};
use app\common\service\{AreaServer, ConfigServer, UrlServer};
use think\Db;
use think\Exception;
use think\facade\Hook;
class DistributionLogic
{
/**
* 填写邀请码
* @param $code
* @param $my_id
* @return bool|string
*/
public static function code($code, $my_id)
{
try {
Db::startTrans();
$my_leader = Db::name('user')
->field(['id', 'first_leader', 'second_leader', 'third_leader', 'ancestor_relation'])
->where(['distribution_code' => $code])
->find();
//更新我的第一上级、第二上级、第三上级、关系链
$my_leader_id = $my_leader['id'];
$my_first_leader = $my_leader['first_leader'];
$my_third_leader = $my_leader['second_leader'];
$my_leader['ancestor_relation'] = boolval($my_leader['ancestor_relation']) ? $my_leader['ancestor_relation'] : '';
$my_ancestor_relation = trim("{$my_leader_id},{$my_leader['ancestor_relation']}", ',');
$user = User::findOrEmpty($my_id);
// 旧关系链
if (!empty($user->ancestor_relation)) {
$old_ancestor_relation = $user->id . ',' .$user->ancestor_relation;
} else {
$old_ancestor_relation = $user->id;
}
$data = [
'first_leader' => $my_leader_id,
'second_leader' => $my_first_leader,
'third_leader' => $my_third_leader,
'ancestor_relation' => $my_ancestor_relation,
];
Db::name('user')
->where(['id' => $my_id])
->update($data);
//更新我向下一级的第二上级、第三上级
$data = [
'second_leader' => $my_leader_id,
'third_leader' => $my_first_leader,
];
Db::name('user')
->where(['first_leader' => $my_id])
->update($data);
//更新我向下二级的第三级
$data = [
'third_leader' => $my_leader_id,
];
Db::name('user')
->where(['second_leader' => $my_id])
->update($data);
//更新与我相关的所有关系链
Db::name('user')
->where("find_in_set({$my_id},ancestor_relation)")
->exp('ancestor_relation', "replace(ancestor_relation,'{$old_ancestor_relation}','" . trim("{$my_id},{$my_ancestor_relation}", ',') . "')")
->update();
//邀请会员赠送积分
$invited_award_integral = ConfigServer::get('marketing','invited_award_integral',0);
if($invited_award_integral > 0){
Db::name('user')->where(['id'=>$my_leader['id']])->setInc('user_integral',$invited_award_integral);
AccountLogLogic::AccountRecord($my_leader['id'],$invited_award_integral,1, AccountLog::invite_add_integral);
}
//消息通知
Hook::listen('notice', [
'user_id' => $my_leader_id,
'lower_id' => $my_id,
'scene' => NoticeSetting::INVITE_SUCCESS_NOTICE,
]);
Db::commit();
return true;
} catch (Exception $e) {
Db::rollback();
return $e->getMessage();
}
}
/**
* 填写申请记录
* @param $post
* @param $user_id
* @return bool|string
*/
public static function apple($post, $user_id)
{
try {
$time = time();
$data = [
'user_id' => $user_id,
'real_name' => $post['real_name'],
'province' => $post['province'],
'city' => $post['city'],
'district' => $post['district'],
'reason' => $post['reason'],
'create_time' => $time,
'update_time' => $time,
];
Db::name('distribution_member_apply')
->insert($data);
return true;
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
* 获取最新申请详情
* @param $user_id
* @return array|\PDOStatement|string|\think\Model|null
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function appleDetail($user_id)
{
$result = Db::name('distribution_member_apply')
->field(['real_name', 'province', 'city', 'district', 'reason', 'status'])
->where('user_id', $user_id)
->order('id', 'desc')
->find();
if (empty($result)) {
return [];
}
$result['province'] = AreaServer::getAddress($result['province']);
$result['city'] = AreaServer::getAddress($result['city']);
$result['district'] = AreaServer::getAddress($result['district']);
switch ($result['status']) {
case 0:
$result['status_str'] = '已提交,等待客服审核...';
break;
case 1:
$result['status_str'] = '';
break;
case 2:
$result['status_str'] = '审核失败,请重新提交审核';
break;
}
return $result;
}
/**
* 上级邀请人信息
* @param $user_id
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function myLeader($user_id)
{
$field = 'nickname,avatar,is_distribution,mobile,first_leader,distribution_code,earnings';
$user = Db::name('user')
->field($field)
->where(['id' => $user_id])
->find();
$first_leader = Db::name('user')
->field('nickname,mobile')
->where(['id' => $user['first_leader']])
->findOrEmpty();
$user['avatar'] = UrlServer::getFileUrl($user['avatar'], 'local');
return [
'user' => $user,
'leader' => $first_leader,
];
}
/**
* 分销推广主页信息
* @param $user_id
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function index($user_id)
{
$user_info = self::myLeader($user_id);//用户信息
$fans = Db::name('user')
->where('first_leader|second_leader', '=', $user_id)
->count();
//今天的预估收益
$today_earnings = Db::name('distribution_order_goods')
->whereTime('create_time', 'today')
->where(['status' => 1, 'user_id' => $user_id])
->sum('money');
//本月预估收益
$month_earnings = Db::name('distribution_order_goods')
->whereTime('create_time', 'month')
->where(['status' => 1, 'user_id' => $user_id])
->sum('money');
//累计收益
$history_earnings = Db::name('distribution_order_goods')
->where(['status' => 2, 'user_id' => $user_id])
->sum('money');
$data = [
'user' => $user_info['user'],
'leader' => $user_info['leader'],
'fans' => $fans,//粉丝数量
'able_withdrawal' => $user_info['user']['earnings'],//可提现佣金
'today_earnings' => round($today_earnings, 2),//今天预估收益
'month_earnings' => round($month_earnings, 2),//本月预估收益
'history_earnings' => round($history_earnings, 2),//累计收益
];
return $data;
}
//可提现佣金
public static function getAbleWithdrawal($user_id)
{
$after_sale_time = ConfigServer::get('after_sale', 'refund_days');
$time = time() - ($after_sale_time * 24 * 60 * 60);
//可提现佣金
$orders = Db::name('order o')
->field('o.id, d.money')
->join('order_goods g', 'o.id = g.order_id')
->join('distribution_order_goods d', 'd.order_goods_id = g.id')
->where('o.create_time', '<', $time)
->where('o.order_status', Order::STATUS_FINISH)
->where('d.user_id', $user_id)
->where('d.status', DistributionOrder::STATUS_WAIT_HANDLE)
->select();
$able_withdrawal = 0;
if (!$orders) {
return $able_withdrawal;
}
foreach ($orders as $order) {
$check = Db::name('after_sale')
->where(['order_id' => $order['id']])
->where('status', 'in', [AfterSale::STATUS_WAIT_REFUND, AfterSale::STATUS_SUCCESS_REFUND])
->find();
if ($check) {
continue;
}
$able_withdrawal += $order['money'];
}
return $able_withdrawal;
}
/**
* 分销订单列表(待返佣,已结算,已失效)
* @param $user_id
* @param $get
* @return array|\PDOStatement|string|\think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function order($user_id, $get, $page, $size)
{
$where = [];
$where[] = ['d.user_id', '=', $user_id];
$status = $get['status'] ?? 0;
if ($status != 0) {
$where[] = ['d.status', '=', $status];
}
$field = 'o.order_sn, og.total_pay_price as pay_price, d.create_time, d.money, og.item_id, og.goods_num, d.status';
$count = Db::name('distribution_order_goods d')
->field($field)
->join('order_goods og', 'og.id = d.order_goods_id')
->join('order o', 'o.id = og.order_id')
->where($where)
->count();
$lists = Db::name('distribution_order_goods d')
->field($field)
->join('order_goods og', 'og.id = d.order_goods_id')
->join('order o', 'o.id = og.order_id')
->where($where)
->order('o.id desc')
->page($page, $size)
->select();
$item_ids = array_column($lists, 'item_id');
$goods = Db::name('goods_item i')
->join('goods g', 'i.goods_id = g.id')
->where('i.id', 'in', $item_ids)
->column('g.name, g.image, i.image as spec_image, i.spec_value_str', 'i.id');
foreach ($lists as &$item) {
$item_id = $item['item_id'];
if (!isset($goods[$item_id])) {
continue;
}
$info = $goods[$item_id];
$item['goods_name'] = $info['name'];
$item['spec_name'] = $info['spec_value_str'];
$item['image'] = UrlServer::getFileUrl(empty($info['spec_image']) ? $info['image'] : $info['spec_image']);
$item['status'] = DistributionOrder::getOrderStatus($item['status']);
$item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
}
$data = [
'list' => $lists,
'page' => $page,
'size' => $size,
'count' => $count,
'more' => is_more($count, $page, $size)
];
return $data;
}
/**
* 月度账单
* @param $user_id
* @param $get
* @param $page
* @param $size
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function getMonthBill($user_id, $page, $size)
{
$field = [
"FROM_UNIXTIME(d.create_time,'%Y年%m月') as date",
"FROM_UNIXTIME(d.create_time,'%Y') as year",
"FROM_UNIXTIME(d.create_time,'%m') as month",
'sum(d.money) as total_money',
'count(o.id) as order_num'
];
$count = Db::name('distribution_order_goods d')
->field($field)
->join('order_goods g', 'g.id = d.order_goods_id')
->join('order o', 'o.id = g.order_id')
->where(['d.user_id' => $user_id])
->where('d.status', 'in', [DistributionOrder::STATUS_WAIT_HANDLE, DistributionOrder::STATUS_SUCCESS])
->group('date')
->count();
$lists = Db::name('distribution_order_goods d')
->field($field)
->join('order_goods g', 'g.id = d.order_goods_id')
->join('order o', 'o.id = g.order_id')
->where(['d.user_id' => $user_id])
->where('d.status', 'in', [DistributionOrder::STATUS_WAIT_HANDLE, DistributionOrder::STATUS_SUCCESS])
->page($page, $size)
->group('date')
->select();
$data = [
'list' => $lists,
'page' => $page,
'size' => $size,
'count' => $count,
'more' => is_more($count, $page, $size)
];
return $data;
}
public static function getMonth($get, $user_id, $page, $size)
{
$year = $get['year'] ?? date('Y');
$month = $get['month'] ?? date('m');
//指定月份
list($y, $m, $t) = explode('-', date("$year-$month-t"));
$time_range = [
mktime(0, 0, 0, $m, 1, $y),
mktime(23, 59, 59, $m, $t, $y)
];
$field = 'o.order_sn, o.id as order_id, g.total_pay_price as pay_price, d.create_time, d.money, g.item_id, g.goods_num, d.status';
$count = Db::name('distribution_order_goods')->alias('d')
->field($field)
->join('order_goods g', 'g.id = d.order_goods_id')
->join('order o', 'o.id = g.order_id')
->where(['d.user_id' => $user_id])
->where('d.status', 'in', [DistributionOrder::STATUS_WAIT_HANDLE, DistributionOrder::STATUS_SUCCESS])
->where('d.create_time', 'between time', $time_range)
->count();
$lists = Db::name('distribution_order_goods')->alias('d')
->field($field)
->join('order_goods g', 'g.id = d.order_goods_id')
->join('order o', 'o.id = g.order_id')
->where(['d.user_id' => $user_id])
->where('d.status', 'in', [DistributionOrder::STATUS_WAIT_HANDLE, DistributionOrder::STATUS_SUCCESS])
->where('d.create_time', 'between time', $time_range)
->page($page, $size)
->select();
$item_ids = array_column($lists, 'item_id');
$goods = Db::name('goods_item i')
->join('goods g', 'i.goods_id = g.id')
->where('i.id', 'in', $item_ids)
->column('g.name, g.image, i.image as spec_image, i.spec_value_str', 'i.id');
$total_money = 0;
$order_ids = [];
foreach ($lists as &$item) {
$item_id = $item['item_id'];
if (!isset($goods[$item_id])) {
continue;
}
$info = $goods[$item_id];
$item['goods_name'] = $info['name'];
$item['spec_name'] = $info['spec_value_str'];
$item['image'] = UrlServer::getFileUrl(empty($info['spec_image']) ? $info['image'] : $info['spec_image']);
$item['status'] = DistributionOrder::getOrderStatus($item['status']);
$item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
$total_money += $item['money'];
if (!in_array($item['order_id'], $order_ids)) {
array_push($order_ids, $item['order_id']);
}
}
$data = [
'year' => $year,
'month' => $month,
'total_money' => $total_money,
'total_order' => count($order_ids),
'list' => $lists,
'page' => $page,
'size' => $size,
'count' => $count,
'more' => is_more($count, $page, $size)
];
return $data;
}
/**
* Desc: 生成用户扩展表
* @param $user_id
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function createUserDistribution($user_id)
{
$user_distribution = Db::name('user_distribution')
->where(['user_id' => $user_id])
->find();
if ($user_distribution) {
return true;
}
$data = [
'user_id' => $user_id,
'distribution_order_num' => 0,
'distribution_money' => 0,
'fans' => 0,
'create_time' => time(),
];
Db::name('user_distribution')->insert($data);
return true;
}
/**
* Desc: 取消订单后更新分销订单为已失效
* @param $order_id
* @throws Exception
* @throws \think\exception\PDOException
*/
public static function setDistributionOrderFail($order_id)
{
//订单取消后更新分销订单为已失效状态
return Db::name('distribution_order_goods d')
->join('order_goods og', 'og.id = d.order_goods_id')
->join('order o', 'o.id = og.order_id')
->where('o.id', $order_id)
->update([
'd.status' => DistributionOrder::STATUS_ERROR,
'd.update_time' => time(),
]);
}
/**
* Notes: 发生售后后,更新分销订单为已失效
* @param $order_goods_id
* @author 段誉(2021/5/13 17:38)
* @return int|string
* @throws Exception
* @throws \think\exception\PDOException
*/
public static function setFailByAfterSale($order_goods_id)
{
return Db::name('distribution_order_goods')
->where('order_goods_id', $order_goods_id)
->update([
'status' => DistributionOrder::STATUS_ERROR,
'update_time' => time(),
]);
}
/**
* Notes: 根据后台设置返回当前生成用户的分销会员状态(设置了全员分销,新生成的用户即为分销会员)
* @author 段誉(2021/4/7 14:48)
* @return int
*/
public static function isDistributionMember()
{
$is_distribution = 0;
//分销会员申请--1,申请分销; 2-全员分销;
$distribution = ConfigServer::get('distribution', 'member_apply', 1);
if ($distribution == 2) {
$is_distribution = 1;
}
return $is_distribution;
}
public static function fixAncestorRelation()
{
Db::startTrans();
try {
$userList = User::select()->toArray();
if (empty($userList)) {
throw new \Exception('没有用户,无需修复');
}
$updateEmptyData = [];
$updateData = [];
foreach($userList as $user) {
$my_ancestor_relation = self::myAncestorRelation($user);
$updateEmptyData[] = ['id' => $user['id'], 'ancestor_relation' => ''];
$updateData[] = ['id' => $user['id'], 'ancestor_relation' => $my_ancestor_relation];
}
// 先清除所有关系链
(new User())->saveAll($updateEmptyData);
// 重新设置关系链
(new User())->saveAll($updateData);
Db::commit();
return [
"flag" => true,
"msg" => '修复成功'
];
} catch (\Exception $e) {
Db::rollback();
return [
"flag" => false,
"msg" => $e->getMessage()
];
}
}
public static function myAncestorRelation($user)
{
if (empty($user['first_leader'])) {
return '';
}
return trim(self::findAncestorRelation($user['first_leader']), ',');
}
public static function findAncestorRelation($id, $flag = true)
{
static $ancestor_relation = '';
if ($flag) {
$ancestor_relation = '';
}
$ancestor_relation .= $id . ',';
$user = User::findOrEmpty($id)->toArray();
if (empty($user['first_leader'])) {
return $ancestor_relation;
}
return self::findAncestorRelation($user['first_leader'], false);
}
/**
* @notes 获取背景海报
* @return array
* @author cjhao
* @date 2021/11/29 12:00
*/
public static function getPoster(){
$poster = ConfigServer::get('invite', 'poster', '/images/share/share_user_bg.png');
$poster = empty($poster) ? $poster : UrlServer::getFileUrl($poster);
return ['poster'=>$poster];
}
}

View File

@ -14,8 +14,17 @@
namespace app\api\logic;
use Alipay\EasySDK\Kernel\Factory;
use app\api\cache\TokenCache;
use app\api\service\UserServer;
use app\common\cache\WebScanLoginCache;
use app\common\logic\AccountLogLogic;
use app\common\logic\BaseLogic;
use app\common\model\account\AccountLog;
use app\common\model\Client_;
use app\common\service\WeChatServer;
use app\common\service\ConfigServer;
use EasyWeChat\Kernel\Exceptions\Exception;
use app\api\service\{UserTokenService, WechatUserService};
use app\common\enum\{LoginEnum, user\UserTerminalEnum, YesNoEnum};
use app\common\service\{
@ -27,7 +36,7 @@ use app\common\service\{
wechat\WeChatRequestService
};
use app\common\model\user\{User, UserAuth};
use think\facade\{Db, Config};
use think\facade\{Cache, Db, Config};
/**
* 登录逻辑
@ -115,8 +124,173 @@ class LoginLogic extends BaseLogic
return false;
}
}
public static function authLogin($post)
{
try {
//通过code获取微信 openid
$response = self::getWechatResByCode($post);
$response['headimgurl'] = $post['headimgurl'] ?? '';
$response['nickname'] = $post['nickname'] ?? '';
//通过获取到的openID或unionid获取当前 系统 用户id
$user_id = self::getUserByWechatResponse($response);
} catch (Exception $e) {
self::setError('登录失败:' . $e->getMessage());
return false;
} catch (\think\Exception $e) {
self::setError('登录失败:' . $e->getMessage());
return false;
}
if (empty($user_id)) {
$user_info = UserServer::createUser($response, Client_::mnp);
} else {
$user_info = UserServer::updateUser($response, Client_::mnp, $user_id);
}
//验证用户信息
$check_res = self::checkUserInfo($user_info);
if (true !== $check_res) {
return self::setError($check_res);
}
//创建会话
$user_info['token'] = self::createSession($user_info['id'], Client_::mnp);
unset($user_info['id'], $user_info['disable']);
return $user_info;
}
public static function registerAward($user_id){
$register_award_integral_status = ConfigServer::get('marketing','register_award_integral_status',0);
$register_award_coupon_status = ConfigServer::get('marketing','register_award_coupon_status',0);
//赠送积分
if($register_award_integral_status){
$register_award_integral = ConfigServer::get('marketing','register_award_integral',0);
//赠送的积分
if($register_award_integral > 0){
\think\Db::name('user')->where(['id'=>$user_id])->setInc('user_integral',$register_award_integral);
AccountLogLogic::AccountRecord($user_id,$register_award_integral,1,AccountLog::register_add_integral,'');
}
}
//注册账号,首次进入首页时领取优惠券
$register_award_coupon = ConfigServer::get('marketing','register_award_coupon','');
if($register_award_coupon_status && $register_award_coupon){
Cache::tag('register_coupon')->set('register_coupon_'.$user_id,$register_award_coupon);
}
//会员等级
$user_level = Db::name('user_level')->where(['del'=>0,'growth_value'=>0])->find();
if($user_level){
Db::name('user')->where(['id'=>$user_id])->update(['level'=>$user_level['id']]);
}
}
/**
* Notes: 根据code 获取微信信息(openid, unionid)
* @param $post
* @author 段誉(2021/4/19 16:52)
* @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
* @throws Exception
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
*/
public static function getWechatResByCode($post)
{
// $config = WeChatServer::getMnpConfig();
$response = (new WeChatMnpService())->getMnpResByCode($post['code']);
// $app = Factory::miniProgram($config);
// $response = $app->auth->session($post['code']);
if (!isset($response['openid']) || empty($response['openid'])) {
throw new Exception('获取openID失败');
}
return $response;
}
/**
* Notes: 根据微信返回信息查询当前用户id
* @param $response
* @author 段誉(2021/4/19 16:52)
* @return mixed
*/
public static function getUserByWechatResponse($response)
{
$user_id = Db::name('user_auth au')
->join('user u', 'au.user_id=u.id')
->where(['u.del' => 0])
->where(function ($query) use ($response) {
$query->whereOr(['au.openid' => $response['openid']]);
if(isset($response['unionid']) && !empty($response['unionid'])){
$query->whereOr(['au.unionid' => $response['unionid']]);
}
})
->value('user_id');
return $user_id;
}
public static function checkUserInfo($user_info)
{
if (empty($user_info)) {
return '登录失败:user';
}
if ($user_info['disable']) {
return '账号已被禁用';
}
return true;
}
/**
* 创建会话
* @param $user_id
* @param $client
* @return string
* @throws \think\Exception
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
* @throws \think\exception\PDOException
*/
public static function createSession($user_id, $client)
{
//清除之前缓存
$token = Db::name('session')
->where(['user_id' => $user_id, 'client' => $client])
->value('token');
if($token) {
$token_cache = new TokenCache($token);
$token_cache->del();
}
$result = Db::name('session')
->where(['user_id' => $user_id, 'client' => $client])
->find();
$time = time();
$expire_time = $time + Config::get('project.token_expire_time');
$token = md5($user_id . $client . $time);
$data = [
'user_id' => $user_id,
'token' => $token,
'client' => $client,
'update_time' => $time,
'expire_time' => $expire_time,
];
if (empty($result)) {
Db::name('session')->insert($data);
} else {
Db::name('session')
->where(['user_id' => $user_id, 'client' => $client])
->update($data);
}
//更新登录信息
$login_ip = $ip = request()->ip();
Db::name('user')
->where(['id' => $user_id])
->update(['login_time' => $time, 'login_ip' => $login_ip]);
//创建新的缓存
(new TokenCache($token, ['token' => $token]))->set(300);
return $token;
}
/**
* @notes 退出登录
* @param $userInfo

View File

@ -0,0 +1,246 @@
<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | gitee下载https://gitee.com/likeshop_gitee
// | github下载https://github.com/likeshop-github
// | 访问官网https://www.likeshop.cn
// | 访问社区https://home.likeshop.cn
// | 访问手册http://doc.likeshop.cn
// | 微信公众号likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用未经许可不能去除前后端官方版权标识
// | likeshop系列产品收费版本务必购买商业授权购买去版权授权后方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的,任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------
namespace app\api\service;
use app\api\logic\DistributionLogic;
use app\api\logic\LoginLogic;
use app\common\model\Client_;
use app\common\model\noticesetting\NoticeSetting;
use app\common\model\UserLevel;
use app\common\service\storage\Driver as StorageDriver;
use app\common\service\UrlServer;
use think\facade\Db;
use think\Exception;
use app\common\service\ConfigServer;
use think\facade\Hook;
class UserServer
{
/**
* User: 意象信息科技 lr
* Desc: 通过小程序创建用户信息
* @param $response
* @param $client
* @return array|\PDOStatement|string|\think\Model|null
* @throws Exception
*/
public static function createUser($response, $client)
{
$user_info = [];
try {
$openid = $response['openid'];
$unionid = $response['unionid'] ?? '';
$avatar_url = $response['headimgurl'] ?? '';
$nickname = $response['nickname'] ?? '';
Db::startTrans();
// 获取存储引擎
$config = [
'default' => ConfigServer::get('storage', 'default', 'local'),
'engine' => ConfigServer::get('storage_engine')
];
$time = time(); //创建时间
$avatar = ''; //头像路径
if (empty($avatar_url)) {
$avatar = ConfigServer::get('website', 'user_image');
} else {
if ($config['default'] == 'local') {
$file_name = md5($openid . $time) . '.jpeg';
$avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
} else {
$avatar = 'uploads/user/avatar/' . md5($openid . $time) . '.jpeg';
$StorageDriver = new StorageDriver($config);
if (!$StorageDriver->fetch($avatar_url, $avatar)) {
throw new Exception( '头像保存失败:'. $StorageDriver->getError());
}
}
}
$data = [
'nickname' => $nickname,
'sn' => create_user_sn(),
'avatar' => $avatar,
'create_time' => $time,
'distribution_code' => generate_invite_code(),//分销邀请码
'is_distribution' => DistributionLogic::isDistributionMember(),
// 微信新用户
'is_new_user' => 1,
];
if (empty($nickname)) {
$data['nickname'] = '用户'.$data['sn'];
}
$user_id = Db::name('user')
->insertGetId($data);
$data = [
'user_id' => $user_id,
'openid' => $openid,
'create_time' => $time,
'unionid' => $unionid,
'client' => $client,
];
Db::name('user_auth')
->insert($data);
//生成会员分销扩展表
DistributionLogic::createUserDistribution($user_id);
// 生成分销会员基础表
\app\common\logic\DistributionLogic::add($user_id);
//消息通知
Hook::listen('notice', ['user_id' => $user_id, 'scene' => NoticeSetting::REGISTER_SUCCESS_NOTICE]);
//注册赠送优惠
LoginLogic::registerAward($user_id);
Db::commit();
$user_info = Db::name('user')
->field(['id', 'nickname', 'avatar', 'level', 'disable', 'distribution_code','is_new_user'])
->where(['id' => $user_id])
->find();
if (empty($user_info['avatar'])) {
$user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
} else {
$user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']);
}
} catch (Exception $e) {
Db::rollback();
throw new Exception($e->getMessage());
}
return $user_info;
}
/**
* 更新用户信息
* @param $response
* @param $client
* @param $user_id
* @return array|\PDOStatement|string|\think\Model|null
*/
public static function updateUser($response, $client, $user_id)
{
$time = time();
try {
$openid = $response['openid'];
$unionid = $response['unionid'] ?? '';
$avatar_url = $response['headimgurl'] ?? '';
$nickname = $response['nickname'] ?? '';
Db::startTrans();
//ios,android
if (in_array($client, [Client_::ios, Client_::android])) {
Db::name('user_auth')
->where(['openid' => $openid])
->update(['client' => $client]);
}
//用户已存在,但是无该端的授权信息,保存数据
$user_auth_id = Db::name('user_auth')
->where(['user_id' => $user_id, 'openid' => $openid])
->value('id');
if (empty($user_auth_id)) {
$data = [
'create_time' => $time,
'openid' => $openid,
'unionid' => $unionid,
'user_id' => $user_id,
'client' => $client,
];
Db::name('user_auth')
->insert($data);
}
$user_info = Db::name('user u')
->field(['u.nickname', 'u.avatar', 'u.level', 'u.id', 'au.unionid'])
->join('user_auth au', 'u.id=au.user_id')
->where(['au.openid' => $openid])
->find();
//无头像需要更新头像
if (empty($user_info['avatar'])) {
// 获取存储引擎
$config = [
'default' => ConfigServer::get('storage', 'default', 'local'),
'engine' => ConfigServer::get('storage_engine')
];
$avatar = ''; //头像路径
if ($config['default'] == 'local') {
$file_name = md5($openid . $time) . '.jpeg';
$avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
} else {
$avatar = 'uploads/user/avatar/' . md5($openid . $time) . '.jpeg';
$StorageDriver = new StorageDriver($config);
if (!$StorageDriver->fetch($avatar_url, $avatar)) {
throw new Exception( '头像保存失败:'. $StorageDriver->getError());
}
}
$data['avatar'] = $avatar;
$data['update_time'] = $time;
$data['nickname'] = $nickname;
Db::name('user')
->where(['id' => $user_info['id']])
->update($data);
}
//之前无unionid需要更新
if (empty($user_info['unionid']) && isset($unionid)) {
$data = [];
$data['unionid'] = $unionid;
$data['update_time'] = $time;
Db::name('user_auth')
->where(['user_id' => $user_info['id']])
->update($data);
}
$user_info = Db::name('user')
->where(['id' => $user_info['id']])
->field(['id', 'nickname', 'avatar', 'level', 'disable', 'distribution_code','is_new_user'])
->find();
if (empty($user_info['avatar'])) {
$user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
} else {
$user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']);
}
Db::commit();
} catch (Exception $e) {
Db::rollback();
throw new Exception($e->getMessage());
}
return $user_info;
}
}