1792 lines
77 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;
2024-03-09 10:43:42 +08:00
use app\common\model\store\consumption\StoreConsumptionDetail;
use app\common\model\store\consumption\StoreConsumptionUser;
use app\common\model\store\order\StoreGroupOrder;
use app\common\model\store\order\StoreOrder;
use app\common\model\store\order\StoreOrderOther;
use app\common\model\store\order\StoreOrderProduct;
use app\common\model\store\order\StoreOrderStatus;
use app\common\model\store\order\StoreRefundOrder;
use app\common\model\system\merchant\FinancialRecord;
use app\common\model\user\UserAddress;
use app\common\model\user\UserBill;
use app\common\model\user\UserRecharge;
2023-05-10 13:38:51 +08:00
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\order\StoreRefundOrderRepository;
use app\common\repositories\system\notice\SystemNoticeConfigRepository;
2023-09-28 14:49:59 +08:00
use app\common\repositories\system\config\ConfigValueRepository;
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 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;
2024-03-09 10:43:42 +08:00
use think\db\Query;
2023-05-10 13:38:51 +08:00
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-09-27 19:40:25 +08:00
use app\common\service\JgPush;
2023-08-16 10:30:32 +08:00
use crmeb\jobs\TestJob;
2023-09-23 11:23:30 +08:00
use crmeb\services\PayService;
use crmeb\services\CombinePayService;
use app\common\model\user\User;
2023-10-10 14:54:50 +08:00
use app\common\service\TopClient;
2023-06-02 17:00:16 +08:00
use app\controller\api\Ceshi;
2023-10-10 14:54:50 +08:00
use taobao\request\TbkItemInfoGetRequest;
use app\common\repositories\store\product\ProductRepository;
2023-11-20 16:15:45 +08:00
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
2023-10-10 14:54:50 +08:00
use think\facade\App;
2023-05-10 13:38:51 +08:00
/**
* Class Auth
* @package app\controller\api
* @author xaboy
* @day 2020-05-06
*/
class Auth extends BaseController
{
2023-11-20 16:15:45 +08:00
public function parseToken(UserRepository $repository)
{
$token = $this->request->param('token');
$app_key = 'ae47e94a7dcd1fdfacb499b60e361a8d';
try {
JWT::$leeway = 10; //当前时间减去10秒时间留点余地
// jwt ^5.0
// $decoded = JWT::decode($token, Config::get('app.app_key', 'default'), array('HS256'));
// jwt ^6.9
// $decoded = JWT::decode($token, new Key(env('app.app_key', '123456'), 'HS256'));
$decoded = JWT::decode($token, new Key($app_key, 'HS256'));
$decodedArray = json_decode(json_encode($decoded), true);
$jwtData = $decodedArray['data'] ?? [];
if (empty($jwtData['phone'])) {
return app('json')->fail('解析数据缺少phone');
}
$user = $repository->accountByUser($jwtData['phone']);
$user_type = 'app';
if (!$user) $user = $repository->registr($jwtData['phone'], null, $user_type);
$user = $repository->mainUser($user);
$tokenInfo = $repository->createToken($user);
$repository->loginAfter($user);
return app('json')->success($repository->returnToken($user, $tokenInfo));
} catch(\Firebase\JWT\SignatureInvalidException $e) {
return app('json')->fail('签名错误');
} catch(\Firebase\JWT\BeforeValidException $e) {
return app('json')->fail('token无效');
} catch(\Firebase\JWT\ExpiredException $e) {
return app('json')->fail('token已过期');
} catch(\Exception $e) {
return app('json')->fail('非法请求');
}
}
2023-10-10 14:54:50 +08:00
public function caiji()
{
2023-10-10 14:54:50 +08:00
$url=$this->request->host();
2023-10-10 14:54:50 +08:00
$parmas = $this->request->param();
2023-10-10 14:54:50 +08:00
$query=parse_url($parmas['url']);
$itemId=$this->convertUrlQuery($query['query']);
2023-10-10 14:54:50 +08:00
$c = new TopClient;
$c->appkey = '34537213';
$c->secretKey = '4a35f3657156580c1f533750295c54c4';
$req = new TbkItemInfoGetRequest;
$req->setNumIids($itemId['itemId']);
$resp = $c->execute($req);
2023-10-10 14:54:50 +08:00
$res=$resp->results->n_tbk_item;
$images=[];
$filename = basename($res->pict_url); // 获取文件名
$destination = public_path('uploads').'img/' . $filename; // 目标路径
$pict_url= $url.'/uploads/img/'.$filename;
file_put_contents($destination, file_get_contents($res->pict_url));
2024-03-08 15:56:34 +08:00
2023-10-10 14:54:50 +08:00
if($resp && isset($resp->small_images) && isset($resp->small_images->string)){
foreach($resp->small_images->string as $k=>$v){
$filename = basename($v); // 获取文件名
$destination = public_path('uploads').'img/' . $filename; // 目标路径
file_put_contents($destination, file_get_contents($v));
$images[]=$url.'/uploads/img/'.$filename;
}
2023-10-10 16:49:36 +08:00
}
2023-10-10 14:54:50 +08:00
$data=[
2023-10-10 14:54:50 +08:00
"image" => $pict_url,
2023-10-10 14:54:50 +08:00
"slider_image" =>$images,
"store_name" => json_decode(json_encode($res->title),true)[0],
"store_info" => json_decode(json_encode($res->cat_leaf_name),true)[0],
2023-10-10 14:54:50 +08:00
"keyword" => "",
"bar_code" => "",
"guarantee_template_id" => "",
"cate_id" => $parmas['cate_id'],
"mer_cate_id" => [],
"unit_name" => $parmas['unit_name'],
"sort" => 0,
2023-10-10 14:54:50 +08:00
"is_show" => "",
2023-10-10 14:54:50 +08:00
"is_good" => 0,
"is_gift_bag" => 0,
"integral_rate" => -1,
"video_link" => "",
"temp_id" => 399,
"content" => $images,
"spec_type" => 0,
"extension_type" => 0,
"attr" => [],
"mer_labels" => [],
"delivery_way" => [
2023-10-10 14:54:50 +08:00
0 => "1",
1 => "2"
2023-10-10 14:54:50 +08:00
],
"delivery_free" => 0,
"param_temp_id" => [],
"extend" => [],
"source_product_id" => "",
"stock" => "100",
"brand_id" => "",
"once_max_count" => 0,
"once_min_count" => 0,
"pay_limit" => 0,
"attrValue" => [
2023-10-10 14:54:50 +08:00
0 => [
"image" => $pict_url,
"price" => bcsub($res->reserve_price,($res->reserve_price*0.05),2),
"cost" => 0,
"ot_price" => 0,
"svip_price" => null,
"stock" => 100,
"bar_code" => "",
"weight" => 0,
"volume" => 0,
],
2023-10-10 14:54:50 +08:00
],
"give_coupon_ids" => [],
"type" => 0,
"svip_price" => 0,
"svip_price_type" => 0,
"params" => [],
"mer_id" => $parmas['mer_id'],
2023-10-10 14:54:50 +08:00
"status" => 0,
2023-10-10 14:54:50 +08:00
"mer_status" => 1,
"rate" => 3,
2023-10-10 14:54:50 +08:00
];
$a= app()->make( ProductRepository::class)->create($data,0,1);
2023-10-10 14:54:50 +08:00
// 下载图片并保存到目标路径
return app('json')->success($a);
}
function convertUrlQuery($query)
{
2023-10-10 14:54:50 +08:00
$queryParts = explode('&', $query);
2024-03-08 15:56:34 +08:00
2023-10-10 14:54:50 +08:00
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
2024-03-08 15:56:34 +08:00
2023-10-10 14:54:50 +08:00
return $params;
2023-10-10 14:54:50 +08:00
}
public function dotest()
{
2023-09-27 19:40:25 +08:00
$data = [
"tempId" => "ADMIN_PAY_SUCCESS_CODE",
2023-10-10 14:54:50 +08:00
"id" => 113
2023-09-23 11:23:30 +08:00
];
2023-09-27 19:40:25 +08:00
try {
$client = app()->make(JgPush::class);
Log::info('JgPush送发送数据' . json_encode($data));
$client->send($data['tempId'], $data);
2023-09-28 18:22:38 +08:00
return app('json')->success(json_encode($data, true));
2023-09-27 19:40:25 +08:00
} catch (\Exception $e) {
Log::info('JgPush推送消息发送失败' . json_encode($data) . ' - ' . $e->getMessage());
2023-09-28 18:22:38 +08:00
return app('json')->success(json_encode($data, true) . $e->getMessage());
2023-09-27 19:40:25 +08:00
}
}
2023-05-10 13:38:51 +08:00
public function test()
{
2023-06-02 17:00:16 +08:00
$type = $this->request->param('type');
2023-10-10 14:54:50 +08:00
$res = [];
2023-06-02 17:00:16 +08:00
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-10-10 14:54:50 +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);
// }
2023-05-10 13:38:51 +08:00
}
/**
* @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'));
2023-10-10 14:54:50 +08:00
// if($auth_token && $user){
// return app('json')->fail('用户已存在');
// }
2023-05-10 13:38:51 +08:00
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-10-10 14:54:50 +08:00
2023-05-12 17:10:56 +08:00
if ($store_service) {
2024-03-07 11:20:44 +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,mer_settlement_agree_status,is_margin,street_id,is_company,mer_money')->find();
2023-12-23 17:12:38 +08:00
$bank_info = Db::name('merchant_intention')->where('mer_id', $store_service['mer_id'])->field('company_name,bank_username,bank_opening,bank_code')->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;
}
2024-03-02 15:18:23 +08:00
if($bank_info && count($bank_info)>0 && count($mer_arr)>0){
2024-01-05 09:47:07 +08:00
$data['mer_info'] = array_merge($mer_arr,$bank_info);
}else{
$data['mer_info'] =$mer_arr;
}
2024-03-09 14:24:16 +08:00
$merType = Db::name('merchant_type')->where('mer_type_id', $mer_arr['type_id'] ?? 0)->field('type_code,type_name')->find();
$data['mer_info']['type_code'] = $merType['type_code'];
$data['mer_info']['type_name'] = $merType['type_name'];
2023-09-19 17:48:35 +08:00
$data['mer_info']['setting_status'] = 0;
2024-03-11 11:48:22 +08:00
if (!empty($mer_arr['mer_avatar']) && !empty($mer_arr['mer_banner']) && !empty($mer_arr['mer_address'])) {
2024-03-11 11:37:37 +08:00
$data['mer_info']['setting_status'] = 1;
}
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 = [];
2023-10-10 14:54:50 +08:00
foreach ($thirdparty as $v) {
2023-09-01 16:26:00 +08:00
$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;
$arr=env('APP_SHOW')??'';
$arr=explode(',',$arr);
2023-10-17 09:31:30 +08:00
if(in_array($user['uid'],$arr )){
$data['show_controller_applet']=true;
}else{
$data['show_controller_applet']=false;
}
2024-01-21 19:21:38 +08:00
$data['red_pack_balance']=Db::name('store_consumption_user')->where('uid',$data['uid'])->where('status',0)->sum('balance');
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('退出登录');
}
2023-09-23 14:21:24 +08:00
public function doMargin()
{
$user = $this->request->userInfo();
2023-09-28 14:52:27 +08:00
$merchant = Db::name('merchant')->where('uid', $user['uid'])->where('status', 1)->find();
2023-09-23 14:21:24 +08:00
if (!$merchant) {
2023-09-28 14:52:27 +08:00
return app('json')->fail('没有店铺');
}
2023-10-10 14:54:50 +08:00
if ($merchant['is_margin'] == 10) {
2023-10-26 15:08:25 +08:00
return app('json')->fail('押金已缴纳');
2023-09-23 14:21:24 +08:00
}
2023-10-10 14:54:50 +08:00
if ($merchant['margin'] == 0) {
2023-09-27 20:57:02 +08:00
$margin = Db::name('MerchantType')->where('mer_type_id', $merchant['type_id'])->value('margin');
2023-10-10 16:49:36 +08:00
$margin = bcsub($margin, $merchant['paid_margin'], 2);
} else {
$margin = $merchant['margin'];
2023-10-08 12:46:32 +08:00
}
2023-10-10 16:49:36 +08:00
if ($margin == 0) {
2023-10-08 12:46:32 +08:00
return app('json')->fail('当前金额为0,不能进行充值');
}
2023-09-23 14:57:30 +08:00
$orderSn = "bzj" . date('YmdHis') . uniqid();
Db::name('margin_order')->insert([
'uid' => $user['uid'],
'mer_id' => $merchant['mer_id'],
'order_sn' => $orderSn,
2023-09-27 20:57:02 +08:00
'total_price' => $margin,
2023-09-23 14:57:30 +08:00
'pay_type' => 1,
'create_time' => date('Y-m-d H:i:s')
]);
2023-09-23 14:21:24 +08:00
$param = [
"status" => 0,
"is_del" => 0,
"mer_id" => $merchant['mer_id'],
"pay_type" => 1,
2023-09-23 14:36:35 +08:00
"attach" => "margin",
2023-09-27 20:57:02 +08:00
"order_info" => '{"is_margin":1,"margin":"' . $margin . '"}',
"pay_price" => $margin,
2023-09-23 14:57:30 +08:00
"order_sn" => $orderSn,
2023-09-27 20:57:02 +08:00
"body" => $merchant['mer_name'] . ' - ' . $margin,
2023-09-23 14:21:24 +08:00
];
$payType = 'weixinApp';
$service = new PayService($payType, $param);
2023-10-10 14:54:50 +08:00
$payInfo = $service->pay(User::where(['uid' => $user['uid']])->find());
2023-09-23 14:21:24 +08:00
return app('json')->success($payInfo);
}
2023-09-25 15:10:36 +08:00
public function marginList()
{
$user = $this->request->userInfo();
[$page, $limit] = $this->getPage();
2023-10-10 14:54:50 +08:00
$count = Db::name('margin_order')->where('uid', $user['uid'])->where('paid', 1)->count();
$list = Db::name('margin_order')->where('uid', $user['uid'])->where('paid', 1)->page($page, $limit)->order('order_id', 'desc')->select()->toArray();
2023-09-25 15:10:36 +08:00
return app('json')->success(compact('count', 'list'));
}
2023-05-10 13:38:51 +08:00
/**
* @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('请求太频繁请稍后再试');
}
2023-10-10 14:54:50 +08:00
// if(!env('APP_DEBUG', false)){
2023-05-10 13:38:51 +08:00
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());
}
2023-10-10 14:54:50 +08:00
// }else{
// $sms_code = 1234;
// $sms_time = 5;
// }
2023-05-10 13:38:51 +08:00
$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']);
2024-03-01 10:00:16 +08:00
$isNewUser = false;
2024-01-27 16:11:09 +08:00
if (!$user) {
$isNewUser = true;
$user = $repository->registr($data['phone'], null, $data['user_type']);
}
2024-03-12 15:41:17 +08:00
$spreadId = empty($data['spread']) ? $user['spread_uid'] : $data['spread'];
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);
2024-03-12 15:41:17 +08:00
$repository->bindSpread($user, intval($spreadId));
2023-05-10 13:38:51 +08:00
$tokenInfo = $repository->createToken($user);
$repository->loginAfter($user);
2024-03-01 10:00:16 +08:00
return app('json')->success(array_merge(['is_new_user' => $isNewUser], $repository->returnToken($user, $tokenInfo)));
2023-05-10 13:38:51 +08:00
}
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') {
2024-03-07 17:41:49 +08:00
$oauth = WechatService::create(true)->getApplication()->oauth;
$accessToken = $oauth->getAccessToken($data['code']);
2023-05-10 13:38:51 +08:00
try {
2024-03-07 17:41:49 +08:00
$wechatInfo = $oauth->user($accessToken)->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');
2024-03-09 10:43:42 +08:00
$createUser = true;
if ($auth['type'] == 'app_wechat' || systemConfig('is_phone_login') == '1') {
$createUser = false;
}
$users = $this->authInfo($auth, $createUser);
2023-05-10 13:38:51 +08:00
if (!$users)
return app('json')->fail('授权失败');
$authInfo = $users[0];
2024-03-08 15:56:34 +08:00
/** @var UserRepository $userRepository */
2023-05-10 13:38:51 +08:00
$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'];
}
2024-03-12 09:09:22 +08:00
if ((!$user || empty($user['account']) || empty($user['phone'])) && $auth['type'] == 'app_wechat') {
2023-05-10 13:38:51 +08:00
$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']));
}
2024-03-08 15:56:34 +08:00
if (!empty($user['account'])) {
$user = $userRepository->accountByUser($user['account']);
}
2023-05-10 13:38:51 +08:00
$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);
2023-10-10 14:54:50 +08:00
// if($user && $auth_token){
// return app('json')->fail('用户已存在');
// }
2023-05-10 13:38:51 +08:00
$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-10-10 14:54:50 +08:00
$cityCodeArray = explode(',', $cityCode);
2023-08-30 15:43:22 +08:00
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-10-10 14:54:50 +08:00
$cityCodeArray = explode(',', $cityCode);
2023-08-30 16:16:20 +08:00
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();
};
2023-10-10 14:54:50 +08:00
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
];
2023-10-10 14:54:50 +08:00
return app('json')->success($data);
2023-08-23 14:33:35 +08:00
}
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-10-10 14:54:50 +08:00
$tokenInfo = Db::name('user_thirdparty_token')->where(['user_type' => $userType, 'user_id' => $uid])->find();
2023-09-01 13:32:33 +08:00
if ($tokenInfo) {
$updData = [
'account' => $account,
'token' => $token,
'expires_time' => $expiresTime,
'create_time' => date('Y-m-d H:i:s')
];
2023-10-10 14:54:50 +08:00
Db::name('user_thirdparty_token')->where(['user_type' => $userType, 'user_id' => $uid])->update($updData);
2023-09-01 13:32:33 +08:00
} 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
2023-09-26 09:53:33 +08:00
//获取APP菜单
2023-09-26 10:46:49 +08:00
public function miniAppVersion()
2023-09-26 09:53:33 +08:00
{
2023-09-26 10:46:49 +08:00
$version = $this->request->param('version', '');
$queryBuilder = Db::name('miniapp_update');
if ($version) {
$queryBuilder = $queryBuilder->where('version', '>', $version);
2023-09-26 09:53:33 +08:00
}
2023-09-26 10:51:31 +08:00
$appInfo = ($queryBuilder->order('version', 'desc')->fetchSql(false)->find()) ?? (object)[];
2023-09-26 10:46:49 +08:00
return app('json')->success(compact('appInfo'));
2023-09-26 09:53:33 +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-11 15:53:44 +08:00
$type = $this->request->param('type', '-1');
2023-12-21 16:40:13 +08:00
// $version = $this->request->param('version', '');
// $phoneBrand = $this->request->param('phone_brand', '');
// $queryBuilder = Db::name('AppUpdate')->where('type', $type);
2023-09-11 16:01:44 +08:00
if ($type == 3) {
2024-02-28 12:11:52 +08:00
$android = (Db::name('AppUpdate')->where('type', 1)->where('phone_brand', '')->where('is_wget',0)->order('id', 'desc')->find()) ?? (object)[];
2023-10-10 14:54:50 +08:00
$ios = (Db::name('AppUpdate')->where('type', 2)->where('phone_brand', '')->order('id', 'desc')->find()) ?? (object)[];
2023-09-11 16:01:44 +08:00
return app('json')->success(compact('android', 'ios'));
2023-09-11 16:04:22 +08:00
} else {
2023-12-21 16:43:58 +08:00
$agent = strtolower($this->request->server('HTTP_USER_AGENT'));
2023-12-21 16:40:13 +08:00
// 检查是否为iOS设备包括iPhone和iPad
if (strpos($agent, 'iphone') !== false || strpos($agent, 'ipad') !== false) {
2024-03-18 10:25:10 +08:00
$appInfo = Db::name('AppUpdate')->where('type', $type)->order('id','desc')->find();
2023-12-21 16:40:13 +08:00
} elseif (strpos($agent, 'android') !== false) {
// 检查是否为Android设备
$appInfo = Db::name('AppUpdate')->where('type', $type)->order('id','desc')->find();
if($agent == 'ios'){
$pattern = '/\.wgt$/i';
if (preg_match($pattern, basename($appInfo['dow_url']))) {
$appInfo =[];
}
}
2023-12-21 16:40:13 +08:00
} else {
$appInfo=[];
// 如果都不是,则输出其他
2023-09-25 21:04:51 +08:00
}
2023-09-11 15:53:44 +08:00
}
2023-10-10 14:54:50 +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-10-10 14:54:50 +08:00
return app('json')->fail('数据不存在');
2023-09-19 10:55:01 +08:00
$status = $this->request->post('status', 0);
2023-09-19 17:15:16 +08:00
$remark = $this->request->post('remark', '');
2023-09-19 10:55:01 +08:00
$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 ? '自动审核通过' : '自动审核拒绝';
2023-09-19 17:30:54 +08:00
$updData = [
'status' => ($status == 1 ? 1 : 2),
'fail_msg' => $remark
];
2023-09-28 12:37:42 +08:00
if ($status == 1) {
$repository->updateStatus($id, $data);
2023-09-28 14:07:43 +08:00
$intention = Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 1)->find();
2023-10-10 14:54:50 +08:00
if (!empty($intention['images'])) {
2023-09-28 14:19:10 +08:00
$merLicenseImageArray = explode(',', $intention['images']);
2023-12-25 14:35:43 +08:00
app()->make(ConfigValueRepository::class)->setFormData([
'mer_certificate' => $merLicenseImageArray
], $intention['mer_id']);
2023-09-28 14:19:10 +08:00
}
2023-09-19 17:30:54 +08:00
}
2023-09-28 15:43:22 +08:00
Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 1)->update($updData);
2023-09-19 10:06:21 +08:00
} else {
//商户交易申请
2023-09-19 17:15:16 +08:00
$updData = [
'status' => ($status == 1 ? 1 : 2),
'fail_msg' => $remark
];
Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 2)->update($updData);
2023-12-29 10:27:31 +08:00
$merchant_intention = Db::name('merchant_intention')->where('mer_intention_id', $id)->where('type', 2)->find();
if($merchant_intention){
if ($status == 1) {
$datas['business_status']=2;
$datas['mer_settlement_agree_status']=1;
2023-12-29 19:02:44 +08:00
$datas['financial_bank']=json_encode(['name'=>$merchant_intention['company_name'],
2023-12-29 19:09:30 +08:00
'bank_code'=>$merchant_intention['bank_code'],'bank'=>$merchant_intention['bank_username'],'bank_branch'=>$merchant_intention['bank_opening']]);
2023-12-29 10:27:31 +08:00
}else{
$datas['business_status']=3;
}
Db::name('merchant')->where('mer_id', $merchant_intention['mer_id'])->where('status', 1)->update($datas);
2023-09-22 11:20:25 +08:00
}
2023-12-29 10:27:31 +08:00
2023-09-19 10:06:21 +08:00
}
2023-10-10 14:54:50 +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
2023-09-21 20:46:29 +08:00
//mer_services_agree mer_supply_agree
//consign_product_agree mer_settlement_agree
2023-09-19 10:55:01 +08:00
$type = $this->request->get('type', 'sys_intention_agree');
2023-09-21 20:46:29 +08:00
$typeArray = ['sys_intention_agree', 'business_apply_agree', 'mer_services_agree', 'mer_supply_agree', 'consign_product_agree', 'mer_settlement_agree'];
2023-09-19 10:55:01 +08:00
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);
}
2024-03-09 10:43:42 +08:00
/**
* 合并账号
* @param UserRepository $repository
* @return mixed
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function merge(UserRepository $repository)
{
$data = $this->request->params(['phone', 'sms_code', 'spread', 'pwd', 'auth_token', ['user_type', 'h5']]);
$sms_code = app()->make(SmsService::class)->checkSmsCode($data['phone'], $data['sms_code'], 'login');
if (!$sms_code && !env('APP_DEBUG')) {
return app('json')->fail('验证码不正确');
}
$auth = Cache::get('u_try' . $data['auth_token']);
2024-03-09 11:12:03 +08:00
$auth && Cache::delete('u_try' . $data['auth_token']);
2024-03-09 10:43:42 +08:00
if (empty($auth)) {
return app('json')->fail('授权已过期,请重新登录');
}
$user = $repository->wechatUserIdBytUser($auth['id']);
2024-03-09 16:47:06 +08:00
if (!empty($user['account']) && !empty($user['phone'])) {
2024-03-09 10:43:42 +08:00
return app('json')->fail('已绑定手机号');
}
$targetUser = $repository->accountByUser($data['phone']);
if (empty($targetUser)) {
if (!empty($user)) {
$user->account = $data['phone'];
$user->phone = $data['phone'];
$user->save();
$tokenInfo = $repository->createToken($user);
return app('json')->success($repository->returnToken($user, $tokenInfo));
} else {
$targetUser = $repository->registr($data['phone'], $data['pwd'], $data['user_type']);
$repository->bindSpread($targetUser, intval($data['spread']));
}
}
$repository->syncBaseAuth($auth, $targetUser);
if (!empty($user)) {
Db::startTrans();
try {
$merchant = Merchant::where('uid', $targetUser['uid'])->find();
if (!empty($merchant)) {
$orders = StoreOrder::with(['refundOrder' => function(Query $query) {
$query->where('status', '<>', -1)->field('order_id,refund_price');
}])->where('uid', $user['uid'])
2024-03-13 10:41:39 +08:00
->whereIn('status', [2, 3])
2024-03-09 10:43:42 +08:00
->field('order_id,uid,total_price')
->select()->toArray();
$otherOrders = StoreOrderOther::with(['refundOrder' => function(Query $query) {
$query->where('status', '<>', -1)->field('order_id,refund_price');
}])->where('uid', $user['uid'])
2024-03-13 10:41:39 +08:00
->whereIn('status', [2, 3])
2024-03-09 10:43:42 +08:00
->field('order_id,uid,total_price')
->select()->toArray();
$purchaseAmount = 0;
foreach ($orders as $order) {
$purchaseAmount = bcadd($purchaseAmount, $order['total_price'], 2);
foreach ($order['refundOrder']as $refundOrder) {
$purchaseAmount = bcsub($purchaseAmount, $refundOrder['refund_price'], 2);
}
}
unset($refundOrder, $order);
foreach ($otherOrders as $otherOrder) {
$purchaseAmount = bcadd($purchaseAmount, $otherOrder['total_price'], 2);
foreach ($otherOrder['refundOrder']as $refundOrder) {
$purchaseAmount = bcsub($purchaseAmount, $refundOrder['refund_price'], 2);
}
}
unset($refundOrder, $otherOrder);
if ($purchaseAmount > 0) {
$merchant->purchase_amount = bcadd($merchant->purchase_amount, $purchaseAmount, 2);
$merchant->save();
}
}
2024-03-13 09:57:58 +08:00
StoreGroupOrder::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
StoreOrder::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
StoreOrderProduct::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
UserBill::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
FinancialRecord::where('user_id', $user['uid'])->update(['user_id' => $targetUser['uid']]);
UserAddress::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
StoreConsumptionUser::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
StoreConsumptionDetail::where('user_id', $user['uid'])->update(['user_id' => $targetUser['uid']]);
StoreRefundOrder::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
UserRecharge::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
StoreOrderStatus::where('uid', $user['uid'])->update(['uid' => $targetUser['uid']]);
if ($user->now_money > 0) {
$targetUser->now_money = bcadd($targetUser->now_money, $user->now_money, 2);
$user->now_money = 0;
$targetUser->save();
}
2024-03-13 09:54:05 +08:00
$user->wechat_user_id = 0;
2024-03-13 10:20:42 +08:00
$user->account = 'uid_' . $targetUser['uid'];
2024-03-13 10:38:42 +08:00
$user->status = -1;
2024-03-13 09:54:05 +08:00
$user->save();
2024-03-09 10:43:42 +08:00
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
throw new ValidateException('绑定出错');
}
}
$tokenInfo = $repository->createToken($targetUser);
return app('json')->success($repository->returnToken($targetUser, $tokenInfo));
}
2023-05-10 13:38:51 +08:00
}