1397 lines
59 KiB
PHP
Raw Normal View History

2023-05-10 13:38:51 +08:00
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\controller\api;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\order\StoreRefundOrderRepository;
use app\common\repositories\system\notice\SystemNoticeConfigRepository;
use app\common\model\system\merchant\Merchant;
2023-05-10 13:38:51 +08:00
use app\common\repositories\user\UserRepository;
use app\common\repositories\user\UserSignRepository;
use app\common\repositories\wechat\RoutineQrcodeRepository;
use app\common\repositories\wechat\WechatUserRepository;
2023-08-25 12:47:34 +08:00
use app\common\repositories\system\RelevanceRepository;
2023-09-18 16:02:43 +08:00
use app\common\repositories\system\CacheRepository;
2023-09-13 15:23:09 +08:00
use app\common\repositories\system\merchant\MerchantIntentionRepository;
2023-05-10 13:38:51 +08:00
use app\validate\api\ChangePasswordValidate;
use app\validate\api\UserAuthValidate;
use crmeb\basic\BaseController;
use crmeb\services\MiniProgramService;
use crmeb\services\SmsService;
use crmeb\services\WechatService;
use crmeb\services\WechatTemplateMessageService;
use Exception;
use Firebase\JWT\JWT;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Overtrue\Socialite\AccessToken;
use Symfony\Component\HttpFoundation\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Cache;
2023-05-12 17:10:56 +08:00
use think\facade\Db;
2023-05-10 13:38:51 +08:00
use think\facade\Log;
use think\facade\Queue;
use crmeb\jobs\SendSmsJob;
2023-08-16 10:30:32 +08:00
use crmeb\jobs\TestJob;
2023-06-02 17:00:16 +08:00
use app\controller\api\Ceshi;
2023-05-10 13:38:51 +08:00
/**
* Class Auth
* @package app\controller\api
* @author xaboy
* @day 2020-05-06
*/
class Auth extends BaseController
{
public function dotest()
{
2023-08-16 10:30:32 +08:00
Queue::push(SendSmsJob::class, ['tempId' => 'ORDER_CREATE', 'id' => 101]);
return app('json')->success();
}
2023-05-10 13:38:51 +08:00
public function test()
{
2023-06-02 17:00:16 +08:00
$type = $this->request->param('type');
$res=[];
switch ($type) {
case 1:
$res = (app()->make(Ceshi::class))->Merchant_reconciliation_download();
break;
case 2:
$res = (app()->make(Ceshi::class))->Pay();
break;
case 3:
$res = (app()->make(Ceshi::class))->SettlementQuery();
break;
case 4:
$res = (app()->make(Ceshi::class))->OrderClosure();
break;
case 5:
$res = (app()->make(Ceshi::class))->OrderQuery();
break;
case 6:
$res = (app()->make(Ceshi::class))->refund();
break;
case 7:
$res = (app()->make(Ceshi::class))->NoticeSettlement();
break;
}
return app('json')->success(json_decode($res, true));
2023-05-10 13:38:51 +08:00
// $data = [
// 'tempId' => '',
// 'id' => '',
// ];
// Queue::push(SendSmsJob::class,$data);
// $status = app()->make(SystemNoticeConfigRepository::class)->getNoticeStatusByConstKey($data['tempId']);
// if ($status['notice_sms'] == 1) {
// SmsService::sendMessage($data);
// }
// if ($status['notice_wechat'] == 1) {
// app()->make(WechatTemplateMessageService::class)->sendTemplate($data);
// }
// if ($status['notice_routine'] == 1) {
// app()->make(WechatTemplateMessageService::class)->subscribeSendTemplate($data);
// }
}
/**
* @param UserRepository $repository
* @return mixed
* @throws DbException
* @author xaboy
* @day 2020/6/1
*/
public function login(UserRepository $repository)
{
$account = $this->request->param('account');
$auth_token = $this->request->param('auth_token');
if (Cache::get('api_login_freeze_' . $account))
return app('json')->fail('账号或密码错误次数太多,请稍后在尝试');
if (!$account)
return app('json')->fail('请输入账号');
$user = $repository->accountByUser($this->request->param('account'));
// if($auth_token && $user){
// return app('json')->fail('用户已存在');
// }
if (!$user) $this->loginFailure($account);
if (!password_verify($pwd = (string)$this->request->param('password'), $user['pwd'])) $this->loginFailure($account);
$auth = $this->parseAuthToken($auth_token);
if ($auth && !$user['wechat_user_id']) {
$repository->syncBaseAuth($auth, $user);
}
$user = $repository->mainUser($user);
$pid = $this->request->param('spread', 0);
$repository->bindSpread($user, intval($pid));
$tokenInfo = $repository->createToken($user);
$repository->loginAfter($user);
return app('json')->success($repository->returnToken($user, $tokenInfo));
}
/**
* TODO 登录尝试次数限制
* @param $account
* @param int $number
* @param int $n
* @author Qinii
* @day 7/6/21
*/
public function loginFailure($account, $number = 5, $n = 3)
{
$key = 'api_login_failuree_' . $account;
$numb = Cache::get($key) ?? 0;
$numb++;
if ($numb >= $number) {
$fail_key = 'api_login_freeze_' . $account;
Cache::set($fail_key, 1, 15 * 60);
throw new ValidateException('账号或密码错误次数太多,请稍后在尝试');
} else {
Cache::set($key, $numb, 5 * 60);
$msg = '账号或密码错误';
$_n = $number - $numb;
if ($_n <= $n) {
$msg .= ',还可尝试' . $_n . '次';
}
throw new ValidateException($msg);
}
}
/**
* @return mixed
* @author xaboy
* @day 2020/6/1
*/
public function userInfo()
{
$user = $this->request->userInfo()->hidden(['label_id', 'group_id', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price']);
$user->append(['service', 'topService', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread', 'total_recharge', 'lock_integral', 'total_integral']);
$data = $user->toArray();
$data['total_consume'] = $user['pay_price'];
$data['extension_status'] = systemConfig('extension_status');
if (systemConfig('member_status'))
$data['member_icon'] = $this->request->userInfo()->member->brokerage_icon ?? '';
if ($data['is_svip'] == 3)
2023-06-02 17:00:16 +08:00
$data['svip_endtime'] = date('Y-m-d H:i:s', strtotime("+100 year"));
2023-05-10 13:38:51 +08:00
2023-06-02 17:00:16 +08:00
$day = date('Y-m-d', time());
$key = 'sign_' . $user['uid'] . '_' . $day;
2023-05-10 13:38:51 +08:00
$data['sign_status'] = false;
if (Cache::get($key)) {
2023-06-02 17:00:16 +08:00
$data['sign_status'] = true;
2023-05-10 13:38:51 +08:00
} else {
2023-06-02 17:00:16 +08:00
$nu = app()->make(UserSignRepository::class)->getSign($user->uid, $day);
2023-05-10 13:38:51 +08:00
if ($nu) {
$data['sign_status'] = true;
2023-06-02 17:00:16 +08:00
Cache::set($key, true, new \DateTime($day . ' 23:59:59'));
2023-05-10 13:38:51 +08:00
}
}
2023-05-12 17:10:56 +08:00
$data['is_wsxx'] = 0;
$data['mer_info'] = [];
2023-08-22 09:55:37 +08:00
// 判断是否是商户,并且有没有完善信息
// 这里有点小问题以后要修改
2023-06-02 17:00:16 +08:00
$store_service = Db::name('store_service')->where('uid', $data['uid'])->find();
2023-09-14 17:33:56 +08:00
2023-05-12 17:10:56 +08:00
if ($store_service) {
2023-09-18 14:30:20 +08:00
$mer_arr = Db::name('merchant')->where('mer_id', $store_service['mer_id'])->where('is_del', 0)->field('type_id,mer_avatar,mer_banner,business_status,mer_info,category_id,service_phone,mer_address,uid,mer_name,create_time,update_time')->find();
2023-05-12 17:10:56 +08:00
if ($mer_arr && $mer_arr['mer_avatar'] != '' && $mer_arr['mer_banner'] != '' && $mer_arr['mer_info'] && $mer_arr['service_phone'] != '' && $mer_arr['mer_address'] != '') {
$data['is_wsxx'] = 1;
}
2023-09-06 14:21:26 +08:00
$data['mer_info'] = $mer_arr;
2023-09-06 14:17:56 +08:00
$typCode = Db::name('merchant_type')->where('mer_type_id', $mer_arr['type_id'] ?? 0)->value('type_code');
$data['mer_info']['type_code'] = $typCode;
2023-09-18 14:30:20 +08:00
// 交易申请状态0未申请 1申请中 2申请通过 3申请拒绝
2023-05-12 17:10:56 +08:00
}
2023-08-25 12:47:34 +08:00
$data['fan_num'] = app()->make(RelevanceRepository::class)->getUserFans($user->uid, 1, 1, 1);
$data['focus_num'] = app()->make(RelevanceRepository::class)->getUserFocus($user->uid, 1, 1, 1);
$data['community_num'] = Db::name('community')->where('uid', $user->uid)->whereIn('is_type', '1,2')->count();
2023-09-01 13:32:33 +08:00
$thirdparty = Db::name('user_thirdparty_token')->where('user_id', $user->uid)->select();
2023-09-01 16:26:00 +08:00
$thirdList = [];
foreach($thirdparty as $v) {
$temp = [
'account' => $v['account'],
'user_type' => $v['user_type'],
'token' => $v['token']
];
if ($v['expires_time'] <= date('Y-m-d H:i:s')) {
$temp['token'] = '';
}
$thirdList[] = $temp;
}
$data['thirdparty'] = $thirdList;
2023-05-10 13:38:51 +08:00
return app('json')->success($data);
}
/**
* @param UserRepository $repository
* @return mixed
* @author xaboy
* @day 2020/6/1
*/
public function logout(UserRepository $repository)
{
$repository->clearToken($this->request->token());
return app('json')->success('退出登录');
}
/**
* @return mixed
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @author xaboy
* @day 2020-05-11
*/
public function auth()
{
if (systemConfig('is_phone_login') === '1') {
return app('json')->fail('请绑定手机号');
}
$request = $this->request;
$oauth = WechatService::create()->getApplication()->oauth;
$oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
try {
$wechatInfo = $oauth->user()->getOriginal();
} catch (Exception $e) {
return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]);
}
if (!isset($wechatInfo['nickname'])) {
return app('json')->fail('授权失败[002]');
}
/** @var WechatUserRepository $make */
$make = app()->make(WechatUserRepository::class);
$user = $make->syncUser($wechatInfo['openid'], $wechatInfo);
if (!$user)
return app('json')->fail('授权失败[003]');
/** @var UserRepository $make */
$userRepository = app()->make(UserRepository::class);
$user[1] = $userRepository->mainUser($user[1]);
$pid = $this->request->param('spread', 0);
$userRepository->bindSpread($user[1], intval($pid));
$tokenInfo = $userRepository->createToken($user[1]);
$userRepository->loginAfter($user[1]);
return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
}
/**
* @return mixed
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @author xaboy
* @day 2020-05-11
*/
public function mpAuth()
{
list($code, $post_cache_key) = $this->request->params([
'code',
'cache_key',
], true);
if (systemConfig('is_phone_login') === '1') {
return app('json')->fail('请绑定手机号');
}
$userInfoCong = Cache::get('eb_api_code_' . $code);
if (!$code && !$userInfoCong)
return app('json')->fail('授权失败,参数有误');
$miniProgramService = MiniProgramService::create();
if ($code && !$userInfoCong) {
try {
$userInfoCong = $miniProgramService->getUserInfo($code);
Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
} catch (Exception $e) {
return app('json')->fail('获取session_key失败请检查您的配置', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
}
}
$data = $this->request->params([
['spread_spid', 0],
['spread_code', ''],
['iv', ''],
['encryptedData', ''],
]);
try {
//解密获取用户信息
$userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
} catch (Exception $e) {
if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
throw $e;
}
if (!$userInfo) return app('json')->fail('openid获取失败');
if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
$userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
if (!$userInfo['openId']) return app('json')->fail('openid获取失败');
/** @var WechatUserRepository $make */
$make = app()->make(WechatUserRepository::class);
$user = $make->syncRoutineUser($userInfo['openId'], $userInfo);
if (!$user)
return app('json')->fail('授权失败');
/** @var UserRepository $make */
$userRepository = app()->make(UserRepository::class);
$user[1] = $userRepository->mainUser($user[1]);
$code = intval($data['spread_code']['id'] ?? $data['spread_code']);
//获取是否有扫码进小程序
if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
$data['spread_spid'] = $info['third_id'];
}
$userRepository->bindSpread($user[1], intval($data['spread_spid']));
$tokenInfo = $userRepository->createToken($user[1]);
$userRepository->loginAfter($user[1]);
return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
}
2023-05-19 18:22:32 +08:00
/**
* 手机号用户绑定微信账号
* @param UserRepository $repository
* @return mixed
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function bindMp(UserRepository $repository)
{
list($code, $post_cache_key, $phone) = $this->request->params([
'code',
'cache_key',
'phone',
], true);
$userInfoCong = Cache::get('eb_api_code_' . $code);
if (!$code && !$userInfoCong)
return app('json')->fail('授权失败,参数有误');
$miniProgramService = MiniProgramService::create();
if ($code && !$userInfoCong) {
try {
$userInfoCong = $miniProgramService->getUserInfo($code);
Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
} catch (Exception $e) {
return app('json')->fail('获取session_key失败请检查您的配置', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
}
}
$data = $this->request->params([
['spread_spid', 0],
['spread_code', ''],
['iv', ''],
['encryptedData', ''],
]);
try {
//解密获取用户信息
$userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
} catch (Exception $e) {
if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
throw $e;
}
if (!$userInfo) return app('json')->fail('openid获取失败');
if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
$userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
if (!$userInfo['openId']) return app('json')->fail('openid获取失败');
/** @var WechatUserRepository $make */
$make = app()->make(WechatUserRepository::class);
$user = $make->syncRoutineUser($userInfo['openId'], $userInfo, false);
if (!$user) {
return app('json')->fail('授权失败');
}
$userInDb = $repository->accountByUser($phone);
if ($userInDb->save(['wechat_user_id' => $user[0]['wechat_user_id']]) === false) {
return app('json')->fail('授权失败');
}
return app('json')->success();
}
2023-06-30 17:27:43 +08:00
/**
* 绑定极光register_id
* @param UserRepository $repository
* @return mixed
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function bindJg(UserRepository $repository)
{
$phone = $this->request->param('phone');
$jgRegisterId = $this->request->param('jg_register_id');
$user = $repository->accountByUser($phone);
if ($user->save(['jg_register_id' => $jgRegisterId]) === false) {
return app('json')->fail('绑定失败');
}
return app('json')->success();
}
2023-05-10 13:38:51 +08:00
public function getCaptcha()
{
$codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4));
$key = uniqid(microtime(true), true);
Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300);
$captcha = $codeBuilder->build()->inline();
return app('json')->success(compact('key', 'captcha'));
}
protected function checkCaptcha($uni, string $code): bool
{
$cacheName = 'api_captche' . $uni;
if (!Cache::has($cacheName)) return false;
$key = Cache::get($cacheName);
$res = strtolower($key) == strtolower($code);
if ($res) Cache::delete($cacheName);
return $res;
}
public function verify(UserAuthValidate $validate)
{
2023-06-02 17:00:16 +08:00
$data = $this->request->params(['phone', ['type', 'login'], ['captchaType', ''], ['captchaVerification', ''], 'token']);
2023-05-10 13:38:51 +08:00
//二次验证
try {
aj_captcha_check_two($data['captchaType'], $data['captchaVerification']);
} catch (\Throwable $e) {
return app('json')->fail($e->getMessage());
}
$validate->sceneVerify()->check($data);
$sms_limit_key = 'sms_limit_' . $data['phone'];
$limit = Cache::get($sms_limit_key) ? Cache::get($sms_limit_key) : 0;
$sms_limit = systemConfig('sms_limit');
if ($sms_limit && $limit > $sms_limit) {
return app('json')->fail('请求太频繁请稍后再试');
}
// if(!env('APP_DEBUG', false)){
try {
$sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
$sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30;
SmsService::create()->send($data['phone'], 'VERIFICATION_CODE', ['code' => $sms_code, 'time' => $sms_time]);
} catch (Exception $e) {
return app('json')->fail($e->getMessage());
}
// }else{
// $sms_code = 1234;
// $sms_time = 5;
// }
$sms_key = app()->make(SmsService::class)->sendSmsKey($data['phone'], $data['type']);
Cache::set($sms_key, $sms_code, $sms_time * 60);
Cache::set($sms_limit_key, $limit + 1, 60);
//'短信发送成功'
return app('json')->success('短信发送成功');
}
public function smsLogin(UserAuthValidate $validate, UserRepository $repository)
{
2023-06-02 17:00:16 +08:00
$data = $this->request->params(['phone', 'sms_code', 'spread', 'auth_token', ['user_type', 'h5']]);
2023-05-10 13:38:51 +08:00
$validate->sceneSmslogin()->check($data);
$sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
2023-06-07 13:57:24 +08:00
if (!$sms_code && !env('APP_DEBUG')) return app('json')->fail('验证码不正确');
2023-05-10 13:38:51 +08:00
$user = $repository->accountByUser($data['phone']);
$auth = $this->parseAuthToken($data['auth_token']);
if (!$user) $user = $repository->registr($data['phone'], null, $data['user_type']);
2023-06-02 17:00:16 +08:00
if ($auth && !$user['wechat_user_id']) {
2023-05-10 13:38:51 +08:00
$repository->syncBaseAuth($auth, $user);
}
$user = $repository->mainUser($user);
$repository->bindSpread($user, intval($data['spread']));
$tokenInfo = $repository->createToken($user);
$repository->loginAfter($user);
return app('json')->success($repository->returnToken($user, $tokenInfo));
}
public function changePassword(ChangePasswordValidate $validate, UserRepository $repository)
{
$data = $this->request->params(['phone', 'sms_code', 'pwd']);
$validate->check($data);
$user = $repository->accountByUser($data['phone']);
if (!$user) return app('json')->fail('用户不存在');
$sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'change_pwd');
if (!$sms_code)
return app('json')->fail('验证码不正确');
$user->pwd = $repository->encodePassword($data['pwd']);
$user->save();
return app('json')->success('修改成功');
}
public function spread(UserRepository $userRepository)
{
$data = $this->request->params([
['spread_spid', 0],
['spread_code', null],
]);
if (isset($data['spread_code']['id']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']['id']))) {
$data['spread_spid'] = $info['third_id'];
}
$userRepository->bindSpread($this->request->userInfo(), intval($data['spread_spid']));
return app('json')->success();
}
/**
* TODO 注册账号
* @param UserAuthValidate $validate
* @param UserRepository $repository
* @return \think\response\Json
* @author Qinii
* @day 5/27/21
*/
public function register(UserAuthValidate $validate, UserRepository $repository)
{
2023-06-02 17:00:16 +08:00
$data = $this->request->params(['phone', 'sms_code', 'spread', 'pwd', 'auth_token', ['user_type', 'h5']]);
2023-05-10 13:38:51 +08:00
$validate->check($data);
$sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
2023-06-07 13:57:24 +08:00
if (!$sms_code && !env('APP_DEBUG')) {
2023-05-10 13:38:51 +08:00
return app('json')->fail('验证码不正确');
2023-06-07 13:57:24 +08:00
}
2023-05-10 13:38:51 +08:00
$user = $repository->accountByUser($data['phone']);
if ($user) return app('json')->fail('用户已存在');
$auth = $this->parseAuthToken($data['auth_token']);
$user = $repository->registr($data['phone'], $data['pwd'], $data['user_type']);
2023-06-02 17:00:16 +08:00
if ($auth) {
2023-05-10 13:38:51 +08:00
$repository->syncBaseAuth($auth, $user);
}
$user = $repository->mainUser($user);
$repository->bindSpread($user, intval($data['spread']));
$tokenInfo = $repository->createToken($user);
$repository->loginAfter($user);
return app('json')->success($repository->returnToken($user, $tokenInfo));
}
private function parseAuthToken($authToken)
{
$auth = Cache::get('u_try' . $authToken);
$auth && Cache::delete('u_try' . $authToken);
return $auth;
}
private function authInfo($auth, $createUser = false)
{
if (!in_array($auth['type'] ?? '', ['wechat', 'routine', 'apple', 'app_wechat']) || !isset($auth['auth']))
throw new ValidateException('授权信息类型有误');
$data = $auth['auth'];
if ($auth['type'] === 'routine') {
$code = $data['code'] ?? '';
$userInfoCong = Cache::get('eb_api_code_' . $code);
if (!$code && !$userInfoCong)
throw new ValidateException('授权失败,参数有误');
$miniProgramService = MiniProgramService::create();
if ($code && !$userInfoCong) {
try {
$userInfoCong = $miniProgramService->getUserInfo($code);
Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
} catch (Exception $e) {
throw new ValidateException('获取session_key失败请检查您的配置');
}
}
try {
//解密获取用户信息
$userInfo = $miniProgramService->encryptor($userInfoCong['session_key'], $data['iv'], $data['encryptedData']);
} catch (Exception $e) {
if ($e->getCode() == '-41003') throw new ValidateException('获取会话密匙失败');
throw $e;
}
if (!$userInfo) throw new ValidateException('openid获取失败');
if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';
$userInfo['unionId'] = $userInfoCong['unionid'] ?? $userInfo['unionId'] ?? '';
if (!$userInfo['openId']) throw new ValidateException('openid获取失败');
/** @var WechatUserRepository $make */
$make = app()->make(WechatUserRepository::class);
$user = $make->syncRoutineUser($userInfo['openId'], $userInfo, $createUser);
if (!$user)
throw new ValidateException('授权失败');
return $user;
} else if ($auth['type'] === 'wechat') {
$request = $this->request;
$oauth = WechatService::create()->getApplication()->oauth;
$oauth->setRequest(new Request($data, $data, [], [], [], $request->server(), $request->getContent()));
try {
$wechatInfo = $oauth->user()->getOriginal();
} catch (Exception $e) {
throw new ValidateException('授权失败[001]');
}
if (!isset($wechatInfo['nickname'])) {
throw new ValidateException('授权失败[002]');
}
/** @var WechatUserRepository $make */
$make = app()->make(WechatUserRepository::class);
$user = $make->syncUser($wechatInfo['openid'], $wechatInfo, false, $createUser);
if (!$user)
throw new ValidateException('授权失败[003]');
return $user;
} else if ($auth['type'] === 'app_wechat') {
$oauth = WechatService::create()->getApplication()->oauth;
try {
2023-06-02 17:00:16 +08:00
$wechatInfo = $oauth->user(new AccessToken(['access_token' => $data['code'], 'openid' => $data['openid']]))->getOriginal();
2023-05-10 13:38:51 +08:00
} catch (Exception $e) {
2023-06-02 17:00:16 +08:00
throw new ValidateException('授权失败[001]' . $e->getMessage());
2023-05-10 13:38:51 +08:00
}
$user = app()->make(WechatUserRepository::class)->syncAppUser($wechatInfo['unionid'], $wechatInfo, 'App', $createUser);
if (!$user)
throw new ValidateException('授权失败');
return $user;
} else if ($auth['type'] === 'apple') {
$identityToken = $data['userInfo']['identityToken'];
$tks = explode('.', $identityToken);
if (count($tks) != 3) {
throw new ValidateException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
if (null === ($payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64)))) {
throw new ValidateException('Invalid header encoding');
}
2023-06-02 17:00:16 +08:00
if ($payload->sub != $data['openId']) {
2023-05-10 13:38:51 +08:00
throw new ValidateException('授权失败');
}
$user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
], 'App', $createUser);
if (!$user)
throw new ValidateException('授权失败');
return $user;
}
}
public function authLogin()
{
$auth = $this->request->param('auth');
$users = $this->authInfo($auth, systemConfig('is_phone_login') !== '1');
if (!$users)
return app('json')->fail('授权失败');
$authInfo = $users[0];
$userRepository = app()->make(UserRepository::class);
$user = $users[1] ?? $userRepository->wechatUserIdBytUser($authInfo['wechat_user_id']);
$code = (int)($auth['auth']['spread_code']['id'] ?? $auth['auth']['spread_code'] ?? '');
//获取是否有扫码进小程序
if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {
$auth['auth']['spread'] = $info['third_id'];
}
if (!$user) {
$uni = uniqid(true, false) . random_int(1, 100000000);
$key = 'U' . md5(time() . $uni);
Cache::set('u_try' . $key, ['id' => $authInfo['wechat_user_id'], 'type' => $authInfo['user_type'], 'spread' => $auth['auth']['spread'] ?? 0], 3600);
return app('json')->status(201, compact('key'));
}
if ($auth['auth']['spread'] ?? 0) {
$userRepository->bindSpread($user, (int)($auth['auth']['spread']));
}
$tokenInfo = $userRepository->createToken($user);
$userRepository->loginAfter($user);
return app('json')->status(200, $userRepository->returnToken($user, $tokenInfo));
}
/**
* App微信登陆
* @param Request $request
* @return mixed
*/
public function appAuth()
{
$data = $this->request->params(['userInfo']);
if (systemConfig('is_phone_login') === '1') {
return app('json')->fail('请绑定手机号');
}
$user = app()->make(WechatUserRepository::class)->syncAppUser($data['userInfo']['unionId'], $data['userInfo']);
if (!$user)
return app('json')->fail('授权失败');
/** @var UserRepository $make */
$userRepository = app()->make(UserRepository::class);
$user[1] = $userRepository->mainUser($user[1]);
$tokenInfo = $userRepository->createToken($user[1]);
$userRepository->loginAfter($user[1]);
return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
}
public function getMerCertificate($merId)
{
$merId = (int)$merId;
$data = $this->request->params(['key', 'code']);
if (!$this->checkCaptcha($data['key'], $data['code']))
return app('json')->fail('验证码输入有误');
$certificate = merchantConfig($merId, 'mer_certificate') ?: [];
if (!count($certificate))
return app('json')->fail('该商户未上传证书');
return app('json')->success($certificate);
}
public function appleAuth()
{
$data = $this->request->params(['openId', 'nickname']);
if (systemConfig('is_phone_login') === '1') {
return app('json')->fail('请绑定手机号');
}
$user = app()->make(WechatUserRepository::class)->syncAppUser($data['openId'], [
'nickName' => (string)$data['nickname'] ?: '用户' . strtoupper(substr(md5(time()), 0, 12))
], 'apple');
if (!$user)
return app('json')->fail('授权失败');
/** @var UserRepository $make */
$userRepository = app()->make(UserRepository::class);
$user[1] = $userRepository->mainUser($user[1]);
$tokenInfo = $userRepository->createToken($user[1]);
$userRepository->loginAfter($user[1]);
return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
}
/**
* 注销账号
*/
public function cancel()
{
$userRepository = app()->make(UserRepository::class);
$user = $this->request->userInfo();
$order = app()->make(StoreOrderRepository::class)->search(['uid' => $user['uid'], 'paid' => 1])->where('StoreOrder.status', 0)->count();
$refund = app()->make(StoreRefundOrderRepository::class)->search(['uid' => $user['uid'], 'type' => 1])->count();
$key = $this->request->param('key');
$flag = false;
if ($user->now_money > 0 || $user->integral > 0 || $order > 0 || $refund > 0) {
$flag = true;
if (!$key) {
$uni = uniqid(true, false) . random_int(1, 100000000);
$key = 'L' . md5(time() . $uni);
Cache::set('u_out' . $user['uid'], $key, 600);
return app('json')->status(201, '该账号下有未完成业务,注销后不可恢复,您确定继续注销?', compact('key'));
}
}
if ($flag && (!$key || (Cache::get('u_out' . $user['uid']) != $key))) {
return app('json')->fail('操作超时');
}
$userRepository->cancel($user);
$userRepository->clearToken($user);
return app('json')->status(200, '注销成功');
}
public function mpPhone()
{
$code = $this->request->param('code');
$auth_token = $this->request->param('auth_token');
$iv = $this->request->param('iv');
$encryptedData = $this->request->param('encryptedData');
$miniProgramService = MiniProgramService::create();
$userInfoCong = Cache::get('eb_api_code_' . $code);
if (!$code && !$userInfoCong)
throw new ValidateException('授权失败,参数有误');
if ($code && !$userInfoCong) {
try {
$userInfoCong = $miniProgramService->getUserInfo($code);
Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
} catch (Exception $e) {
throw new ValidateException('获取session_key失败请检查您的配置');
}
}
$session_key = $userInfoCong['session_key'];
$data = $miniProgramService->encryptor($session_key, $iv, $encryptedData);
$userRepository = app()->make(UserRepository::class);
$phone = $data['purePhoneNumber'];
$user = $userRepository->accountByUser($phone);
// if($user && $auth_token){
// return app('json')->fail('用户已存在');
// }
$auth = $this->parseAuthToken($auth_token);
if ($user && $auth) {
$userRepository->syncBaseAuth($auth, $user);
} else if (!$user) {
if (!$auth) {
return app('json')->fail('操作超时');
}
$wechatUser = app()->make(WechatUserRepository::class)->get($auth['id']);
$user = $userRepository->syncWechatUser($wechatUser, 'routine');
$user->phone = $phone;
$user->account = $phone;
$user->save();
if ($auth['spread']) {
$userRepository->bindSpread($user, $auth['spread']);
}
}
$tokenInfo = $userRepository->createToken($user);
$userRepository->loginAfter($user);
return app('json')->success($userRepository->returnToken($user, $tokenInfo));
}
/**
* @return mixed
*/
public function ajcaptcha()
{
2023-06-02 17:00:16 +08:00
$captchaType = $this->request->get('captchaType');
if (!$captchaType) return app('json')->fail('请输入类型');
2023-05-10 13:38:51 +08:00
return app('json')->success(aj_captcha_create($captchaType));
}
/**
* 一次验证
* @return mixed
*/
public function ajcheck()
{
2023-06-02 17:00:16 +08:00
$token = $this->request->param('token', '');
$pointJson = $this->request->param('pointJson', '');
$captchaType = $this->request->param('captchaType', '');
2023-05-10 13:38:51 +08:00
try {
aj_captcha_check_one($captchaType, $token, $pointJson);
return app('json')->success();
} catch (\Throwable $e) {
return app('json')->fail(400336);
}
}
2023-06-14 14:34:03 +08:00
/**
* 发送短信验证码
* @return mixed
*/
public function verifyCode()
{
$data = $this->request->params(['phone', ['type', 'login']]);
$sms_limit_key = 'sms_limit_' . $data['phone'];
$limit = Cache::get($sms_limit_key) ? Cache::get($sms_limit_key) : 0;
$sms_limit = systemConfig('sms_limit');
if ($sms_limit && $limit > $sms_limit) {
return app('json')->fail('请求太频繁请稍后再试');
}
try {
$sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
$sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30;
SmsService::create()->send($data['phone'], 'VERIFICATION_CODE', ['code' => $sms_code, 'time' => $sms_time]);
} catch (Exception $e) {
return app('json')->fail($e->getMessage());
}
$sms_key = app()->make(SmsService::class)->sendSmsKey($data['phone'], $data['type']);
Cache::set($sms_key, $sms_code, $sms_time * 60);
Cache::set($sms_limit_key, $limit + 1, 60);
return app('json')->success('短信发送成功');
}
2023-08-10 16:28:38 +08:00
//物流系统扫码取货确认商家发货
2023-08-11 09:27:01 +08:00
public function deliveryGoods($id)
2023-08-10 16:28:38 +08:00
{
$orderSn = $this->request->param('order_sn');
2023-08-11 21:29:40 +08:00
$logisticsCode = $this->request->param('logistics_code') ?? '';
2023-08-10 16:28:38 +08:00
if (empty($orderSn)) {
return app('json')->fail('参数order_sn不能为空');
}
2023-08-11 21:29:40 +08:00
if (empty($logisticsCode)) {
app()->make(StoreOrderRepository::class)->deliveryGoods($id, $orderSn);
return app('json')->success('快递员扫描取件成功');
} else {
app()->make(StoreOrderRepository::class)->deliveryGoods($id, $orderSn, $logisticsCode);
return app('json')->success('快递员已完成送货');
}
2023-08-10 16:28:38 +08:00
}
//获取商户分类类别和店铺类型类别
public function merchantCate()
{
$cateList = Db::name('MerchantCategory')->field(['merchant_category_id', 'category_name'])->select();
2023-09-04 12:49:08 +08:00
// $typeList = [
// ['merchant_category_id' => Merchant::TypeStore ?? 0, 'category_name' => Merchant::TypeMap[Merchant::TypeStore] ?? ''],
// ['merchant_category_id' => Merchant::TypeTownSupplyChain ?? 0, 'category_name' => Merchant::TypeMap[Merchant::TypeTownSupplyChain] ?? ''],
// ['merchant_category_id' => Merchant::TypeSupplyChain ?? 0, 'category_name' => Merchant::TypeMap[Merchant::TypeSupplyChain] ?? '']
// ];
$typeList = Db::name('MerchantType')->where('is_allow_apply', 1)->field(['mer_type_id as merchant_category_id', 'type_name as category_name'])->select();
$data = [
'category' => $cateList,
'type' => $typeList
];
return app('json')->success($data);
}
//根据地址信息查询汇总信息
public function orderStatistics()
{
$cityCode = $this->request->param('city_code', '');
$districtCode = $this->request->param('district_code', '');
2023-08-23 14:33:35 +08:00
$streetCode = $this->request->param('street_code', '');
$villageCode = $this->request->param('village_code', '');
2023-08-22 12:55:41 +08:00
$brigadeId = $this->request->param('brigade_id', 0);
$categoryId = $this->request->param('category_id', 0);
$typeId = $this->request->param('type_id', 0);
2023-08-23 14:33:35 +08:00
$startDate = $this->request->param('start_date', '');
$endDate = $this->request->param('end_date', '');
2023-08-30 15:43:22 +08:00
$sql = $this->request->param('sql', 0);
$queryBuilder = Db::name('ProductOrderLog')->where('status', 1);
//根据商户分类店铺类型筛选商户
$queryMerBuilder = Db::name('Merchant');
if ($categoryId) {
$queryMerBuilder = $queryMerBuilder->where('category_id', $categoryId);
}
if ($typeId) {
$queryMerBuilder = $queryMerBuilder->where('type_id', $typeId);
}
$merIdArray = $queryMerBuilder->fetchSql(false)->column('mer_id');
$queryBuilder = $queryBuilder->whereIn('mer_id', $merIdArray);
if ($cityCode) {
2023-08-30 15:43:22 +08:00
$cityCodeArray = explode(',', $cityCode );
if (count($cityCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('city_code', $cityCode);
}
if (count($cityCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('city_code', $cityCodeArray);
}
}
if ($districtCode) {
2023-08-30 15:43:22 +08:00
$districtCodeArray = explode(',', $districtCode);
if (count($districtCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('district_code', $districtCode);
}
if (count($districtCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('district_code', $districtCodeArray);
}
}
if ($streetCode) {
2023-08-30 15:43:22 +08:00
$streetCodeArray = explode(',', $streetCode);
if (count($streetCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('street_code', $streetCode);
}
if (count($streetCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('street_code', $streetCodeArray);
}
}
if ($villageCode) {
2023-08-30 15:43:22 +08:00
$villageCodeArray = explode(',', $villageCode);
if (count($villageCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('village_code', $villageCode);
}
if (count($villageCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('village_code', $villageCodeArray);
}
}
if ($brigadeId) {
2023-08-30 15:43:22 +08:00
$brigadeIdArray = explode(',', $brigadeId);
if (count($brigadeIdArray) == 1) {
$queryBuilder = $queryBuilder->where('brigade_id', $brigadeId);
}
if (count($brigadeIdArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('brigade_id', $brigadeIdArray);
}
}
if ($startDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '>=', trim($startDate));
}
if ($endDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '<=', trim($endDate) . ' 23:59:59');
}
2023-08-30 15:43:22 +08:00
$orderNum = $queryBuilder->fetchSql((bool)$sql)->count();
$productNum = $queryBuilder->sum('product_num');
$totalPrice = $queryBuilder->sum('total_price');
$data = [
'where' => $this->request->param(),
'order_num' => $orderNum,
'product_num' => $productNum,
'total_price' => $totalPrice
];
return app('json')->success($data);
}
2023-08-22 11:59:43 +08:00
//根据地址信息查询订单列表
public function orderList()
{
[$page, $limit] = $this->getPage();
$cityCode = $this->request->param('city_code', '');
$districtCode = $this->request->param('district_code', '');
2023-08-23 14:33:35 +08:00
$streetCode = $this->request->param('street_code', '');
2023-08-22 11:59:43 +08:00
$villageCode = $this->request->param('village_code', '');
2023-08-22 12:55:41 +08:00
$brigadeId = $this->request->param('brigade_id', 0);
$categoryId = $this->request->param('category_id', 0);
$typeId = $this->request->param('type_id', 0);
2023-08-23 14:33:35 +08:00
$startDate = $this->request->param('start_date', '');
$endDate = $this->request->param('end_date', '');
2023-08-30 16:16:20 +08:00
$sql = $this->request->param('sql', 0);
2023-08-22 11:59:43 +08:00
$queryBuilder = Db::name('ProductOrderLog')->where('status', 1);
//根据商户分类店铺类型筛选商户
$queryMerBuilder = Db::name('Merchant');
if ($categoryId) {
$queryMerBuilder = $queryMerBuilder->where('category_id', $categoryId);
}
if ($typeId) {
$queryMerBuilder = $queryMerBuilder->where('type_id', $typeId);
}
$merIdArray = $queryMerBuilder->fetchSql(false)->column('mer_id');
$queryBuilder = $queryBuilder->whereIn('mer_id', $merIdArray);
2023-08-22 11:59:43 +08:00
if ($cityCode) {
2023-08-30 16:16:20 +08:00
$cityCodeArray = explode(',', $cityCode );
if (count($cityCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('city_code', $cityCode);
}
if (count($cityCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('city_code', $cityCodeArray);
}
2023-08-22 11:59:43 +08:00
}
if ($districtCode) {
2023-08-30 16:16:20 +08:00
$districtCodeArray = explode(',', $districtCode);
if (count($districtCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('district_code', $districtCode);
}
if (count($districtCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('district_code', $districtCodeArray);
}
2023-08-22 11:59:43 +08:00
}
if ($streetCode) {
2023-08-30 16:16:20 +08:00
$streetCodeArray = explode(',', $streetCode);
if (count($streetCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('street_code', $streetCode);
}
if (count($streetCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('street_code', $streetCodeArray);
}
2023-08-22 11:59:43 +08:00
}
if ($villageCode) {
2023-08-30 16:16:20 +08:00
$villageCodeArray = explode(',', $villageCode);
if (count($villageCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('village_code', $villageCode);
}
if (count($villageCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('village_code', $villageCodeArray);
}
2023-08-22 11:59:43 +08:00
}
if ($brigadeId) {
2023-08-30 16:16:20 +08:00
$brigadeIdArray = explode(',', $brigadeId);
if (count($brigadeIdArray) == 1) {
$queryBuilder = $queryBuilder->where('brigade_id', $brigadeId);
}
if (count($brigadeIdArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('brigade_id', $brigadeIdArray);
}
2023-08-22 11:59:43 +08:00
}
if ($startDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '>=', trim($startDate));
}
if ($endDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '<=', trim($endDate) . ' 23:59:59');
}
2023-08-30 16:16:20 +08:00
$count = $queryBuilder->fetchSql((bool)$sql)->count();
2023-08-22 12:55:41 +08:00
$list = $queryBuilder->setOption('field', [])->field(['id', 'order_id', 'product_num', 'product_price', 'total_price', 'city_code', 'district_code', 'street_code', 'village_code', 'brigade_id', 'create_time'])->order('id', 'desc')->page($page, $limit)->fetchSql(false)->select();
$orderIdList = [];
if ($list) {
$orderIdArray = $list->column('order_id');
if (count($orderIdArray) > 0) {
$orderIdList = Db::name('store_order')->whereIn('order_id', $orderIdArray)->fetchSql(false)->column('order_sn', 'order_id');
}
$list = $list->toArray();
};
foreach($list as $k=>$v) {
2023-08-22 13:06:44 +08:00
$list[$k]['order_sn'] = !empty($orderIdList[$v['order_id']]) ? $orderIdList[$v['order_id']] : '';
2023-08-22 12:55:41 +08:00
}
2023-08-22 11:59:43 +08:00
return app('json')->success(compact('count', 'list'));
}
2023-08-11 21:29:40 +08:00
2023-08-23 14:33:35 +08:00
//根据地址信息查询商家数
public function merStatistics()
{
$districtCode = $this->request->param('district_code', '');
$streetCode = $this->request->param('street_code', '');
$villageCode = $this->request->param('village_code', '');
$categoryId = $this->request->param('category_id', 0);
$typeId = $this->request->param('type_id', 0);
2023-08-23 14:33:35 +08:00
$startDate = $this->request->param('start_date', '');
$endDate = $this->request->param('end_date', '');
2023-08-30 16:16:20 +08:00
$sql = $this->request->param('sql', 0);
$villageIdArray = [];
if ($villageCode) {
$villageCodeArray = explode(',', $villageCode);
if (count($villageCodeArray) == 1) {
2023-08-30 16:27:21 +08:00
$villageIdArray = Db::name('GeoVillage')->where('village_code', $villageCode)->fetchSql(false)->column('village_id');
2023-08-30 16:16:20 +08:00
}
if (count($villageCodeArray) > 1) {
$villageIdArray = Db::name('GeoVillage')->whereIn('village_code', $villageCodeArray)->fetchSql(false)->column('village_id');
}
}
$queryBuilder = Db::name('Merchant');
if ($categoryId) {
$queryBuilder = $queryBuilder->where('category_id', $categoryId);
}
if ($typeId) {
$queryBuilder = $queryBuilder->where('type_id', $typeId);
}
2023-08-23 14:33:35 +08:00
if ($districtCode) {
2023-08-30 16:16:20 +08:00
$districtCodeArray = explode(',', $districtCode);
if (count($districtCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('area_id', $districtCode);
}
if (count($districtCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('area_id', $districtCodeArray);
}
2023-08-23 14:33:35 +08:00
}
if ($streetCode) {
2023-08-30 16:16:20 +08:00
$streetCodeArray = explode(',', $streetCode);
if (count($streetCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('street_id', $streetCode);
}
if (count($streetCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('street_id', $streetCodeArray);
}
2023-08-23 14:33:35 +08:00
}
2023-08-30 16:16:20 +08:00
if (count($villageIdArray)) {
$queryBuilder = $queryBuilder->whereIn('village_id', $villageIdArray);
2023-08-23 14:33:35 +08:00
}
if ($startDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '>=', trim($startDate));
}
if ($endDate) {
$queryBuilder = $queryBuilder->whereTime('create_time', '<=', trim($endDate) . ' 23:59:59');
}
2023-08-30 16:16:20 +08:00
$merNum = $queryBuilder->fetchSql((bool)$sql)->count();
2023-08-23 14:33:35 +08:00
$data = [
'where' => $this->request->param(),
'mer_num' => $merNum
];
return app('json')->success($data);
}
2023-08-23 14:47:33 +08:00
//根据地址信息查询商品数
public function goodsStatistics()
{
$districtCode = $this->request->param('district_code', '');
$streetCode = $this->request->param('street_code', '');
$villageCode = $this->request->param('village_code', '');
$categoryId = $this->request->param('category_id', 0);
$typeId = $this->request->param('type_id', 0);
2023-08-23 14:47:33 +08:00
$startDate = $this->request->param('start_date', '');
$endDate = $this->request->param('end_date', '');
2023-08-30 16:16:20 +08:00
$sql = $this->request->param('sql', 0);
$villageIdArray = [];
if ($villageCode) {
$villageCodeArray = explode(',', $villageCode);
if (count($villageCodeArray) == 1) {
2023-08-30 16:27:21 +08:00
$villageIdArray = Db::name('GeoVillage')->where('village_code', $villageCode)->fetchSql(false)->column('village_id');
2023-08-30 16:16:20 +08:00
}
if (count($villageCodeArray) > 1) {
$villageIdArray = Db::name('GeoVillage')->whereIn('village_code', $villageCodeArray)->fetchSql(false)->column('village_id');
}
}
$queryBuilder = Db::name('Merchant');
if ($categoryId) {
$queryBuilder = $queryBuilder->where('category_id', $categoryId);
}
if ($typeId) {
$queryBuilder = $queryBuilder->where('type_id', $typeId);
}
2023-08-23 14:47:33 +08:00
if ($districtCode) {
2023-08-30 16:16:20 +08:00
$districtCodeArray = explode(',', $districtCode);
if (count($districtCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('area_id', $districtCode);
}
if (count($districtCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('area_id', $districtCodeArray);
}
2023-08-23 14:47:33 +08:00
}
if ($streetCode) {
2023-08-30 16:16:20 +08:00
$streetCodeArray = explode(',', $streetCode);
if (count($streetCodeArray) == 1) {
$queryBuilder = $queryBuilder->where('street_id', $streetCode);
}
if (count($streetCodeArray) > 1) {
$queryBuilder = $queryBuilder->whereIn('street_id', $streetCodeArray);
}
2023-08-23 14:47:33 +08:00
}
2023-08-30 16:16:20 +08:00
if (count($villageIdArray)) {
$queryBuilder = $queryBuilder->whereIn('village_id', $villageIdArray);
2023-08-23 14:47:33 +08:00
}
$merIdArray = $queryBuilder->fetchSql(false)->column('mer_id');
$prodQueryBuilder = Db::name('StoreProduct')->where('is_show', 1)->where('status', 1)->whereIn('mer_id', $merIdArray);
if ($startDate) {
$prodQueryBuilder = $prodQueryBuilder->whereTime('create_time', '>=', trim($startDate));
}
if ($endDate) {
$prodQueryBuilder = $prodQueryBuilder->whereTime('create_time', '<=', trim($endDate) . ' 23:59:59');
}
2023-08-30 16:16:20 +08:00
$goodsNum = $prodQueryBuilder->fetchSql((bool)$sql)->count();
2023-08-23 14:47:33 +08:00
$data = [
'where' => $this->request->param(),
2023-08-30 16:16:20 +08:00
'goods_num' => $goodsNum,
'merid' => $merIdArray
2023-08-23 14:47:33 +08:00
];
return app('json')->success($data);
2023-08-23 14:47:33 +08:00
}
2023-09-01 13:07:04 +08:00
//同步其他小程序token信息
//userType小程序类型1供销工作平台 2物流系统
public function syncToken()
{
$account = $this->request->param('account', '');
$userType = $this->request->param('user_type', 1);
$token = $this->request->param('token', '');
$expiresTime = $this->request->param('expires_time', '');
$user = $this->request->userInfo();
$uid = $user->uid;
2023-09-01 13:32:33 +08:00
$tokenInfo = Db::name('user_thirdparty_token')->where(['user_type'=>$userType, 'user_id'=>$uid])->find();
if ($tokenInfo) {
$updData = [
'account' => $account,
'token' => $token,
'expires_time' => $expiresTime,
'create_time' => date('Y-m-d H:i:s')
];
Db::name('user_thirdparty_token')->where(['user_type'=>$userType, 'user_id'=>$uid])->update($updData);
} else {
$insertData = [
'user_id' => $uid,
'user_type' => $userType,
'account' => $account,
'token' => $token,
'expires_time' => $expiresTime,
'create_time' => date('Y-m-d H:i:s')
];
Db::name('user_thirdparty_token')->insert($insertData);
}
return app('json')->success($this->request->param());
2023-09-01 13:07:04 +08:00
}
2023-09-01 13:55:00 +08:00
//获取全局配置信息
public function globalConfig()
{
$getUrl = env('TASK_WORKER_HOST_URL') . '/api/index/config';
2023-09-01 15:10:41 +08:00
$os = 'pc';
$userAgent = request()->header('user-agent');
$isAndroid = stripos($userAgent, 'android') !== false;
if ($isAndroid) {
$os = 'android';
}
$isIOS = stripos($userAgent, 'iphone') !== false;
if ($isIOS) {
$os = 'ios';
}
$getUrl .= '?os=' . $os;
2023-09-01 13:55:00 +08:00
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
if (!empty($data) && is_string($data)) {
$miniappInfo = json_decode($data, true);
return app('json')->success($miniappInfo['data'] ?? []);
}
return app('json')->success([]);
}
2023-09-08 17:09:32 +08:00
//根据street_id获取商户信息
public function regionMerchant($street_id)
{
[$page, $limit] = $this->getPage();
$queryBuilder = Db::name('Merchant')->where('status', 1)->where('is_del', 0)->where('street_id', $street_id);
$count = $queryBuilder->count();
$list = $queryBuilder->setOption('field', [])->field(['mer_id', 'category_id', 'type_id', 'mer_name', 'area_id', 'street_id', 'village_id', 'mer_address', 'long', 'lat', 'create_time'])->order('mer_id', 'desc')->page($page, $limit)->fetchSql(false)->select();
return app('json')->success(compact('count', 'list'));
}
2023-09-08 17:09:32 +08:00
//获取app版本更新信息
public function appVersion()
{
2023-09-13 17:39:06 +08:00
$brandArray = [
2023-09-13 18:11:44 +08:00
'huawei',
'honor',
'iphone',
'samsung',
'xiaomi',
'redmi',
'mi',
'oppo',
'vivo',
'nokia',
'meizu',
'moto'
2023-09-13 17:39:06 +08:00
];
2023-09-11 15:53:44 +08:00
$type = $this->request->param('type', '-1');
2023-09-08 17:09:32 +08:00
$version = $this->request->param('version', '');
2023-09-11 15:53:44 +08:00
$phoneBrand = $this->request->param('phone_brand', '');
$queryBuilder = Db::name('AppUpdate')->where('type', $type);
2023-09-11 16:01:44 +08:00
if ($type == 3) {
$android = (Db::name('AppUpdate')->where('type', 1)->where('phone_brand','')->order('id', 'desc')->find()) ?? (object)[];
$ios = (Db::name('AppUpdate')->where('type', 2)->where('phone_brand','')->order('id', 'desc')->find()) ?? (object)[];
return app('json')->success(compact('android', 'ios'));
2023-09-11 16:04:22 +08:00
} else {
2023-09-11 16:01:44 +08:00
if ($version) {
$queryBuilder = $queryBuilder->where('version', '>', $version);
}
if ($phoneBrand) {
2023-09-15 09:39:04 +08:00
$pos = false;
2023-09-13 18:11:44 +08:00
foreach($brandArray as $b) {
$pos = stripos($phoneBrand, $b);
if ($pos !== false) {
2023-09-13 19:07:35 +08:00
$queryBuilder = $queryBuilder->where('phone_brand', $b);
2023-09-13 18:11:44 +08:00
}
}
2023-09-15 09:39:04 +08:00
if ($pos === false) {
$queryBuilder = $queryBuilder->where('phone_brand', '');
}
2023-09-11 16:01:44 +08:00
}
2023-09-15 09:39:04 +08:00
$appInfo = ($queryBuilder->order('version', 'desc')->fetchSql(false)->find()) ?? (object)[];
2023-09-11 15:53:44 +08:00
}
2023-09-11 16:01:44 +08:00
2023-09-08 17:09:32 +08:00
return app('json')->success(compact('appInfo'));
}
2023-09-13 15:23:09 +08:00
//同步商户状态信息
public function merchantStatus($id)
{
2023-09-18 15:48:09 +08:00
// business_status 交易申请状态0未申请 1申请中 2申请通过 3申请拒绝
2023-09-19 13:51:09 +08:00
Log::info("同步商户申请状态URL" . request()->host() . request()->url());
2023-09-19 13:41:37 +08:00
Log::info("同步商户申请状态数据:" . json_encode(request()->param()));
2023-09-13 15:23:09 +08:00
$repository = app()->make(MerchantIntentionRepository::class);
if (!$repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
2023-09-14 17:33:56 +08:00
return app('json')->fail('数据不存在');
2023-09-19 10:55:01 +08:00
$status = $this->request->post('status', 0);
$type = $this->request->post('type', 1);
2023-09-19 10:06:21 +08:00
if ($type == 1) {
//商户入驻申请
$data['status'] = $status;
$data['create_mer'] = -1;
$data['fail_msg'] = $status == 1 ? '自动审核通过' : '自动审核拒绝';
$repository->updateStatus($id, $data);
} else {
//商户交易申请
2023-09-19 14:31:25 +08:00
Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 2)->update(['status' => ($status == 1 ? 1 : 2)]);
$merId = Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 2)->value('mer_id', 0);
2023-09-19 11:23:51 +08:00
Db::name('merchant')->where('mer_id', $merId)->where('status', 1)->update(['business_status' => ($status == 1 ? 2 : 3)]);
2023-09-19 10:06:21 +08:00
}
2023-09-13 15:29:48 +08:00
return app('json')->success('同步成功');
2023-09-13 15:23:09 +08:00
}
2023-09-18 16:02:43 +08:00
//获取交易申请协议
public function businessAgree()
{
$repository = app()->make(CacheRepository::class);
2023-09-19 10:55:01 +08:00
//sys_intention_agree business_apply_agree
$type = $this->request->get('type', 'sys_intention_agree');
$typeArray = ['sys_intention_agree', 'business_apply_agree'];
if (!in_array($type, $typeArray)) {
return app('json')->fail('协议key错误');
}
$data = $repository->getResult($type);
2023-09-18 16:02:43 +08:00
return app('json')->success($data);
}
2023-05-10 13:38:51 +08:00
}