This commit is contained in:
2025-04-26 11:07:05 +08:00
commit abf553c41b
4942 changed files with 930993 additions and 0 deletions

View File

@@ -0,0 +1,373 @@
<?php
namespace app\api\controller;
use app\api\model\JunkaCard;
use app\api\model\JunkaCardLog;
use app\api\model\JunkaCode;
use app\api\model\JunkaList;
use app\api\model\JunkaPurchcardLog;
use app\api\model\JunkaStore;
use app\api\model\Order;
use app\common\controller\Api;
use fast\Http;
use fast\Random;
use think\Db;
use think\Exception;
use think\Log;
/**
* 卡接口
*/
class Block extends Api
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
protected $key = 'LAUXWZVRTMPONKEHILPXSBST';
/**
* 获取卡种类
*/
public function getcard()
{
$order = new Order;
// 获取骏卡类型
// $junkatype_list = $order->getjunkatype();
// 购买骏卡
// $order = new Order;
// $junka_list = $order->getjunka([]);
// if(!$junka_list) {
// $this->error($order->getError());
// }
// echo '看看明显减少';
}
/**
* 提卡购卡接口
* @param string price 价格
* @param string number 数量
* @param string type 卡种类
* @param string order_no 订单号
* @param string sign 签名
* @param string store_id 商户ID
*/
public function takecard()
{
$post = $this->request->post();
$get = $this->request->get();
Log::write('购卡POST' . json_encode($post));
Log::write('购卡GET' .json_encode($get));
if(empty($post['price'])) {
$this->error('价格不能为空');
}
if(empty($post['number'])) {
$this->error('数量不能为空');
}
if(empty($post['type'])) {
$this->error('卡编码不能为空');
}
if(empty($post['order_no'])) {
$this->error('订单号不能为空');
}
if(empty($post['sign'])) {
$this->error('sign 不能为空');
}
$sign = $post['sign'];
unset($post['sign']);
$new_sign = md5(http_build_query(['order_no' => $post['order_no'], 'number' => $post['number']]) . '|' . $this->key);
if($new_sign != $sign) {
$this->error('签名不正确');
}
if(empty($get['store_id'])) {
$this->error('商户ID不能为空');
}
// 查询商家余额
$store = JunkaStore::where(['id' => $get['store_id']])->find();
if(!$store) {
$this->error('此商户不存在');
}
if($store->status == 2) {
$this->error('此商户已锁定');
}
$codelist = JunkaCode::where(['code' => $post['type']])->find();
if(!$codelist){
$this->error('卡不存在');
}
$JunkaPurchcardLog = JunkaPurchcardLog::where(['bill_id' => $post['order_no']])->find();
if($JunkaPurchcardLog) {
// $this->error('订单号已存在');
$this->success('ok', json_decode($JunkaPurchcardLog->data));
}
$p = $post['number'] * $codelist->par_value;
$total_num = $post['number'];
$minus_price = $p;
if(is_numeric($store->discount) && $store->discount > 0) { // 折扣
$minus_price = $p * ($store->discount / 100);
}
if($minus_price > $store->money) {
$this->error('商户可用余额不足');
}
try {
Db::startTrans();
$junka_list_data = JunkaList::where(['id' => 1])->find();
$order = new Order;
// // 查询库存
$inventory = $order->queryInventory($post['type'], $post['number']);
// // 库存够直接返回
if($inventory['number'] >= $post['number']) {
// 添加购卡记录
JunkaPurchcardLog::create([
'admin_id' => $store->admin_id,
'store_id' => $store->id,
'bill_id' => $post['order_no'],
'bill_time' => date('YmdHis'),
'product_code' => $post['type'],
'price' => $post['price'],
't_price' => $minus_price,
'card_price' => $codelist->par_value,
'product_num' => $post['number'],
'total_num' => $total_num,
'status' => 1,
'send_status' => 1,
'card_list_id' => $junka_list_data->id,
'card_list_name' => $junka_list_data->junka_name,
'data' => json_encode($inventory['card_data']),
]);
// 扣除商家余额
JunkaStore::moneychange($store, 0, 2, '购卡【库存】-' . $codelist->name, $post['order_no']);
Db::commit();
$this->success('ok', $inventory['card_data']);
// $this->success('ok');
}
$post['number'] = $post['number'] - $inventory['number'];
$k_minus_price = ($minus_price / $total_num) * $post['number'];
// 不够继续去购卡
$data = [
'agent_id' => config('junka.agent_id'),
'bill_id' => $post['order_no'],
'bill_time' => date('YmdHis'),
'product_code' => $post['type'],
'product_num' => $post['number'],
];
$order = new Order;
// 购卡
$junka_list = $order->getjunka($data, $store, true, $codelist, $post['price']);
if(!$junka_list) {
if(!empty($inventory['card_data'])) {
$data_n = $inventory['card_data'];
}else {
$data_n = [];
}
// 添加购卡记录
JunkaPurchcardLog::create([
'admin_id' => $store->admin_id,
'store_id' => $store->id,
'bill_id' => $post['order_no'],
'bill_time' => date('YmdHis'),
'product_code' => $post['type'],
'price' => $post['price'],
't_price' => $minus_price,
'card_price' => $codelist->par_value,
'product_num' => $post['number'],
'total_num' => $total_num,
'status' => 0,
'send_status' => 0,
'card_list_id' => $junka_list_data->id,
'card_list_name' => $junka_list_data->junka_name,
'data' => json_encode($data_n),
'notes' => $order->getError(),
]);
Db::commit();
$this->error($order->getError());
}
$junka_list_n = [];
foreach ($junka_list as $k => $v) {
$junka_list_n[$k]['card_number'] = $v['card_number'];
$junka_list_n[$k]['card_password'] = $v['card_password'];
}
if(!empty($inventory['card_data'])) {
// 扣除商家余额
JunkaStore::moneychange($store, 0, 2, '购卡【库存】-' . $codelist->name, $post['order_no']);
$junka_list_n = array_merge($junka_list_n, $inventory['card_data']);
}
// 扣除商家余额
JunkaStore::moneychange($store, $k_minus_price, 2, '购卡-' . $codelist->name, $post['order_no']);
// 添加购卡记录
JunkaPurchcardLog::create([
'admin_id' => $store->admin_id,
'store_id' => $store->id,
'bill_id' => $post['order_no'],
'bill_time' => date('YmdHis'),
'product_code' => $post['type'],
'price' => $post['price'],
't_price' => $minus_price,
'card_price' => $codelist->par_value,
'product_num' => $post['number'],
'total_num' => $total_num,
'status' => 1,
'send_status' => 1,
'card_list_id' => $junka_list_data->id,
'card_list_name' => $junka_list_data->junka_name,
'data' => json_encode($junka_list_n),
]);
Db::commit();
$this->success('ok', $junka_list_n);
// $this->success('ok');
}catch (Exception $e) {
Log::write('购卡错误---' . $e);
Db::rollback();
}
}
/**
* 回调/查询
*/
public function seach()
{
$this->success('ok');
$post = $this->request->post();
Log::write($post);
if(empty($post['order_no'])) {
$this->error('订单号不能为空');
}
if(empty($post['sign'])) {
$this->error('sign 不能为空');
}
$order = new Order;
$sign = $post['sign'];
unset($post['sign']);
$new_sign = md5(http_build_query(['order_no' => $post['order_no']]) . '|' . $this->key);
if($new_sign != $sign) {
$this->error('签名不正确');
}
try {
Db::startTrans();
$junkapur = JunkaPurchcardLog::where(['bill_id' => $post['order_no'], 'send_status' => 0])->find();
$junka_card = [];
$cardunlock = [];
if($junkapur) {
$data = json_decode($junkapur->data, true);
foreach ($data as $k => $v) {
$junka_card[] = [
'card_number' => $v['card_number'], // 卡号
'card_password' => $v['card_password'], // 卡密
];
$cardunlock[] = $v['card_number'];
}
$card = JunkaCard::where('card_number', 'in', $cardunlock)->select();
if($card) {
foreach ($card as $k => $v) {
if($v->status == 3) {
// 解锁 - 发货
$order->cardunlock($v, 2);
}else{
$v->status = 2;
$v->save();
}
}
}
$junkapur->send_status = 1;
$junkapur->save();
}
Db::commit();
$this->success('ok', $junka_card);
}catch (Exception $e) {
Log::write('查询错误---' . $e);
Db::rollback();
}
//
//
//
// $params['agent_id'] = config('junka.agent_id');
// $params['bill_id'] = $post['order_no'];
// $params['time_stamp'] = date('YmdHis');
// $params['sign'] = $order->getsign($params);
// $get = Http::get('http://Service.800j.com/UCard/UCardFetchQuery.aspx', $params);
// $get = $order->returnparamssave($get);
// $junka_card = [];
// $sql_arr = [];
// $purch = JunkaPurchcardLog::where(['bill_id' => $params['bill_id'], 'status' => 0])->find();
// if($get['ret_code'] == 0 && $get['ret_msg'] == '提卡成功') {
// $data = $order->decry($get['card_no_data']);
// foreach ($data as $k => $v) {
// $junka_data = explode(',', $v);
// $sql_arr[] = $junka_data[0];
// $junka_card[] = [
// 'card_number' => $junka_data[0], // 卡号
// 'card_password' => $junka_data[1], // 卡密
// ];
// }
// if($purch) {
// // 没发货
// $purch->status = 1;
// $purch->send_status = 1;
// JunkaCardLog::where(['bill_id' => $params['bill_id']])->update(['send_status' => 1, 'status' => 1]);
// JunkaCard::where('card_number', 'in', $sql_arr)->update(['status' => 2]);
// $purch->data = json_encode($junka_card);
// $this->success('ok', $junka_card);
// }
// $this->success('ok', $junka_card);
// }else {
// if($purch) {
// $purch->notes = $get['ret_msg'];
// $purch->save();
// }
// $this->error('查询失败');
// }
}
/**
* 撤单接口
*/
public function cancelorder()
{
$post = $this->request->post();
if(empty($post['order_no'])) {
$this->error('订单号不能为空');
}
if(empty($post['sign'])) {
$this->error('sign 不能为空');
}
$sign = $post['sign'];
unset($post['sign']);
$new_sign = md5(http_build_query(['order_no' => $post['order_no']]) . '|' . $this->key);
if($new_sign != $sign) {
$this->error('签名不正确');
}
$card_log = JunkaCardLog::where(['bill_id' => $post['order_no']])->with('junkacard')->find();
foreach ($card_log->junkacard as $k => $v) {
$junka_card[] = [
'card_number' => $v['card_number'], // 卡号
'card_price' => $v['card_price'], // 卡密
];
}
$order = new Order;
$order->cardlock($junka_card);
}
}

View File

@@ -0,0 +1,164 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Hook;
/**
* 公共接口
*/
class Common extends Api
{
protected $noNeedLogin = ['init', 'captcha'];
protected $noNeedRight = '*';
public function _initialize()
{
if (isset($_SERVER['HTTP_ORIGIN'])) {
header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
}
//跨域检测
check_cors_request();
if (!isset($_COOKIE['PHPSESSID'])) {
Config::set('session.id', $this->request->server("HTTP_SID"));
}
parent::_initialize();
}
/**
* 加载初始化
*
* @param string $version 版本号
* @param string $lng 经度
* @param string $lat 纬度
*/
public function init()
{
if ($version = $this->request->request('version')) {
$lng = $this->request->request('lng');
$lat = $this->request->request('lat');
//配置信息
$upload = Config::get('upload');
//如果非服务端中转模式需要修改为中转
if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
//临时修改上传模式为服务端中转
set_addon_config($upload['storage'], ["uploadmode" => "server"], false);
$upload = \app\common\model\Config::upload();
// 上传信息配置后
Hook::listen("upload_config_init", $upload);
$upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
}
$upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
$upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);
$content = [
'citydata' => Area::getCityFromLngLat($lng, $lat),
'versiondata' => Version::check($version),
'uploaddata' => $upload,
'coverdata' => Config::get("cover"),
];
$this->success('', $content);
} else {
$this->error(__('Invalid parameters'));
}
}
/**
* 上传文件
* @ApiMethod (POST)
* @param File $file 文件流
*/
public function upload()
{
Config::set('default_return_type', 'json');
//必须设定cdnurl为空,否则cdnurl函数计算错误
Config::set('upload.cdnurl', '');
$chunkid = $this->request->post("chunkid");
if ($chunkid) {
if (!Config::get('upload.chunking')) {
$this->error(__('Chunk file disabled'));
}
$action = $this->request->post("action");
$chunkindex = $this->request->post("chunkindex/d");
$chunkcount = $this->request->post("chunkcount/d");
$filename = $this->request->post("filename");
$method = $this->request->method(true);
if ($action == 'merge') {
$attachment = null;
//合并分片文件
try {
$upload = new Upload();
$attachment = $upload->merge($chunkid, $chunkcount, $filename);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
} elseif ($method == 'clean') {
//删除冗余的分片文件
try {
$upload = new Upload();
$upload->clean($chunkid);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success();
} else {
//上传分片文件
//默认普通上传文件
$file = $this->request->file('file');
try {
$upload = new Upload($file);
$upload->chunk($chunkid, $chunkindex, $chunkcount);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success();
}
} else {
$attachment = null;
//默认普通上传文件
$file = $this->request->file('file');
try {
$upload = new Upload($file);
$attachment = $upload->upload();
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
}
}
/**
* 验证码
* @param $id
* @return \think\Response
*/
public function captcha($id = "")
{
\think\Config::set([
'captcha' => array_merge(config('captcha'), [
'fontSize' => 44,
'imageH' => 150,
'imageW' => 350,
])
]);
$captcha = new Captcha((array)Config::get('captcha'));
return $captcha->entry($id);
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
/**
* 示例接口
*/
class Demo extends Api
{
//如果$noNeedLogin为空表示所有接口都需要登录才能请求
//如果$noNeedRight为空表示所有接口都需要验证权限才能请求
//如果接口已经设置无需登录,那也就无需鉴权了
//
// 无需登录的接口,*表示全部
protected $noNeedLogin = ['test', 'test1'];
// 无需鉴权的接口,*表示全部
protected $noNeedRight = ['test2'];
/**
* 测试方法
*
* @ApiTitle (测试名称)
* @ApiSummary (测试描述信息)
* @ApiMethod (POST)
* @ApiRoute (/api/demo/test/id/{id}/name/{name})
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiParams (name="id", type="integer", required=true, description="会员ID")
* @ApiParams (name="name", type="string", required=true, description="用户名")
* @ApiParams (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
* @ApiReturnParams (name="code", type="integer", required=true, sample="0")
* @ApiReturnParams (name="msg", type="string", required=true, sample="返回成功")
* @ApiReturnParams (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
* @ApiReturn ({
'code':'1',
'msg':'返回成功'
})
*/
public function test()
{
$this->success('返回成功', $this->request->param());
}
/**
* 无需登录的接口
*
*/
public function test1()
{
$this->success('返回成功', ['action' => 'test1']);
}
/**
* 需要登录的接口
*
*/
public function test2()
{
$this->success('返回成功', ['action' => 'test2']);
}
/**
* 需要登录且需要验证有相应组的权限
*
*/
public function test3()
{
$this->success('返回成功', ['action' => 'test3']);
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Ems as Emslib;
use app\common\model\User;
use think\Hook;
/**
* 邮箱验证码接口
*/
class Ems extends Api
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
}
/**
* 发送验证码
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $event 事件名称
*/
public function send()
{
$email = $this->request->post("email");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
$last = Emslib::get($email, $event);
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByEmail($email);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changeemail']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = Emslib::send($email, null, $event);
if ($ret) {
$this->success(__('发送成功'));
} else {
$this->error(__('发送失败'));
}
}
/**
* 检测验证码
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $event 事件名称
* @param string $captcha 验证码
*/
public function check()
{
$email = $this->request->post("email");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
$captcha = $this->request->post("captcha");
if ($event) {
$userinfo = User::getByEmail($email);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changeemail']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = Emslib::check($email, $captcha, $event);
if ($ret) {
$this->success(__('成功'));
} else {
$this->error(__('验证码不正确'));
}
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace app\api\controller;
use app\api\model\Order;
use app\common\controller\Api;
/**
* 首页接口
*/
class Index extends Api
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
/**
* 首页
*
*/
public function index()
{
$data = Order::getjunkatype();
$this->success('请求成功');
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;
/**
* 手机短信接口
*/
class Sms extends Api
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
/**
* 发送验证码
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $event 事件名称
*/
public function send()
{
$mobile = $this->request->post("mobile");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
if (!Hook::get('sms_send')) {
$this->error(__('请在后台插件管理安装短信验证插件'));
}
$ret = Smslib::send($mobile, null, $event);
if ($ret) {
$this->success(__('发送成功'));
} else {
$this->error(__('发送失败,请检查短信配置是否正确'));
}
}
/**
* 检测验证码
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $event 事件名称
* @param string $captcha 验证码
*/
public function check()
{
$mobile = $this->request->post("mobile");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
$captcha = $this->request->post("captcha");
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = Smslib::check($mobile, $captcha, $event);
if ($ret) {
$this->success(__('成功'));
} else {
$this->error(__('验证码不正确'));
}
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use fast\Random;
/**
* Token接口
*/
class Token extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/**
* 检测Token是否过期
*
*/
public function check()
{
$token = $this->auth->getToken();
$tokenInfo = \app\common\library\Token::get($token);
$this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
}
/**
* 刷新Token
*/
public function refresh()
{
//删除源Token
$token = $this->auth->getToken();
\app\common\library\Token::delete($token);
//创建新Token
$token = Random::uuid();
\app\common\library\Token::set($token, $this->auth->id, 2592000);
$tokenInfo = \app\common\library\Token::get($token);
$this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
}
}

View File

@@ -0,0 +1,348 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
/**
* 会员接口
*/
class User extends Api
{
protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
if (!Config::get('fastadmin.usercenter')) {
$this->error(__('User center already closed'));
}
}
/**
* 会员中心
*/
public function index()
{
$this->success('', ['welcome' => $this->auth->nickname]);
}
/**
* 会员登录
*
* @ApiMethod (POST)
* @param string $account 账号
* @param string $password 密码
*/
public function login()
{
$account = $this->request->post('account');
$password = $this->request->post('password');
if (!$account || !$password) {
$this->error(__('Invalid parameters'));
}
$ret = $this->auth->login($account, $password);
if ($ret) {
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 手机验证码登录
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $captcha 验证码
*/
public function mobilelogin()
{
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
$this->error(__('Captcha is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if ($user) {
if ($user->status != 'normal') {
$this->error(__('Account is locked'));
}
//如果已经有账号则直接登录
$ret = $this->auth->direct($user->id);
} else {
$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
}
if ($ret) {
Sms::flush($mobile, 'mobilelogin');
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 注册会员
*
* @ApiMethod (POST)
* @param string $username 用户名
* @param string $password 密码
* @param string $email 邮箱
* @param string $mobile 手机号
* @param string $code 验证码
*/
public function register()
{
$username = $this->request->post('username');
$password = $this->request->post('password');
$email = $this->request->post('email');
$mobile = $this->request->post('mobile');
$code = $this->request->post('code');
if (!$username || !$password) {
$this->error(__('Invalid parameters'));
}
if ($email && !Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$ret = Sms::check($mobile, $code, 'register');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
$ret = $this->auth->register($username, $password, $email, $mobile, []);
if ($ret) {
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Sign up successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 退出登录
* @ApiMethod (POST)
*/
public function logout()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$this->auth->logout();
$this->success(__('Logout successful'));
}
/**
* 修改会员个人信息
*
* @ApiMethod (POST)
* @param string $avatar 头像地址
* @param string $username 用户名
* @param string $nickname 昵称
* @param string $bio 个人简介
*/
public function profile()
{
$user = $this->auth->getUser();
$username = $this->request->post('username');
$nickname = $this->request->post('nickname');
$bio = $this->request->post('bio');
$avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
if ($username) {
$exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
if ($exists) {
$this->error(__('Username already exists'));
}
$user->username = $username;
}
if ($nickname) {
$exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
if ($exists) {
$this->error(__('Nickname already exists'));
}
$user->nickname = $nickname;
}
$user->bio = $bio;
$user->avatar = $avatar;
$user->save();
$this->success();
}
/**
* 修改邮箱
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $captcha 验证码
*/
public function changeemail()
{
$user = $this->auth->getUser();
$email = $this->request->post('email');
$captcha = $this->request->post('captcha');
if (!$email || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
$this->error(__('Email already exists'));
}
$result = Ems::check($email, $captcha, 'changeemail');
if (!$result) {
$this->error(__('Captcha is incorrect'));
}
$verification = $user->verification;
$verification->email = 1;
$user->verification = $verification;
$user->email = $email;
$user->save();
Ems::flush($email, 'changeemail');
$this->success();
}
/**
* 修改手机号
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $captcha 验证码
*/
public function changemobile()
{
$user = $this->auth->getUser();
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
$this->error(__('Mobile already exists'));
}
$result = Sms::check($mobile, $captcha, 'changemobile');
if (!$result) {
$this->error(__('Captcha is incorrect'));
}
$verification = $user->verification;
$verification->mobile = 1;
$user->verification = $verification;
$user->mobile = $mobile;
$user->save();
Sms::flush($mobile, 'changemobile');
$this->success();
}
/**
* 第三方登录
*
* @ApiMethod (POST)
* @param string $platform 平台名称
* @param string $code Code码
*/
public function third()
{
$url = url('user/index');
$platform = $this->request->post("platform");
$code = $this->request->post("code");
$config = get_addon_config('third');
if (!$config || !isset($config[$platform])) {
$this->error(__('Invalid parameters'));
}
$app = new \addons\third\library\Application($config);
//通过code换access_token和绑定会员
$result = $app->{$platform}->getUserInfo(['code' => $code]);
if ($result) {
$loginret = \addons\third\library\Service::connect($platform, $result);
if ($loginret) {
$data = [
'userinfo' => $this->auth->getUserinfo(),
'thirdinfo' => $result
];
$this->success(__('Logged in successful'), $data);
}
}
$this->error(__('Operation failed'), $url);
}
/**
* 重置密码
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $newpassword 新密码
* @param string $captcha 验证码
*/
public function resetpwd()
{
$type = $this->request->post("type", "mobile");
$mobile = $this->request->post("mobile");
$email = $this->request->post("email");
$newpassword = $this->request->post("newpassword");
$captcha = $this->request->post("captcha");
if (!$newpassword || !$captcha) {
$this->error(__('Invalid parameters'));
}
//验证Token
if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
$this->error(__('Password must be 6 to 30 characters'));
}
if ($type == 'mobile') {
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Sms::check($mobile, $captcha, 'resetpwd');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Sms::flush($mobile, 'resetpwd');
} else {
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
$user = \app\common\model\User::getByEmail($email);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Ems::check($email, $captcha, 'resetpwd');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Ems::flush($email, 'resetpwd');
}
//模拟一次登录
$this->auth->direct($user->id);
$ret = $this->auth->changepwd($newpassword, '', true);
if ($ret) {
$this->success(__('Reset password successful'));
} else {
$this->error($this->auth->getError());
}
}
}

View File

@@ -0,0 +1,163 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\User;
/**
* 验证接口
*/
class Validate extends Api
{
protected $noNeedLogin = '*';
protected $layout = '';
protected $error = null;
public function _initialize()
{
parent::_initialize();
}
/**
* 检测邮箱
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $id 排除会员ID
*/
public function check_email_available()
{
$email = $this->request->post('email');
$id = (int)$this->request->post('id');
$count = User::where('email', '=', $email)->where('id', '<>', $id)->count();
if ($count > 0) {
$this->error(__('邮箱已经被占用'));
}
$this->success();
}
/**
* 检测用户名
*
* @ApiMethod (POST)
* @param string $username 用户名
* @param string $id 排除会员ID
*/
public function check_username_available()
{
$username = $this->request->post('username');
$id = (int)$this->request->post('id');
$count = User::where('username', '=', $username)->where('id', '<>', $id)->count();
if ($count > 0) {
$this->error(__('用户名已经被占用'));
}
$this->success();
}
/**
* 检测昵称
*
* @ApiMethod (POST)
* @param string $nickname 昵称
* @param string $id 排除会员ID
*/
public function check_nickname_available()
{
$nickname = $this->request->post('nickname');
$id = (int)$this->request->post('id');
$count = User::where('nickname', '=', $nickname)->where('id', '<>', $id)->count();
if ($count > 0) {
$this->error(__('昵称已经被占用'));
}
$this->success();
}
/**
* 检测手机
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $id 排除会员ID
*/
public function check_mobile_available()
{
$mobile = $this->request->post('mobile');
$id = (int)$this->request->post('id');
$count = User::where('mobile', '=', $mobile)->where('id', '<>', $id)->count();
if ($count > 0) {
$this->error(__('该手机号已经占用'));
}
$this->success();
}
/**
* 检测手机
*
* @ApiMethod (POST)
* @param string $mobile 手机号
*/
public function check_mobile_exist()
{
$mobile = $this->request->post('mobile');
$count = User::where('mobile', '=', $mobile)->count();
if (!$count) {
$this->error(__('手机号不存在'));
}
$this->success();
}
/**
* 检测邮箱
*
* @ApiMethod (POST)
* @param string $mobile 邮箱
*/
public function check_email_exist()
{
$email = $this->request->post('email');
$count = User::where('email', '=', $email)->count();
if (!$count) {
$this->error(__('邮箱不存在'));
}
$this->success();
}
/**
* 检测手机验证码
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $captcha 验证码
* @param string $event 事件
*/
public function check_sms_correct()
{
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
$event = $this->request->post('event');
if (!\app\common\library\Sms::check($mobile, $captcha, $event)) {
$this->error(__('验证码不正确'));
}
$this->success();
}
/**
* 检测邮箱验证码
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $captcha 验证码
* @param string $event 事件
*/
public function check_ems_correct()
{
$email = $this->request->post('email');
$captcha = $this->request->post('captcha');
$event = $this->request->post('event');
if (!\app\common\library\Ems::check($email, $captcha, $event)) {
$this->error(__('验证码不正确'));
}
$this->success();
}
}