From 0f20d938ff032982e7065faeed63b65e62465fbd Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 14:23:51 +0800 Subject: [PATCH 01/72] =?UTF-8?q?=E6=96=B0=E5=BA=97=E9=93=BA=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/FileUpload.php | 55 ++++++++++++++++++++++ app/Controller/IndexController.php | 26 ++++++++++- app/Controller/StoreController.php | 73 ++++++++++++++++++++++++++++++ app/Controller/TestController.php | 23 ++++++++++ composer.json | 4 +- 5 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 app/Controller/FileUpload.php create mode 100644 app/Controller/StoreController.php create mode 100644 app/Controller/TestController.php diff --git a/app/Controller/FileUpload.php b/app/Controller/FileUpload.php new file mode 100644 index 0000000..0f9f63a --- /dev/null +++ b/app/Controller/FileUpload.php @@ -0,0 +1,55 @@ +createBucket($bucket); + $result = $ossClient->putObject($bucket, $object, $content); + return $result; + } catch (OssException $e) { + printf(__FUNCTION__ . ": FAILED\n"); + printf($e->getMessage() . "\n"); + return false; + } + } +} \ No newline at end of file diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index 3864423..bceb474 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -11,6 +11,13 @@ declare(strict_types=1); */ namespace App\Controller; +use Hyperf\HttpServer\Annotation\AutoController; +use League\Flysystem\Filesystem; + +/** + * @AutoController() + * @package App\Controller + */ class IndexController extends AbstractController { public function index() @@ -20,7 +27,24 @@ class IndexController extends AbstractController return [ 'method' => $method, - 'message' => "Hello22222 {$user}.", + 'message' => floatval(2.00), ]; } + + public function example(Filesystem $filesystem) + { + + $file = $this->request->file('upload'); + + var_dump($file);die; + $fileContent = file_get_contents($file->getRealPath()); + var_dump($fileContent);die; + + + + + $stream = fopen($file->getRealPath(),'r+'); + $filesystem->writeStream('uplaods/'.$file->getClientFilename(),$stream); + fclose($stream); + } } diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php new file mode 100644 index 0000000..ee8b657 --- /dev/null +++ b/app/Controller/StoreController.php @@ -0,0 +1,73 @@ +request->input('id'); + if (empty($id)){ + return $this->result(1,[],'id不能为空'); + } + $logo = $this->request->input('logo'); + $name = $this->request->input('name'); + $tel = $this->request->input('tel'); + $address = $this->request->input('address'); + $coordinates = $this->request->input('coordinates'); + $capita = $this->request->input('capita'); + $start_at = $this->request->input('start_at'); + $announcement = $this->request->input('announcement'); + $environment = $this->request->input('environment'); + + //>>1上传logo到阿里云oss + //>>2.上传商家环境到阿里云oss + //>>3.保存数据到数据库存 + $fileName = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0,9999999999999999).'.jpg'; + $fileUpload = new FileUpload(); + $resLogo = $fileUpload->ossUpload($logo,$fileName); + if (isset($resLogo['info']['http_code'])&&$resLogo['info']['http_code']==200){ + $logo_url = $fileName; + }else{ + return $this->result(1,[]); + } + $res = Db::table('ims_cjdc_store')->where('id',$id)->update([ + 'logo'=>$logo_url??"", + 'name'=>$name, + 'tel'=>$tel, + 'address'=>$address, + 'coordinates'=>$coordinates, + 'capita'=>$capita, + 'start_at'=>$start_at, + 'announcement'=>$announcement, + 'environment'=>$environment, + ]); + return $this->success($res); + + + + + + + + + + + + + + + } +} \ No newline at end of file diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php new file mode 100644 index 0000000..4551b9b --- /dev/null +++ b/app/Controller/TestController.php @@ -0,0 +1,23 @@ +input('id',2); + return (string)$id; + } +} \ No newline at end of file diff --git a/composer.json b/composer.json index 5d55e6c..2a3907c 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,9 @@ "hyperf/process": "~2.0.0", "hyperf/redis": "~2.0.0", "hyperf/constants": "~2.0.0", - "hyperf/model-cache": "~2.0.0" + "hyperf/model-cache": "~2.0.0", + "hyperf/filesystem": "^2.0", + "xxtime/flysystem-aliyun-oss": "^1.5" }, "require-dev": { "swoole/ide-helper": "^4.5", From 584fdd683e504199e7a2f9a38233a8b2043d5df1 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 22 Jul 2020 16:32:40 +0800 Subject: [PATCH 02/72] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=B8=8D=E5=88=86?= =?UTF-8?q?=E6=B8=A0=E9=81=93=E7=9A=84=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/CouponController.php | 33 +++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/app/Controller/CouponController.php b/app/Controller/CouponController.php index e8b26e2..5ba359d 100644 --- a/app/Controller/CouponController.php +++ b/app/Controller/CouponController.php @@ -34,17 +34,35 @@ class CouponController extends BaseController $this->success(['not_reveive' => []]); } - $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id'); + $c_ids = []; + // 渠道开启,查询该渠道可以领取的优惠券ID + // 渠道未开启,查询所有优惠券 + if (env('SUB_CHANNEL') == 1) { + $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id'); + } else { + $c_ids = Coupon::pluck('id'); + } + $nowTime = time(); - $cr_ids = CouponRec::where([ - ['user_id',"=",$user_id], - ['receive_type',"=",$receive_type] - ])->pluck('system_coupon_user_id'); + + $where = [ + ['user_id',"=",$user_id] + ]; + + // 渠道开启,查询该用户在此渠道领过的优惠券ID + if (env('SUB_CHANNEL') == 1) { + array_push($where, ['receive_type', "=", $receive_type]); + } + + $cr_ids = CouponRec::where($where)->pluck('system_coupon_user_id'); //领过券的ID $c_ids = $c_ids->toArray(); $cr_ids = $cr_ids->toArray(); + // 当前用户可领的优惠券ID + $couponIds = array_diff($c_ids, $cr_ids); + $c = Db::table('ims_system_coupon_user as u') ->where([ ['u.end_time','>',$nowTime], @@ -54,8 +72,9 @@ class CouponController extends BaseController ]) ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id') ->whereRaw('u.inventory_use <= u.inventory and u.inventory-u.inventory_use > type.one_receive_number') - ->whereIn('u.id',$c_ids) - ->whereNotIn('u.id',$cr_ids) + // ->whereIn('u.id',$c_ids) + // ->whereNotIn('u.id',$cr_ids) + ->whereIn('u.id', $couponIds) ->select('u.*','type.one_receive_number') ->orderBy('u.weigh','desc') // ->orderByRaw('FIELD(u.id, '.implode(", " , $ids).')') From 28b0f413f5763b68e2f3bb991bbcbd584963f70e Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:34:07 +0800 Subject: [PATCH 03/72] =?UTF-8?q?=E9=87=8D=E5=86=99=E5=B0=8F=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F=E8=8E=B7=E5=8F=96=E9=97=A8=E5=BA=97=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/FileUpload.php | 12 ++-- app/Controller/IndexController.php | 1 - app/Controller/StoreController.php | 105 ++++++++++++++++------------- 3 files changed, 63 insertions(+), 55 deletions(-) diff --git a/app/Controller/FileUpload.php b/app/Controller/FileUpload.php index 0f9f63a..385a02f 100644 --- a/app/Controller/FileUpload.php +++ b/app/Controller/FileUpload.php @@ -15,21 +15,17 @@ class FileUpload extends AbstractController public function __construct() { - - } - - - public function ossUpload($fileContent,$fileName) - { - if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } + } + - //$base64 = input('upload'); + public function ossUpload($fileContent,$fileName) + { $img = base64_decode($fileContent); $accessKeyId = "LTAI4G8QMM97Fg1Gx8TXeast"; $accessKeySecret = "f1KIbMCiO4CXmTzC0FDl6hTRXgFobm"; diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index bceb474..417e4d4 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -33,7 +33,6 @@ class IndexController extends AbstractController public function example(Filesystem $filesystem) { - $file = $this->request->file('upload'); var_dump($file);die; diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php index ee8b657..30ffa47 100644 --- a/app/Controller/StoreController.php +++ b/app/Controller/StoreController.php @@ -17,55 +17,68 @@ class StoreController extends BaseController { public function infoEdit() { - $id = $this->request->input('id'); - if (empty($id)){ - return $this->result(1,[],'id不能为空'); + if (empty($id)) { + return $this->result(1, [], 'id不能为空'); } - $logo = $this->request->input('logo'); - $name = $this->request->input('name'); - $tel = $this->request->input('tel'); - $address = $this->request->input('address'); - $coordinates = $this->request->input('coordinates'); - $capita = $this->request->input('capita'); - $start_at = $this->request->input('start_at'); - $announcement = $this->request->input('announcement'); - $environment = $this->request->input('environment'); - - //>>1上传logo到阿里云oss - //>>2.上传商家环境到阿里云oss - //>>3.保存数据到数据库存 - $fileName = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0,9999999999999999).'.jpg'; - $fileUpload = new FileUpload(); - $resLogo = $fileUpload->ossUpload($logo,$fileName); - if (isset($resLogo['info']['http_code'])&&$resLogo['info']['http_code']==200){ - $logo_url = $fileName; - }else{ - return $this->result(1,[]); + if ($this->request->isMethod('post')) { + $logo = $this->request->input('logo'); + $name = $this->request->input('name'); + $tel = $this->request->input('tel'); + $address = $this->request->input('address'); + $coordinates = $this->request->input('coordinates'); + $capita = $this->request->input('capita'); + $start_at = $this->request->input('start_at'); + $announcement = $this->request->input('announcement'); + $environment = $this->request->input('environment'); + + //>>1上传logo到阿里云oss + //>>2.上传商家环境到阿里云oss + //>>3.保存数据到数据库存 + $fileNameLogo = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0, 9999999999999999) . '.jpg'; + $fileUpload = new FileUpload(); + $resLogo = $fileUpload->ossUpload($logo, $fileNameLogo); + if (isset($resLogo['info']['http_code']) && $resLogo['info']['http_code'] == 200) { + $logo_url = $fileNameLogo; + } else { + return $this->result(1, []); + } + $environments = explode(',', $environment); + $envPaths = []; + foreach ($environments as $env) { + $fileNameEnv = $object = 'public/upload/' . date('Y') . '/' . date('m-d') . '/' . rand(0, 9999999999999999) . '.jpg'; + $resEnv = $fileUpload->ossUpload($env, $fileNameEnv); + if (isset($resEnv['info']['http_code']) && $resLogo['info']['http_code'] == 200) { + $envPaths[] = $fileNameEnv; + } + } + if (count($envPaths)) { + $envPath = implode(',', $envPaths); + } + + $res = Db::table('ims_cjdc_store')->where('id', $id)->update([ + 'logo' => $logo_url ?? "", + 'name' => $name, + 'tel' => $tel, + 'address' => $address, + 'coordinates' => $coordinates, + 'capita' => $capita, + 'start_at' => $start_at, + 'announcement' => $announcement, + 'environment' => $envPath ?? "", + ]); + return $this->success($res); } - $res = Db::table('ims_cjdc_store')->where('id',$id)->update([ - 'logo'=>$logo_url??"", - 'name'=>$name, - 'tel'=>$tel, - 'address'=>$address, - 'coordinates'=>$coordinates, - 'capita'=>$capita, - 'start_at'=>$start_at, - 'announcement'=>$announcement, - 'environment'=>$environment, - ]); - return $this->success($res); - - - - - - - - - - - +//'id','name','logo','tel','address','coordinates','capita','start_at','announcement','environment' + //获取店铺信息 + $data = Db::table('ims_cjdc_store') + ->select(['id','name','logo','tel','address','coordinates','capita','start_at','announcement','environment']) + ->where('id',$id) + ->first(); + if ($data){ + $data->site = env('SITE_HOST'); + } + return $this->success($data); From dfe90e7ca4a643f2ca1409c02d06e3291753ab53 Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:53:12 +0800 Subject: [PATCH 04/72] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=9F=9F=E5=90=8D=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/config.php b/config/config.php index 7d0c07e..c5ce284 100644 --- a/config/config.php +++ b/config/config.php @@ -28,4 +28,7 @@ return [ LogLevel::WARNING, ], ], + + 'site_host'=>'http://store.api.lanzulive.com/' + ]; From 31db4ffb39fe83aa9ec9368960aea7d6eaaf59dc Mon Sep 17 00:00:00 2001 From: lanzu_qsy <334039090@qq.com> Date: Wed, 22 Jul 2020 16:53:54 +0800 Subject: [PATCH 05/72] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=9F=9F=E5=90=8D?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/StoreController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Controller/StoreController.php b/app/Controller/StoreController.php index 30ffa47..d39decf 100644 --- a/app/Controller/StoreController.php +++ b/app/Controller/StoreController.php @@ -76,7 +76,7 @@ class StoreController extends BaseController ->where('id',$id) ->first(); if ($data){ - $data->site = env('SITE_HOST'); + $data->site = config('site_host'); } return $this->success($data); From 3ae5d4c16b082286bcf62da489410ab99e6ecf4d Mon Sep 17 00:00:00 2001 From: Mike Date: Thu, 23 Jul 2020 11:48:49 +0800 Subject: [PATCH 06/72] =?UTF-8?q?=E6=B7=BB=E5=8A=A0oss=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/TestController.php | 17 +++++- config/autoload/file.php | 94 +++++++++++++++++++++++++++++++ config/routes.php | 4 ++ 3 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 config/autoload/file.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 4551b9b..8b855bb 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -14,10 +14,21 @@ use Hyperf\HttpServer\Annotation\AutoController; */ class TestController extends AbstractController { + private $name = 'default action'; + public function index1(RequestInterface $request) + { + $this->name = 'index1 action'; + return $this->name; + } + + public function index2(RequestInterface $request) + { + $this->name = 'index2 action'; + return $this->name; + } - public function index(RequestInterface $request) + public function index3(RequestInterface $request) { - $id = $request->input('id',2); - return (string)$id; + return $this->name; } } \ No newline at end of file diff --git a/config/autoload/file.php b/config/autoload/file.php new file mode 100644 index 0000000..59cd236 --- /dev/null +++ b/config/autoload/file.php @@ -0,0 +1,94 @@ + 'local', + 'storage' => [ + 'local' => [ + 'driver' => \Hyperf\Filesystem\Adapter\LocalAdapterFactory::class, + 'root' => __DIR__ . '/../../runtime', + ], + 'ftp' => [ + 'driver' => \Hyperf\Filesystem\Adapter\FtpAdapterFactory::class, + 'host' => 'ftp.example.com', + 'username' => 'username', + 'password' => 'password', + // 'port' => 21, + // 'root' => '/path/to/root', + // 'passive' => true, + // 'ssl' => true, + // 'timeout' => 30, + // 'ignorePassiveAddress' => false, + ], + 'memory' => [ + 'driver' => \Hyperf\Filesystem\Adapter\MemoryAdapterFactory::class, + ], + 's3' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => false, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'minio' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => true, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'oss' => [ + 'driver' => \Hyperf\Filesystem\Adapter\AliyunOssAdapterFactory::class, + 'accessId' => env('OSS_ACCESS_ID'), + 'accessSecret' => env('OSS_ACCESS_SECRET'), + 'bucket' => env('OSS_BUCKET'), + 'endpoint' => env('OSS_ENDPOINT'), + // 'timeout' => 3600, + // 'connectTimeout' => 10, + // 'isCName' => false, + // 'token' => '', + ], + 'qiniu' => [ + 'driver' => \Hyperf\Filesystem\Adapter\QiniuAdapterFactory::class, + 'accessKey' => env('QINIU_ACCESS_KEY'), + 'secretKey' => env('QINIU_SECRET_KEY'), + 'bucket' => env('QINIU_BUCKET'), + 'domain' => env('QINBIU_DOMAIN'), + ], + 'cos' => [ + 'driver' => \Hyperf\Filesystem\Adapter\CosAdapterFactory::class, + 'region' => env('COS_REGION'), + 'credentials' => [ + 'appId' => env('COS_APPID'), + 'secretId' => env('COS_SECRET_ID'), + 'secretKey' => env('COS_SECRET_KEY'), + ], + 'bucket' => env('COS_BUCKET'), + 'read_from_cdn' => false, + // 'timeout' => 60, + // 'connect_timeout' => 60, + // 'cdn' => '', + // 'scheme' => 'https', + ], + ], +]; diff --git a/config/routes.php b/config/routes.php index 10aa6e4..a2e3825 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,9 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); + Router::get('test/index1', 'App\Controller\TestController@index1'); + Router::get('test/index2', 'App\Controller\TestController@index2'); + + }); \ No newline at end of file From ab0537a39ad33841e4625cc97619256e8c6ed678 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 26 Jul 2020 12:53:19 +0800 Subject: [PATCH 07/72] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ssdb=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E5=BA=93=EF=BC=8C=E6=B7=BB=E5=8A=A0ssdb=20task=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E5=BA=94=E7=94=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/TestController.php | 20 +- app/Libs/SimpleSSDB.php | 622 ++++++++++++++++++++++++++++++ app/TaskWorker/SSDBTask.php | 39 ++ composer.json | 3 +- config/autoload/server.php | 4 + config/routes.php | 3 +- 6 files changed, 688 insertions(+), 3 deletions(-) create mode 100644 app/Libs/SimpleSSDB.php create mode 100644 app/TaskWorker/SSDBTask.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index 8b855bb..bc034d0 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -6,6 +6,11 @@ namespace App\Controller; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Annotation\AutoController; +use Hyperf\Utils\Coroutine; +use Hyperf\Utils\ApplicationContext; +use Hyperf\Task\TaskExecutor; +use Hyperf\Task\Task; +use App\TaskWorker\SSDBTask; /** * @AutoController() @@ -15,9 +20,22 @@ use Hyperf\HttpServer\Annotation\AutoController; class TestController extends AbstractController { private $name = 'default action'; + + public function index1(RequestInterface $request) { - $this->name = 'index1 action'; + // $container = ApplicationContext::getContainer(); + // $exec = $container->get(TaskExecutor::class); + // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); + + $client = ApplicationContext::getContainer()->get(SSDBTask::class); + $result = $client->exec("set","bar","1234"); + $result = $client->exec("get","bar"); + + // $client = ApplicationContext::getContainer()->get(MethodTask::class); + // $result = $client->handle("set"); + + $this->name = 'index1 action '. $result; return $this->name; } diff --git a/app/Libs/SimpleSSDB.php b/app/Libs/SimpleSSDB.php new file mode 100644 index 0000000..b6920b2 --- /dev/null +++ b/app/Libs/SimpleSSDB.php @@ -0,0 +1,622 @@ +easy(); + } +} + +class SSDB_Response +{ + public $cmd; + public $code; + public $data = null; + public $message; + + function __construct($code='ok', $data_or_message=null){ + $this->code = $code; + if($code == 'ok'){ + $this->data = $data_or_message; + }else{ + $this->message = $data_or_message; + } + } + + function __toString(){ + if($this->code == 'ok'){ + $s = $this->data === null? '' : json_encode($this->data); + }else{ + $s = $this->message; + } + return sprintf('%-13s %12s %s', $this->cmd, $this->code, $s); + } + + function ok(){ + return $this->code == 'ok'; + } + + function not_found(){ + return $this->code == 'not_found'; + } +} + +// Depricated, use SimpleSSDB instead! +class SSDB +{ + private $debug = false; + public $sock = null; + private $_closed = false; + private $recv_buf = ''; + private $_easy = false; + public $last_resp = null; + + function __construct($host, $port, $timeout_ms=2000){ + $timeout_f = (float)$timeout_ms/1000; + $this->sock = @stream_socket_client("[$host]:$port", $errno, $errstr, $timeout_f); + if(!$this->sock){ + throw new SSDBException("$errno: $errstr"); + } + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + if(function_exists('stream_set_chunk_size')){ + @stream_set_chunk_size($this->sock, 1024 * 1024); + } + } + + function set_timeout($timeout_ms){ + $timeout_sec = intval($timeout_ms/1000); + $timeout_usec = ($timeout_ms - $timeout_sec * 1000) * 1000; + @stream_set_timeout($this->sock, $timeout_sec, $timeout_usec); + } + + /** + * After this method invoked with yesno=true, all requesting methods + * will not return a SSDB_Response object. + * And some certain methods like get/zget will return false + * when response is not ok(not_found, etc) + */ + function easy(){ + $this->_easy = true; + } + + function close(){ + if(!$this->_closed){ + @fclose($this->sock); + $this->_closed = true; + $this->sock = null; + } + } + + function closed(){ + return $this->_closed; + } + + private $batch_mode = false; + private $batch_cmds = array(); + + function batch(){ + $this->batch_mode = true; + $this->batch_cmds = array(); + return $this; + } + + function multi(){ + return $this->batch(); + } + + function exec(){ + $ret = array(); + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $this->send_req($cmd, $params); + } + foreach($this->batch_cmds as $op){ + list($cmd, $params) = $op; + $resp = $this->recv_resp($cmd, $params); + $resp = $this->check_easy_resp($cmd, $resp); + $ret[] = $resp; + } + $this->batch_mode = false; + $this->batch_cmds = array(); + return $ret; + } + + function request(){ + $args = func_get_args(); + $cmd = array_shift($args); + return $this->__call($cmd, $args); + } + + private $async_auth_password = null; + + function auth($password){ + $this->async_auth_password = $password; + return null; + } + + function __call($cmd, $params=array()){ + $cmd = strtolower($cmd); + if($this->async_auth_password !== null){ + $pass = $this->async_auth_password; + $this->async_auth_password = null; + $auth = $this->__call('auth', array($pass)); + if($auth !== true){ + throw new Exception("Authentication failed"); + } + } + + if($this->batch_mode){ + $this->batch_cmds[] = array($cmd, $params); + return $this; + } + + try{ + if($this->send_req($cmd, $params) === false){ + $resp = new SSDB_Response('error', 'send error'); + }else{ + $resp = $this->recv_resp($cmd, $params); + } + }catch(SSDBException $e){ + if($this->_easy){ + throw $e; + }else{ + $resp = new SSDB_Response('error', $e->getMessage()); + } + } + + if($resp->code == 'noauth'){ + $msg = $resp->message; + throw new Exception($msg); + } + + $resp = $this->check_easy_resp($cmd, $resp); + return $resp; + } + + private function check_easy_resp($cmd, $resp){ + $this->last_resp = $resp; + if($this->_easy){ + if($resp->not_found()){ + return NULL; + }else if(!$resp->ok() && !is_array($resp->data)){ + return false; + }else{ + return $resp->data; + } + }else{ + $resp->cmd = $cmd; + return $resp; + } + } + + function multi_set($kvs=array()){ + $args = array(); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_hset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function multi_zset($name, $kvs=array()){ + $args = array($name); + foreach($kvs as $k=>$v){ + $args[] = $k; + $args[] = $v; + } + return $this->__call(__FUNCTION__, $args); + } + + function incr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function decr($key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zincr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zdecr($name, $key, $score=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function zadd($key, $score, $value){ + $args = array($key, $value, $score); + return $this->__call('zset', $args); + } + + function zRevRank($name, $key){ + $args = func_get_args(); + return $this->__call("zrrank", $args); + } + + function zRevRange($name, $offset, $limit){ + $args = func_get_args(); + return $this->__call("zrrange", $args); + } + + function hincr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + function hdecr($name, $key, $val=1){ + $args = func_get_args(); + return $this->__call(__FUNCTION__, $args); + } + + private function send_req($cmd, $params){ + $req = array($cmd); + foreach($params as $p){ + if(is_array($p)){ + $req = array_merge($req, $p); + }else{ + $req[] = $p; + } + } + return $this->send($req); + } + + private function recv_resp($cmd, $params){ + $resp = $this->recv(); + if($resp === false){ + return new SSDB_Response('error', 'Unknown error'); + }else if(!$resp){ + return new SSDB_Response('disconnected', 'Connection closed'); + } + if($resp[0] == 'noauth'){ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + switch($cmd){ + case 'dbsize': + case 'ping': + case 'qset': + case 'getbit': + case 'setbit': + case 'countbit': + case 'strlen': + case 'set': + case 'setx': + case 'setnx': + case 'zset': + case 'hset': + case 'qpush': + case 'qpush_front': + case 'qpush_back': + case 'qtrim_front': + case 'qtrim_back': + case 'del': + case 'zdel': + case 'hdel': + case 'hsize': + case 'zsize': + case 'qsize': + case 'hclear': + case 'zclear': + case 'qclear': + case 'multi_set': + case 'multi_del': + case 'multi_hset': + case 'multi_hdel': + case 'multi_zset': + case 'multi_zdel': + case 'incr': + case 'decr': + case 'zincr': + case 'zdecr': + case 'hincr': + case 'hdecr': + case 'zget': + case 'zrank': + case 'zrrank': + case 'zcount': + case 'zsum': + case 'zremrangebyrank': + case 'zremrangebyscore': + case 'ttl': + case 'expire': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? intval($resp[1]) : 0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'zavg': + if($resp[0] == 'ok'){ + $val = isset($resp[1])? floatval($resp[1]) : (float)0; + return new SSDB_Response($resp[0], $val); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'get': + case 'substr': + case 'getset': + case 'hget': + case 'qget': + case 'qfront': + case 'qback': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'qpop': + case 'qpop_front': + case 'qpop_back': + if($resp[0] == 'ok'){ + $size = 1; + if(isset($params[1])){ + $size = intval($params[1]); + } + if($size <= 1){ + if(count($resp) == 2){ + return new SSDB_Response('ok', $resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $data = array_slice($resp, 1); + return new SSDB_Response('ok', $data); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'keys': + case 'zkeys': + case 'hkeys': + case 'hlist': + case 'zlist': + case 'qslice': + if($resp[0] == 'ok'){ + $data = array(); + if($resp[0] == 'ok'){ + $data = array_slice($resp, 1); + } + return new SSDB_Response($resp[0], $data); + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + case 'auth': + case 'exists': + case 'hexists': + case 'zexists': + if($resp[0] == 'ok'){ + if(count($resp) == 2){ + return new SSDB_Response('ok', (bool)$resp[1]); + }else{ + return new SSDB_Response('server_error', 'Invalid response'); + } + }else{ + $errmsg = isset($resp[1])? $resp[1] : ''; + return new SSDB_Response($resp[0], $errmsg); + } + break; + case 'multi_exists': + case 'multi_hexists': + case 'multi_zexists': + if($resp[0] == 'ok'){ + if(count($resp) % 2 == 1){ + $data = array(); + for($i=1; $idebug){ + echo '> ' . str_replace(array("\r", "\n"), array('\r', '\n'), $s) . "\n"; + } + try{ + while(true){ + $ret = @fwrite($this->sock, $s); + if($ret === false || $ret === 0){ + $this->close(); + throw new SSDBException('Connection lost'); + } + $s = substr($s, $ret); + if(strlen($s) == 0){ + break; + } + @fflush($this->sock); + } + }catch(Exception $e){ + $this->close(); + throw new SSDBException($e->getMessage()); + } + return $ret; + } + + function recv(){ + $this->step = self::STEP_SIZE; + while(true){ + $ret = $this->parse(); + if($ret === null){ + try{ + $data = @fread($this->sock, 1024 * 1024); + if($this->debug){ + echo '< ' . str_replace(array("\r", "\n"), array('\r', '\n'), $data) . "\n"; + } + }catch(Exception $e){ + $data = ''; + } + if($data === false || $data === ''){ + if(feof($this->sock)){ + $this->close(); + throw new SSDBException('Connection lost'); + }else{ + throw new SSDBTimeoutException('Connection timeout'); + } + } + $this->recv_buf .= $data; +# echo "read " . strlen($data) . " total: " . strlen($this->recv_buf) . "\n"; + }else{ + return $ret; + } + } + } + + const STEP_SIZE = 0; + const STEP_DATA = 1; + public $resp = array(); + public $step; + public $block_size; + + private function parse(){ + $spos = 0; + $epos = 0; + $buf_size = strlen($this->recv_buf); + // performance issue for large reponse + //$this->recv_buf = ltrim($this->recv_buf); + while(true){ + $spos = $epos; + if($this->step === self::STEP_SIZE){ + $epos = strpos($this->recv_buf, "\n", $spos); + if($epos === false){ + break; + } + $epos += 1; + $line = substr($this->recv_buf, $spos, $epos - $spos); + $spos = $epos; + + $line = trim($line); + if(strlen($line) == 0){ // head end + $this->recv_buf = substr($this->recv_buf, $spos); + $ret = $this->resp; + $this->resp = array(); + return $ret; + } + $this->block_size = intval($line); + $this->step = self::STEP_DATA; + } + if($this->step === self::STEP_DATA){ + $epos = $spos + $this->block_size; + if($epos <= $buf_size){ + $n = strpos($this->recv_buf, "\n", $epos); + if($n !== false){ + $data = substr($this->recv_buf, $spos, $epos - $spos); + $this->resp[] = $data; + $epos = $n + 1; + $this->step = self::STEP_SIZE; + continue; + } + } + break; + } + } + + // packet not ready + if($spos > 0){ + $this->recv_buf = substr($this->recv_buf, $spos); + } + return null; + } +} \ No newline at end of file diff --git a/app/TaskWorker/SSDBTask.php b/app/TaskWorker/SSDBTask.php new file mode 100644 index 0000000..9c6ef29 --- /dev/null +++ b/app/TaskWorker/SSDBTask.php @@ -0,0 +1,39 @@ +client()->__call($method,$args); + + return $result; + } + + protected function client(){ + if ($this->ss instanceof SimpleSSDB) { + return $this->ss; + } + + $this->ss = new SimpleSSDB(env('SSDB_HOST'), env('SSDB_PORT')); + $this->ss->auth(env('SSDB_AUTH')); + + return $this->ss; + + } +} + diff --git a/composer.json b/composer.json index a7581de..3b9ff4f 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,8 @@ "hyperf/model-cache": "~2.0.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0" + "hyperf/validation": "^2.0", + "hyperf/task": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/server.php b/config/autoload/server.php index d6211cc..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,10 +36,14 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, + 'task_worker_num' => 8, + 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], + SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], ]; diff --git a/config/routes.php b/config/routes.php index 37ec1e2..5e0a183 100644 --- a/config/routes.php +++ b/config/routes.php @@ -22,6 +22,7 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/evaluate', 'App\Controller\ServiceEvaluateController@evaluate'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); - + Router::get('test/index1', 'App\Controller\TestController@index1'); + }); \ No newline at end of file From 720dd8259b5d152b5ca2610f795be16c4188210a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 27 Jul 2020 14:58:06 +0800 Subject: [PATCH 08/72] =?UTF-8?q?composer.json=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=87=BA=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7e2cd5a..c9a89d0 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "hyperf/constants": "~2.0.0", "hyperf/model-cache": "~2.0.0", "hyperf/validation": "^2.0", - "hyperf/paginator": "^2.0" + "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", "hyperf/validation": "^2.0", From 1957bbfc1159b38f13719c254134bc87e685323a Mon Sep 17 00:00:00 2001 From: "DESKTOP-GG6FIN9\\Administrator" <15040771@qq.com> Date: Mon, 27 Jul 2020 16:37:13 +0800 Subject: [PATCH 09/72] =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E9=85=8D=E7=BD=AE=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/ServiceEvaluateController.php | 6 +++--- app/Service/ServiceEvaluateService.php | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/Controller/ServiceEvaluateController.php b/app/Controller/ServiceEvaluateController.php index 8440f30..edc7ab5 100644 --- a/app/Controller/ServiceEvaluateController.php +++ b/app/Controller/ServiceEvaluateController.php @@ -45,10 +45,10 @@ class ServiceEvaluateController extends BaseController //根据用户iD 获取服务专员详细信息 $service_personnel_id = $this->request->input('service_personnel_id', 0); $res = $this->evaluateService->getPersonnelInfo($service_personnel_id); - //如果存在服务专员则获取默认快捷评价 + //如果存在服务专员则获取配置信息 if(!empty($res)) { - $quick_evaluate = $this->evaluateService->getQuickEvaluate(); - $res->quick_evaluate = $quick_evaluate; + $config = $this->evaluateService->getQuickEvaluate(); + $res->config = $config; } return $this->success($res); } diff --git a/app/Service/ServiceEvaluateService.php b/app/Service/ServiceEvaluateService.php index d7cf885..675feb2 100644 --- a/app/Service/ServiceEvaluateService.php +++ b/app/Service/ServiceEvaluateService.php @@ -51,14 +51,21 @@ class ServiceEvaluateService implements ServiceEvaluateServiceInterface public function getQuickEvaluate() { $data = (object)null; + //获取快速评论标题 $obj1 = (object)null; $obj1->title1 = '服务态度超好'; $obj1->title2 = '服务态度一般般'; $data->quick_evaluate_title = $obj1; + //获取快速评论内容 $obj2 = (object)null; $obj2->content1 = '超级细心'; $obj2->content2 = '马马虎虎'; $data->quick_evaluate_content = $obj2; + //获取评论长度限制参数 + $obj3 = (object)null; + $obj3->min_length = 15; + $obj3->max_length = 150; + $data->length = $obj3; return $data; } From d5e066466c9bdf635fd2935f19232aa487438778 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 28 Jul 2020 17:59:08 +0800 Subject: [PATCH 10/72] =?UTF-8?q?=E5=9B=BE=E7=89=87=E3=80=81=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=8A=E4=BC=A0=E5=9F=BA=E7=A1=80=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 15 ++ app/Controller/AttachmentController.php | 68 +++++++ .../Handler/FilesystemExceptionHandler.php | 35 ++++ .../Handler/ValidationExceptionHandler.php | 35 ++++ .../ValidatorFactoryResolvedListener.php | 71 +++++++ app/Request/AttachmentRequest.php | 47 +++++ app/Request/ImageBase64Request.php | 46 +++++ app/Request/ImageRequest.php | 46 +++++ app/Service/AttachmentService.php | 73 ++++++++ app/Service/AttachmentServiceInterface.php | 23 +++ composer.json | 5 +- config/autoload/dependencies.php | 1 + config/autoload/exceptions.php | 2 + config/autoload/file.php | 94 ++++++++++ config/autoload/listeners.php | 1 + config/autoload/middlewares.php | 3 +- config/autoload/server.php | 4 + config/autoload/translation.php | 16 ++ config/routes.php | 4 +- storage/languages/en/validation.php | 177 ++++++++++++++++++ storage/languages/zh_CN/validation.php | 177 ++++++++++++++++++ 21 files changed, 940 insertions(+), 3 deletions(-) create mode 100644 app/Controller/AttachmentController.php create mode 100644 app/Exception/Handler/FilesystemExceptionHandler.php create mode 100644 app/Exception/Handler/ValidationExceptionHandler.php create mode 100644 app/Listener/ValidatorFactoryResolvedListener.php create mode 100644 app/Request/AttachmentRequest.php create mode 100644 app/Request/ImageBase64Request.php create mode 100644 app/Request/ImageRequest.php create mode 100644 app/Service/AttachmentService.php create mode 100644 app/Service/AttachmentServiceInterface.php create mode 100644 config/autoload/file.php create mode 100644 config/autoload/translation.php create mode 100644 storage/languages/en/validation.php create mode 100644 storage/languages/zh_CN/validation.php diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index 0651e85..1a1dc07 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -23,4 +23,19 @@ class ErrorCode extends AbstractConstants * @Message("Server Error!") */ const SERVER_ERROR = 500; + + /** + * @Message("Params Invalid!") + */ + const PARAMS_INVALID = 900; + + /** + * @Message("Save Failure!") + */ + const SAVE_FAILURE = 100; + + /** + * @Message("文件上传异常") + */ + const UPLOAD_INVALID = 200; } diff --git a/app/Controller/AttachmentController.php b/app/Controller/AttachmentController.php new file mode 100644 index 0000000..efbf45d --- /dev/null +++ b/app/Controller/AttachmentController.php @@ -0,0 +1,68 @@ +request->file('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->formUpload($file, $type, $filesystem, 'file'); + + return $this->success(['file_path' => $fileName]); + } + + /** + * 单图表单上传 + * @param ImageRequest $request + * @param Filesystem $filesystem + * @return \Psr\Http\Message\ResponseInterface + */ + public function uploadImage(ImageRequest $request, Filesystem $filesystem) + { + $file = $this->request->file('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->formUpload($file, $type, $filesystem); + + return $this->success(['file_path' => $fileName]); + } + + /** + * 单图base64上传 + * @param ImageBase64Request $request + * @param Filesystem $filesystem + * @return \Psr\Http\Message\ResponseInterface + */ + public function uploadImageByBase64(ImageBase64Request $request, Filesystem $filesystem) + { + $base64Code = $this->request->input('upload'); + $type = $this->request->input('type', ''); + + $fileName = $this->attachmentService->base64Upload($base64Code, $type, $filesystem); + + return $this->success(['file_path' => $fileName]); + } + +} \ No newline at end of file diff --git a/app/Exception/Handler/FilesystemExceptionHandler.php b/app/Exception/Handler/FilesystemExceptionHandler.php new file mode 100644 index 0000000..f5f1b1c --- /dev/null +++ b/app/Exception/Handler/FilesystemExceptionHandler.php @@ -0,0 +1,35 @@ +stopPropagation(); + + $content = json_encode([ + "status" => 'error', + "code" => ErrorCode::UPLOAD_INVALID, + "result" => [], + "message" => $throwable->getMessage() + ]); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof FilesystemException; + } +} \ No newline at end of file diff --git a/app/Exception/Handler/ValidationExceptionHandler.php b/app/Exception/Handler/ValidationExceptionHandler.php new file mode 100644 index 0000000..cc2384c --- /dev/null +++ b/app/Exception/Handler/ValidationExceptionHandler.php @@ -0,0 +1,35 @@ +stopPropagation(); + + $content = json_encode([ + "status" => 'error', + "code" => ErrorCode::PARAMS_INVALID, + "result" => [], + "message" => $throwable->validator->errors()->first() + ]); + + return $response->withHeader('Content-Type', 'application/json') + ->withStatus($throwable->status) + ->withBody(new SwooleStream($content)); + } + + public function isValid(Throwable $throwable): bool + { + return $throwable instanceof ValidationException; + } +} \ No newline at end of file diff --git a/app/Listener/ValidatorFactoryResolvedListener.php b/app/Listener/ValidatorFactoryResolvedListener.php new file mode 100644 index 0000000..7e32d66 --- /dev/null +++ b/app/Listener/ValidatorFactoryResolvedListener.php @@ -0,0 +1,71 @@ +validatorFactory; + + // 注册了 nonempty 验证器规则 + $validatorFactory->extend('nonempty', function ($attribute, $value, $parameters, $validator) { + + return isset($value) + && $value + && !empty($value) + && !is_null($value) + && $value != 'undefined' + && $value != 'unknown' + && $value != 'null' + && $value != 'false'; + + }); + + // 注册了 base64 验证器规则 + $validatorFactory->extend('base64', function ($attribute, $value, $parameters, $validator) { + + preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result); + + if (empty($result)) { + return false; + } + + if ( + in_array('image', $parameters) + && !in_array($result[2], ['jpg','jpeg','png','gif','svg','bmp']) + ) { + return false; + } + + return true; + + }); + + // 注册了 ext_not_in 验证器规则 + $validatorFactory->extend('ext_not_in', function ($attribute, $value, $parameters, $validator) { + + if (empty($parameters)) { + $parameters = ['', 'php', 'exe', 'sql', 'sh', 'bat', 'py', 'go', 'c', 'cpp']; + } + return !in_array($value->getExtension(), $parameters); + + }); + + } +} \ No newline at end of file diff --git a/app/Request/AttachmentRequest.php b/app/Request/AttachmentRequest.php new file mode 100644 index 0000000..da2e1f0 --- /dev/null +++ b/app/Request/AttachmentRequest.php @@ -0,0 +1,47 @@ + 'required|nonempty|file|ext_not_in', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.nonempty' => '文件异常', + 'upload.file' => '文件上传不成功', + 'upload.ext_not_in' => '文件不允许上传', + 'type.nonempty' => '文件类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '文件' + ]; + } +} diff --git a/app/Request/ImageBase64Request.php b/app/Request/ImageBase64Request.php new file mode 100644 index 0000000..88a752a --- /dev/null +++ b/app/Request/ImageBase64Request.php @@ -0,0 +1,46 @@ + 'required|nonempty|base64:image', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.base64' => '文件不是正常的图片', + 'upload.nonempty' => '文件异常', + 'type.nonempty' => '图片类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '图片' + ]; + } +} diff --git a/app/Request/ImageRequest.php b/app/Request/ImageRequest.php new file mode 100644 index 0000000..85bad47 --- /dev/null +++ b/app/Request/ImageRequest.php @@ -0,0 +1,46 @@ + 'required|nonempty|file|image', + 'type' => 'nonempty|alpha' + ]; + } + + public function messages(): array + { + return [ + 'upload.required' => '未选择上传的文件', + 'upload.image' => '文件不是正常的图片', + 'upload.nonempty' => '文件异常', + 'type.nonempty' => '图片类型参数异常', + ]; + } + + public function attributes(): array + { + return [ + 'upload' => '图片' + ]; + } +} diff --git a/app/Service/AttachmentService.php b/app/Service/AttachmentService.php new file mode 100644 index 0000000..65ab9a4 --- /dev/null +++ b/app/Service/AttachmentService.php @@ -0,0 +1,73 @@ +getRealPath(); + $fileHash = md5_file($fileRealPath); + + $path = $this->getBasePath($path, $attachmenttype); + $fileName = $path . '/' . $fileHash . '.' . $file->getExtension(); + + $stream = fopen($fileRealPath, 'r+'); + $filesystem->writeStream($fileName, $stream); + fclose($stream); + + return $fileName; + } + + /** + * @inheritDoc + */ + public function base64Upload($contents, $path, $filesystem) + { + + preg_match('/^(data:\s*image\/(\w+);base64,)/', $contents, $result); + if (empty($result)) { + throw new FilesystemNotFoundException(ErrorCode::getMessage(ErrorCode::UPLOAD_INVALID),ErrorCode::UPLOAD_INVALID); + } + + $contents = base64_decode(str_replace($result[1], '', $contents)); + + $fileHash = md5($contents); + $path = $this->getBasePath($path); + $fileName = $path . '/' . $fileHash . '.' . $result[2]; + + $filesystem->write($fileName, $contents); + + return $fileName; + } + + protected function getBasePath($path, $attachmenttype = 'image') + { + switch ($attachmenttype) { + case 'image': + $baseDir = env('IMAGE_BASE', '/attachment/images'); + break; + + case 'file': + $baseDir = env('FILES_BASE', '/attachment/files'); + break; + + default: + $baseDir = env('FILES_BASE', '/attachment'); + break; + } + + $path = $path ? '/'.$path : ''; + $path .= '/'.date('Y').'/'.date('m').'/'.date('d'); + return $baseDir.$path; + } +} \ No newline at end of file diff --git a/app/Service/AttachmentServiceInterface.php b/app/Service/AttachmentServiceInterface.php new file mode 100644 index 0000000..28439b2 --- /dev/null +++ b/app/Service/AttachmentServiceInterface.php @@ -0,0 +1,23 @@ + \App\Service\AttachmentService::class ]; diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 895bda9..1776a7c 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -14,6 +14,8 @@ return [ 'http' => [ Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, App\Exception\Handler\AppExceptionHandler::class, + \App\Exception\Handler\ValidationExceptionHandler::class, + \App\Exception\Handler\FilesystemExceptionHandler::class, ], ], ]; diff --git a/config/autoload/file.php b/config/autoload/file.php new file mode 100644 index 0000000..6744d66 --- /dev/null +++ b/config/autoload/file.php @@ -0,0 +1,94 @@ + 'oss', + 'storage' => [ + 'local' => [ + 'driver' => \Hyperf\Filesystem\Adapter\LocalAdapterFactory::class, + 'root' => BASE_PATH . '/attachment', + ], + 'ftp' => [ + 'driver' => \Hyperf\Filesystem\Adapter\FtpAdapterFactory::class, + 'host' => 'ftp.example.com', + 'username' => 'username', + 'password' => 'password', + // 'port' => 21, + // 'root' => '/path/to/root', + // 'passive' => true, + // 'ssl' => true, + // 'timeout' => 30, + // 'ignorePassiveAddress' => false, + ], + 'memory' => [ + 'driver' => \Hyperf\Filesystem\Adapter\MemoryAdapterFactory::class, + ], + 's3' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => false, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'minio' => [ + 'driver' => \Hyperf\Filesystem\Adapter\S3AdapterFactory::class, + 'credentials' => [ + 'key' => env('S3_KEY'), + 'secret' => env('S3_SECRET'), + ], + 'region' => env('S3_REGION'), + 'version' => 'latest', + 'bucket_endpoint' => false, + 'use_path_style_endpoint' => true, + 'endpoint' => env('S3_ENDPOINT'), + 'bucket_name' => env('S3_BUCKET'), + ], + 'oss' => [ + 'driver' => \Hyperf\Filesystem\Adapter\AliyunOssAdapterFactory::class, + 'accessId' => env('OSS_ACCESS_ID'), + 'accessSecret' => env('OSS_ACCESS_SECRET'), + 'bucket' => env('OSS_BUCKET'), + 'endpoint' => env('OSS_ENDPOINT'), + // 'timeout' => 3600, + // 'connectTimeout' => 10, + // 'isCName' => false, + // 'token' => '', + ], + 'qiniu' => [ + 'driver' => \Hyperf\Filesystem\Adapter\QiniuAdapterFactory::class, + 'accessKey' => env('QINIU_ACCESS_KEY'), + 'secretKey' => env('QINIU_SECRET_KEY'), + 'bucket' => env('QINIU_BUCKET'), + 'domain' => env('QINBIU_DOMAIN'), + ], + 'cos' => [ + 'driver' => \Hyperf\Filesystem\Adapter\CosAdapterFactory::class, + 'region' => env('COS_REGION'), + 'credentials' => [ + 'appId' => env('COS_APPID'), + 'secretId' => env('COS_SECRET_ID'), + 'secretKey' => env('COS_SECRET_KEY'), + ], + 'bucket' => env('COS_BUCKET'), + 'read_from_cdn' => false, + // 'timeout' => 60, + // 'connect_timeout' => 60, + // 'cdn' => '', + // 'scheme' => 'https', + ], + ], +]; diff --git a/config/autoload/listeners.php b/config/autoload/listeners.php index 55b80d5..2741751 100644 --- a/config/autoload/listeners.php +++ b/config/autoload/listeners.php @@ -10,4 +10,5 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ + \App\Listener\ValidatorFactoryResolvedListener::class, ]; diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 8a27adf..2a5ddb0 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,6 +11,7 @@ declare(strict_types=1); */ return [ 'http' => [ - \App\Middleware\Auth\ApiMiddleware::class + \App\Middleware\Auth\ApiMiddleware::class, + \Hyperf\Validation\Middleware\ValidationMiddleware::class ], ]; diff --git a/config/autoload/server.php b/config/autoload/server.php index d6211cc..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,10 +36,14 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, + 'task_worker_num' => 8, + 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], + SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], ]; diff --git a/config/autoload/translation.php b/config/autoload/translation.php new file mode 100644 index 0000000..35b9f06 --- /dev/null +++ b/config/autoload/translation.php @@ -0,0 +1,16 @@ + 'zh_CN', + 'fallback_locale' => 'en', + 'path' => BASE_PATH . '/storage/languages', +]; diff --git a/config/routes.php b/config/routes.php index 10aa6e4..2cc6647 100644 --- a/config/routes.php +++ b/config/routes.php @@ -19,5 +19,7 @@ Router::addGroup('/v1/',function (){ Router::post('CouponUserReceive/getUserReceiveCouponList', 'App\Controller\CouponController@getUserReceiveCouponList'); Router::post('CouponUserReceive/userReceiveCoupon', 'App\Controller\CouponController@userReceiveCoupon'); Router::post('CouponUserReceive/getUserAvailableCoupons', 'App\Controller\CouponController@getUserAvailableCoupons'); - + Router::post('Attachment/uploadImage', 'App\Controller\AttachmentController@uploadImage'); + Router::post('Attachment/uploadImageByBase64', 'App\Controller\AttachmentController@uploadImageByBase64'); + Router::post('Attachment/upload', 'App\Controller\AttachmentController@upload'); }); \ No newline at end of file diff --git a/storage/languages/en/validation.php b/storage/languages/en/validation.php new file mode 100644 index 0000000..5e128a6 --- /dev/null +++ b/storage/languages/en/validation.php @@ -0,0 +1,177 @@ + 'The :attribute must be accepted.', + 'active_url' => 'The :attribute is not a valid URL.', + 'after' => 'The :attribute must be a date after :date.', + 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', + 'alpha' => 'The :attribute may only contain letters.', + 'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.', + 'alpha_num' => 'The :attribute may only contain letters and numbers.', + 'array' => 'The :attribute must be an array.', + 'before' => 'The :attribute must be a date before :date.', + 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', + 'between' => [ + 'numeric' => 'The :attribute must be between :min and :max.', + 'file' => 'The :attribute must be between :min and :max kilobytes.', + 'string' => 'The :attribute must be between :min and :max characters.', + 'array' => 'The :attribute must have between :min and :max items.', + ], + 'boolean' => 'The :attribute field must be true or false.', + 'confirmed' => 'The :attribute confirmation does not match.', + 'date' => 'The :attribute is not a valid date.', + 'date_format' => 'The :attribute does not match the format :format.', + 'different' => 'The :attribute and :other must be different.', + 'digits' => 'The :attribute must be :digits digits.', + 'digits_between' => 'The :attribute must be between :min and :max digits.', + 'dimensions' => 'The :attribute has invalid image dimensions.', + 'distinct' => 'The :attribute field has a duplicate value.', + 'email' => 'The :attribute must be a valid email address.', + 'exists' => 'The selected :attribute is invalid.', + 'file' => 'The :attribute must be a file.', + 'filled' => 'The :attribute field is required.', + 'gt' => [ + 'numeric' => 'The :attribute must be greater than :value', + 'file' => 'The :attribute must be greater than :value kb', + 'string' => 'The :attribute must be greater than :value characters', + 'array' => 'The :attribute must be greater than :value items', + ], + 'gte' => [ + 'numeric' => 'The :attribute must be great than or equal to :value', + 'file' => 'The :attribute must be great than or equal to :value kb', + 'string' => 'The :attribute must be great than or equal to :value characters', + 'array' => 'The :attribute must be great than or equal to :value items', + ], + 'image' => 'The :attribute must be an image.', + 'in' => 'The selected :attribute is invalid.', + 'in_array' => 'The :attribute field does not exist in :other.', + 'integer' => 'The :attribute must be an integer.', + 'ip' => 'The :attribute must be a valid IP address.', + 'ipv4' => 'The :attribute must be a valid IPv4 address.', + 'ipv6' => 'The :attribute must be a valid IPv6 address.', + 'json' => 'The :attribute must be a valid JSON string.', + 'lt' => [ + 'numeric' => 'The :attribute must be less than :value', + 'file' => 'The :attribute must be less than :value kb', + 'string' => 'The :attribute must be less than :value characters', + 'array' => 'The :attribute must be less than :value items', + ], + 'lte' => [ + 'numeric' => 'The :attribute must be less than or equal to :value', + 'file' => 'The :attribute must be less than or equal to :value kb', + 'string' => 'The :attribute must be less than or equal to :value characters', + 'array' => 'The :attribute must be less than or equal to :value items', + ], + 'max' => [ + 'numeric' => 'The :attribute may not be greater than :max.', + 'file' => 'The :attribute may not be greater than :max kilobytes.', + 'string' => 'The :attribute may not be greater than :max characters.', + 'array' => 'The :attribute may not have more than :max items.', + ], + 'mimes' => 'The :attribute must be a file of type: :values.', + 'mimetypes' => 'The :attribute must be a file of type: :values.', + 'min' => [ + 'numeric' => 'The :attribute must be at least :min.', + 'file' => 'The :attribute must be at least :min kilobytes.', + 'string' => 'The :attribute must be at least :min characters.', + 'array' => 'The :attribute must have at least :min items.', + ], + 'not_in' => 'The selected :attribute is invalid.', + 'not_regex' => 'The :attribute cannot match a given regular rule.', + 'numeric' => 'The :attribute must be a number.', + 'present' => 'The :attribute field must be present.', + 'regex' => 'The :attribute format is invalid.', + 'required' => 'The :attribute field is required.', + 'required_if' => 'The :attribute field is required when :other is :value.', + 'required_unless' => 'The :attribute field is required unless :other is in :values.', + 'required_with' => 'The :attribute field is required when :values is present.', + 'required_with_all' => 'The :attribute field is required when :values is present.', + 'required_without' => 'The :attribute field is required when :values is not present.', + 'required_without_all' => 'The :attribute field is required when none of :values are present.', + 'same' => 'The :attribute and :other must match.', + 'size' => [ + 'numeric' => 'The :attribute must be :size.', + 'file' => 'The :attribute must be :size kilobytes.', + 'string' => 'The :attribute must be :size characters.', + 'array' => 'The :attribute must contain :size items.', + ], + 'starts_with' => 'The :attribute must be start with :values ', + 'string' => 'The :attribute must be a string.', + 'timezone' => 'The :attribute must be a valid zone.', + 'unique' => 'The :attribute has already been taken.', + 'uploaded' => 'The :attribute failed to upload.', + 'url' => 'The :attribute format is invalid.', + 'uuid' => 'The :attribute is invalid UUID.', + 'max_if' => [ + 'numeric' => 'The :attribute may not be greater than :max when :other is :value.', + 'file' => 'The :attribute may not be greater than :max kilobytes when :other is :value.', + 'string' => 'The :attribute may not be greater than :max characters when :other is :value.', + 'array' => 'The :attribute may not have more than :max items when :other is :value.', + ], + 'min_if' => [ + 'numeric' => 'The :attribute must be at least :min when :other is :value.', + 'file' => 'The :attribute must be at least :min kilobytes when :other is :value.', + 'string' => 'The :attribute must be at least :min characters when :other is :value.', + 'array' => 'The :attribute must have at least :min items when :other is :value.', + ], + 'between_if' => [ + 'numeric' => 'The :attribute must be between :min and :max when :other is :value.', + 'file' => 'The :attribute must be between :min and :max kilobytes when :other is :value.', + 'string' => 'The :attribute must be between :min and :max characters when :other is :value.', + 'array' => 'The :attribute must have between :min and :max items when :other is :value.', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => 'The :attribute must be a valid phone number', + 'telephone_number' => 'The :attribute must be a valid telephone number', + + 'chinese_word' => 'The :attribute must contain valid characters(chinese/english character, number, underscore)', + 'sequential_array' => 'The :attribute must be sequential array', +]; diff --git a/storage/languages/zh_CN/validation.php b/storage/languages/zh_CN/validation.php new file mode 100644 index 0000000..8093224 --- /dev/null +++ b/storage/languages/zh_CN/validation.php @@ -0,0 +1,177 @@ + ':attribute 必须接受', + 'active_url' => ':attribute 必须是一个合法的 URL', + 'after' => ':attribute 必须是 :date 之后的一个日期', + 'after_or_equal' => ':attribute 必须是 :date 之后或相同的一个日期', + 'alpha' => ':attribute 只能包含字母', + 'alpha_dash' => ':attribute 只能包含字母、数字、中划线或下划线', + 'alpha_num' => ':attribute 只能包含字母和数字', + 'array' => ':attribute 必须是一个数组', + 'before' => ':attribute 必须是 :date 之前的一个日期', + 'before_or_equal' => ':attribute 必须是 :date 之前或相同的一个日期', + 'between' => [ + 'numeric' => ':attribute 必须在 :min 到 :max 之间', + 'file' => ':attribute 必须在 :min 到 :max kb 之间', + 'string' => ':attribute 必须在 :min 到 :max 个字符之间', + 'array' => ':attribute 必须在 :min 到 :max 项之间', + ], + 'boolean' => ':attribute 字符必须是 true 或 false, 1 或 0', + 'confirmed' => ':attribute 二次确认不匹配', + 'date' => ':attribute 必须是一个合法的日期', + 'date_format' => ':attribute 与给定的格式 :format 不符合', + 'different' => ':attribute 必须不同于 :other', + 'digits' => ':attribute 必须是 :digits 位', + 'digits_between' => ':attribute 必须在 :min 和 :max 位之间', + 'dimensions' => ':attribute 具有无效的图片尺寸', + 'distinct' => ':attribute 字段具有重复值', + 'email' => ':attribute 必须是一个合法的电子邮件地址', + 'exists' => '选定的 :attribute 是无效的', + 'file' => ':attribute 必须是一个文件', + 'filled' => ':attribute 的字段是必填的', + 'gt' => [ + 'numeric' => ':attribute 必须大于 :value', + 'file' => ':attribute 必须大于 :value kb', + 'string' => ':attribute 必须大于 :value 个字符', + 'array' => ':attribute 必须大于 :value 项', + ], + 'gte' => [ + 'numeric' => ':attribute 必须大于等于 :value', + 'file' => ':attribute 必须大于等于 :value kb', + 'string' => ':attribute 必须大于等于 :value 个字符', + 'array' => ':attribute 必须大于等于 :value 项', + ], + 'image' => ':attribute 必须是 jpg, jpeg, png, bmp 或者 gif 格式的图片', + 'in' => '选定的 :attribute 是无效的', + 'in_array' => ':attribute 字段不存在于 :other', + 'integer' => ':attribute 必须是个整数', + 'ip' => ':attribute 必须是一个合法的 IP 地址', + 'ipv4' => ':attribute 必须是一个合法的 IPv4 地址', + 'ipv6' => ':attribute 必须是一个合法的 IPv6 地址', + 'json' => ':attribute 必须是一个合法的 JSON 字符串', + 'lt' => [ + 'numeric' => ':attribute 必须小于 :value', + 'file' => ':attribute 必须小于 :value kb', + 'string' => ':attribute 必须小于 :value 个字符', + 'array' => ':attribute 必须小于 :value 项', + ], + 'lte' => [ + 'numeric' => ':attribute 必须小于等于 :value', + 'file' => ':attribute 必须小于等于 :value kb', + 'string' => ':attribute 必须小于等于 :value 个字符', + 'array' => ':attribute 必须小于等于 :value 项', + ], + 'max' => [ + 'numeric' => ':attribute 的最大值为 :max', + 'file' => ':attribute 的最大为 :max kb', + 'string' => ':attribute 的最大长度为 :max 字符', + 'array' => ':attribute 至多有 :max 项', + ], + 'mimes' => ':attribute 的文件类型必须是 :values', + 'mimetypes' => ':attribute 的文件MIME必须是 :values', + 'min' => [ + 'numeric' => ':attribute 的最小值为 :min', + 'file' => ':attribute 大小至少为 :min kb', + 'string' => ':attribute 的最小长度为 :min 字符', + 'array' => ':attribute 至少有 :min 项', + ], + 'not_in' => '选定的 :attribute 是无效的', + 'not_regex' => ':attribute 不能匹配给定的正则', + 'numeric' => ':attribute 必须是数字', + 'present' => ':attribute 字段必须存在', + 'regex' => ':attribute 格式是无效的', + 'required' => ':attribute 字段是必须的', + 'required_if' => ':attribute 字段是必须的当 :other 是 :value', + 'required_unless' => ':attribute 字段是必须的,除非 :other 是在 :values 中', + 'required_with' => ':attribute 字段是必须的当 :values 是存在的', + 'required_with_all' => ':attribute 字段是必须的当 :values 是存在的', + 'required_without' => ':attribute 字段是必须的当 :values 是不存在的', + 'required_without_all' => ':attribute 字段是必须的当 没有一个 :values 是存在的', + 'same' => ':attribute 和 :other 必须匹配', + 'size' => [ + 'numeric' => ':attribute 必须是 :size', + 'file' => ':attribute 必须是 :size kb', + 'string' => ':attribute 必须是 :size 个字符', + 'array' => ':attribute 必须包括 :size 项', + ], + 'starts_with' => ':attribute 必须以 :values 为开头', + 'string' => ':attribute 必须是一个字符串', + 'timezone' => ':attribute 必须是个有效的时区', + 'unique' => ':attribute 已存在', + 'uploaded' => ':attribute 上传失败', + 'url' => ':attribute 无效的格式', + 'uuid' => ':attribute 无效的UUID格式', + 'max_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 不能大于 :max', + 'file' => '当 :other 为 :value 时 :attribute 不能大于 :max kb', + 'string' => '当 :other 为 :value 时 :attribute 不能大于 :max 个字符', + 'array' => '当 :other 为 :value 时 :attribute 最多只有 :max 个单元', + ], + 'min_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须大于等于 :min', + 'file' => '当 :other 为 :value 时 :attribute 大小不能小于 :min kb', + 'string' => '当 :other 为 :value 时 :attribute 至少为 :min 个字符', + 'array' => '当 :other 为 :value 时 :attribute 至少有 :min 个单元', + ], + 'between_if' => [ + 'numeric' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 之间', + 'file' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max kb 之间', + 'string' => '当 :other 为 :value 时 :attribute 必须介于 :min - :max 个字符之间', + 'array' => '当 :other 为 :value 时 :attribute 必须只有 :min - :max 个单元', + ], + /* + |-------------------------------------------------------------------------- + | Custom Validation Language Lines + |-------------------------------------------------------------------------- + | + | Here you may specify custom validation messages for attributes using the + | convention "attribute.rule" to name the lines. This makes it quick to + | specify a specific custom language line for a given attribute rule. + | + */ + + 'custom' => [ + 'attribute-name' => [ + 'rule-name' => 'custom-message', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Validation Attributes + |-------------------------------------------------------------------------- + | + | The following language lines are used to swap attribute place-holders + | with something more reader friendly such as E-Mail Address instead + | of "email". This simply helps us make messages a little cleaner. + | + */ + + 'attributes' => [], + 'phone_number' => ':attribute 必须为一个有效的电话号码', + 'telephone_number' => ':attribute 必须为一个有效的手机号码', + + 'chinese_word' => ':attribute 必须包含以下有效字符 (中文/英文,数字, 下划线)', + 'sequential_array' => ':attribute 必须是一个有序数组', +]; From cb16f46f1a18fef2e4409a5fbee728a59fa43b36 Mon Sep 17 00:00:00 2001 From: Mike Date: Sat, 1 Aug 2020 19:47:38 +0800 Subject: [PATCH 11/72] add ali iot vendor --- app/Controller/TestController.php | 10 +++- app/TaskWorker/AliIotTask.php | 91 +++++++++++++++++++++++++++++++ app/TaskWorker/PubRequest.php | 56 +++++++++++++++++++ composer.json | 4 +- 4 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 app/TaskWorker/AliIotTask.php create mode 100644 app/TaskWorker/PubRequest.php diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index bc034d0..78c2327 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -11,6 +11,7 @@ use Hyperf\Utils\ApplicationContext; use Hyperf\Task\TaskExecutor; use Hyperf\Task\Task; use App\TaskWorker\SSDBTask; +use App\TaskWorker\AliIotTask; /** * @AutoController() @@ -28,9 +29,12 @@ class TestController extends AbstractController // $exec = $container->get(TaskExecutor::class); // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); - $client = ApplicationContext::getContainer()->get(SSDBTask::class); - $result = $client->exec("set","bar","1234"); - $result = $client->exec("get","bar"); + // $client = ApplicationContext::getContainer()->get(SSDBTask::class); + // $result = $client->exec("set","bar","1234"); + // $result = $client->exec("get","bar"); + $client = ApplicationContext::getContainer()->get(AliIotTask::class); + + $client->exec("set","bar","1234"); // $client = ApplicationContext::getContainer()->get(MethodTask::class); // $result = $client->handle("set"); diff --git a/app/TaskWorker/AliIotTask.php b/app/TaskWorker/AliIotTask.php new file mode 100644 index 0000000..e629137 --- /dev/null +++ b/app/TaskWorker/AliIotTask.php @@ -0,0 +1,91 @@ +regionId('cn-shanghai') + ->asDefaultClient(); + $result2 = ''; + + $msg = "{\"msg\":\"收款123元\"}"; + try{ + AlibabaCloud::rpc() + ->product('Iot') + // ->scheme('https') // https | http + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host('iot.cn-shanghai.aliyuncs.com') + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => "a1ZSurIJmO0", + ], + ]) + ->request(); + //var_dump($result2->toArray()); + } catch (ClientException $e) { + echo $e->getErrorMessage() . PHP_EOL; + } catch (ServerException $e) { + echo $e->getErrorMessage() . PHP_EOL; + } + + //print_r($response); + return ""; + } + +// protected function getClient(){ +// AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap') +// ->regionId('cn-shanghai') +// ->asDefaultClient(); +// $result = ''; + +// $msg = "{\"msg\":\"收款123元\"}"; +// try{ +// $result = AlibabaCloud::rpc() +// ->product('Iot') +// // ->scheme('https') // https | http +// ->version('2018-01-20') +// ->action('Pub') +// ->method('POST') +// ->host('iot.cn-shanghai.aliyuncs.com') +// ->options([ +// 'query' => [ +// 'RegionId' => "cn-shanghai", +// 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", +// 'MessageContent' => base64_encode($msg), +// 'ProductKey' => "a1ZSurIJmO0", +// ], +// ]) +// ->request(); +// var_dump($result->toArray()); +// } catch (ClientException $e) { +// echo $e->getErrorMessage() . PHP_EOL; +// } catch (ServerException $e) { +// echo $e->getErrorMessage() . PHP_EOL; +// } +// return $result; + +// } +} + diff --git a/app/TaskWorker/PubRequest.php b/app/TaskWorker/PubRequest.php new file mode 100644 index 0000000..e784ee1 --- /dev/null +++ b/app/TaskWorker/PubRequest.php @@ -0,0 +1,56 @@ +setMethod("POST"); + } + + private $topicFullName; + + private $qos; + + private $messageContent; + + private $productKey; + + public function getTopicFullName() { + return $this->topicFullName; + } + + public function setTopicFullName($topicFullName) { + $this->topicFullName = $topicFullName; + $this->queryParameters["TopicFullName"]=$topicFullName; + } + + public function getQos() { + return $this->qos; + } + + public function setQos($qos) { + $this->qos = $qos; + $this->queryParameters["Qos"]=$qos; + } + + public function getMessageContent() { + return $this->messageContent; + } + + public function setMessageContent($messageContent) { + $this->messageContent = $messageContent; + $this->queryParameters["MessageContent"]=$messageContent; + } + + public function getProductKey() { + return $this->productKey; + } + + public function setProductKey($productKey) { + $this->productKey = $productKey; + $this->queryParameters["ProductKey"]=$productKey; + } + +} \ No newline at end of file diff --git a/composer.json b/composer.json index c9a89d0..0910063 100644 --- a/composer.json +++ b/composer.json @@ -31,8 +31,8 @@ "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0", - "hyperf/task": "^2.0" + "hyperf/task": "^2.0", + "alibabacloud/iot": "^1.8" }, "require-dev": { "swoole/ide-helper": "^4.5", From 9bd0f9b2166785d6c3bdd064f48824a4f34278e0 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 16:38:15 +0800 Subject: [PATCH 12/72] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Commons/Log.php | 88 +++++++++++++++++++++++++++ app/Controller/AbstractController.php | 8 +++ app/Controller/TestController.php | 16 +++-- composer.json | 3 +- config/autoload/dependencies.php | 1 + 5 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 app/Commons/Log.php diff --git a/app/Commons/Log.php b/app/Commons/Log.php new file mode 100644 index 0000000..bf5fb24 --- /dev/null +++ b/app/Commons/Log.php @@ -0,0 +1,88 @@ +clientFactory = $clientFactory; + } + + public function getClient() + { + // $options 等同于 GuzzleHttp\Client 构造函数的 $config 参数 + $options = [ + 'timeout' => 2.0, + ]; + // $client 为协程化的 GuzzleHttp\Client 对象 + $client = $this->clientFactory->create($options); + + return $client; + } + + public function event($labels=null,$datas){ + + co(function () use ($labels,$datas){ + + $client = $this->getClient(); + $kv = []; + foreach ($datas as $key => $value) { + $kv[] = $key."=".$value; + } + $pushLabels = []; + + $event_name = 'event_'.env('APP_ENV'); + if(!empty($labels)) $pushLabels[$event_name] = $labels; + + /* + * data format: + curl -v -H "Content-Type: application/json" -XPOST -s "http://39.96.12.39:3100/loki/api/v1/push" --data-raw \ + '{"streams": [{ "stream": { "foo": "bar2" }, "values": [ [ "1596274538882028800", "fizzbuzz" ] ] }]}' + */ + $ts = $this->getMsecTime() . '000000'; + $datas = implode("&",$kv); + $values = [[$ts,$datas]]; + $app_name = env('APP_NAME').'_'.env('APP_ENV'); + + $pushLabels['app']= $app_name; + $pushDatas = [ + 'streams'=>[ + [ + 'stream'=>$pushLabels, + 'values'=>$values, + ] + ] + ]; + $client->post( + 'http://39.96.12.39:3100/loki/api/v1/push', + [ + 'headers'=>[ + 'Content-Type'=>'application/json' + ], + 'body' => json_encode($pushDatas) + ] + ); + //var_dump(json_encode($pushDatas) ); + }); + } + + + public function push($datas){ + $this->event(null,$datas); + } + + public function getMsecTime() + { + list($msec, $sec) = explode(' ', microtime()); + $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); + return $msectime; + } + +} diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index be3a537..b7429ea 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -15,9 +15,17 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Container\ContainerInterface; +use App\Commons\Log; abstract class AbstractController { + + /** + * @Inject + * @var Log + */ + protected $log; + /** * @Inject * @var ContainerInterface diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index bc034d0..f69cea8 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -11,6 +11,7 @@ use Hyperf\Utils\ApplicationContext; use Hyperf\Task\TaskExecutor; use Hyperf\Task\Task; use App\TaskWorker\SSDBTask; +use App\Commons\Log; /** * @AutoController() @@ -28,14 +29,21 @@ class TestController extends AbstractController // $exec = $container->get(TaskExecutor::class); // $result = $exec->execute(new Task([MethodTask::class, 'handle'], [Coroutine::id()])); - $client = ApplicationContext::getContainer()->get(SSDBTask::class); - $result = $client->exec("set","bar","1234"); - $result = $client->exec("get","bar"); + // $client = ApplicationContext::getContainer()->get(SSDBTask::class); + // $result = $client->exec("set","bar","1234"); + // $result = $client->exec("get","bar"); // $client = ApplicationContext::getContainer()->get(MethodTask::class); // $result = $client->handle("set"); - $this->name = 'index1 action '. $result; + + //$log = ApplicationContext::getContainer()->get(Log::class); + $log = $this->log; + + $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); + $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + + //$this->name = 'index1 action '. $result; return $this->name; } diff --git a/composer.json b/composer.json index c9a89d0..3a10139 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "hyperf/config": "~2.0.0", "hyperf/db-connection": "~2.0.0", "hyperf/framework": "~2.0.0", - "hyperf/guzzle": "~2.0.0", + "hyperf/guzzle": "^2.0", "hyperf/http-server": "~2.0.0", "hyperf/logger": "~2.0.0", "hyperf/memory": "~2.0.0", @@ -31,7 +31,6 @@ "hyperf/paginator": "^2.0", "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", - "hyperf/validation": "^2.0", "hyperf/task": "^2.0" }, "require-dev": { diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index e8f6126..80f707b 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -13,4 +13,5 @@ return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, + \App\Commons\Log::class => \App\Commons\Log::class, ]; From 22cd1ea6550e6d87c4a675a9d9c192579eae50ab Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 18:20:28 +0800 Subject: [PATCH 13/72] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E6=9C=BA=E8=B7=AF=E7=94=B1=E5=92=8Ccontroller?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/AbstractController.php | 7 ++++ app/Controller/DeviceController.php | 41 +++++++++++++++++++ app/Model/SpeakerDevic.php | 11 +++++ app/Service/DeviceServiceImp.php | 0 app/Service/DeviceServiceInterFace.php | 12 ++++++ app/TaskWorker/PubRequest.php | 56 -------------------------- config/routes.php | 8 +++- 7 files changed, 78 insertions(+), 57 deletions(-) create mode 100644 app/Controller/DeviceController.php create mode 100644 app/Model/SpeakerDevic.php create mode 100644 app/Service/DeviceServiceImp.php create mode 100644 app/Service/DeviceServiceInterFace.php delete mode 100644 app/TaskWorker/PubRequest.php diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index b7429ea..2fc26a0 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -43,4 +43,11 @@ abstract class AbstractController * @var ResponseInterface */ protected $response; + + /** + * @Inject() + * @var ValidatorFactoryInterface + */ + protected $validationFactory; + } diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php new file mode 100644 index 0000000..270ac69 --- /dev/null +++ b/app/Controller/DeviceController.php @@ -0,0 +1,41 @@ +validationFactory->make( + $request->all(), + [ + 'store_id' => 'required|nonempty|integer', + ], + [ + 'store_id.required' => '参数不正确', + 'store_id.nonempty' => '参数不正确', + 'store_id.integer' => '参数不正确', + + ] + ); + + if ($validator->fails()){ + // Handle exception + $errorMessage = $validator->errors()->first(); + $this->result(200,[],$errorMessage); + } + + + + + } + + public function list() + { + + } +} \ No newline at end of file diff --git a/app/Model/SpeakerDevic.php b/app/Model/SpeakerDevic.php new file mode 100644 index 0000000..4512111 --- /dev/null +++ b/app/Model/SpeakerDevic.php @@ -0,0 +1,11 @@ +setMethod("POST"); - } - - private $topicFullName; - - private $qos; - - private $messageContent; - - private $productKey; - - public function getTopicFullName() { - return $this->topicFullName; - } - - public function setTopicFullName($topicFullName) { - $this->topicFullName = $topicFullName; - $this->queryParameters["TopicFullName"]=$topicFullName; - } - - public function getQos() { - return $this->qos; - } - - public function setQos($qos) { - $this->qos = $qos; - $this->queryParameters["Qos"]=$qos; - } - - public function getMessageContent() { - return $this->messageContent; - } - - public function setMessageContent($messageContent) { - $this->messageContent = $messageContent; - $this->queryParameters["MessageContent"]=$messageContent; - } - - public function getProductKey() { - return $this->productKey; - } - - public function setProductKey($productKey) { - $this->productKey = $productKey; - $this->queryParameters["ProductKey"]=$productKey; - } - -} \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index fd08a30..0eebd7e 100644 --- a/config/routes.php +++ b/config/routes.php @@ -23,10 +23,16 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/isPersonnel', 'App\Controller\ServiceEvaluateController@isPersonnel'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); - Router::get('test/index1', 'App\Controller\TestController@index1'); Router::post('Attachment/uploadImage', 'App\Controller\AttachmentController@uploadImage'); Router::post('Attachment/uploadImageByBase64', 'App\Controller\AttachmentController@uploadImageByBase64'); Router::post('Attachment/upload', 'App\Controller\AttachmentController@upload'); Router::post('ParamsToken/generate', 'App\Controller\ParamsTokenController@generate'); Router::post('ParamsToken/analyze', 'App\Controller\ParamsTokenController@analyze'); + + //播报器相关 + Router::post('Device/bind', 'App\Controller\DeviceController@bind'); + Router::post('Device/list', 'App\Controller\DeviceController@list'); + + //测试路由 + Router::get('test/index1', 'App\Controller\TestController@index1'); }); \ No newline at end of file From 5d6a9aec0f89ac349ca545a95255c8b1d9eed661 Mon Sep 17 00:00:00 2001 From: Mike Date: Sun, 2 Aug 2020 19:06:21 +0800 Subject: [PATCH 14/72] =?UTF-8?q?=E5=AE=8C=E6=88=90amqp=E5=AF=B9=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 34 ++++++++++++++++++++++++ composer.json | 3 ++- config/autoload/amqp.php | 33 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 app/Amqp/Consumer/DevicOrderConsumer.php create mode 100644 config/autoload/amqp.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php new file mode 100644 index 0000000..ea4cc7d --- /dev/null +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -0,0 +1,34 @@ +getBody()); + if($this->msgCount< 10){ + $this->msgCount += 1; + return Result::REQUEUE; + } + return Result::ACK; + } + + public function isEnable(): bool + { + //if(env('APP_ENV')!='prod') return false; + return parent::isEnable(); + } +} diff --git a/composer.json b/composer.json index f15665e..e089108 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ "hyperf/filesystem": "^2.0", "xxtime/flysystem-aliyun-oss": "^1.5", "hyperf/task": "^2.0", - "alibabacloud/iot": "^1.8" + "alibabacloud/iot": "^1.8", + "hyperf/amqp": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/amqp.php b/config/autoload/amqp.php new file mode 100644 index 0000000..e14780a --- /dev/null +++ b/config/autoload/amqp.php @@ -0,0 +1,33 @@ + [ + 'host' => env('RQM_HOST', 'localhost'), + 'port' => 5672, + 'user' => env('RQM_USER','guest'), + 'password' => env('RQM_PASSWORD','guest'), + 'vhost' => '/', + 'concurrent' => [ + 'limit' => 1, + ], + 'pool' => [ + 'min_connections' => 1, + 'max_connections' => 10, + 'connect_timeout' => 10.0, + 'wait_timeout' => 3.0, + 'heartbeat' => -1, + ], + 'params' => [ + 'insist' => false, + 'login_method' => 'AMQPLAIN', + 'login_response' => null, + 'locale' => 'en_US', + 'connection_timeout' => 3.0, + 'read_write_timeout' => 6.0, + 'context' => null, + 'keepalive' => false, + 'heartbeat' => 3, + 'close_on_destruct' => false, + ], + ] +]; From f8f90aa0bf6f8cf9e96b517fd98e91d7242cb4a3 Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 3 Aug 2020 16:04:21 +0800 Subject: [PATCH 15/72] =?UTF-8?q?=E7=BB=91=E5=AE=9A=E5=92=8Cservice?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/AbstractController.php | 3 ++- app/Controller/DeviceController.php | 26 +++++++++++++++++++---- app/Service/DeviceServiceImp.php | 29 ++++++++++++++++++++++++++ app/Service/DeviceServiceInterFace.php | 2 -- config/autoload/dependencies.php | 1 + 5 files changed, 54 insertions(+), 7 deletions(-) diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index 2fc26a0..30df791 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -15,6 +15,7 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Container\ContainerInterface; +use Hyperf\Validation\Contract\ValidatorFactoryInterface; use App\Commons\Log; abstract class AbstractController @@ -45,7 +46,7 @@ abstract class AbstractController protected $response; /** - * @Inject() + * @Inject * @var ValidatorFactoryInterface */ protected $validationFactory; diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php index 270ac69..438a651 100644 --- a/app/Controller/DeviceController.php +++ b/app/Controller/DeviceController.php @@ -5,21 +5,34 @@ namespace App\Controller; use Hyperf\Di\Annotation\Inject; use App\Constants\ErrorCode; use App\Exception\BusinessException; +use App\Service\DeviceServiceInterFace; class DeviceController extends BaseController { + + /** + * @Inject + * @var DeviceServiceInterFace + */ + protected $deviceService; + + public function bind() { $validator = $this->validationFactory->make( - $request->all(), + $this->request->all(), [ 'store_id' => 'required|nonempty|integer', + 'device_name' => 'required|nonempty|alpha_num', + ], [ 'store_id.required' => '参数不正确', 'store_id.nonempty' => '参数不正确', 'store_id.integer' => '参数不正确', - + 'device_name.required' => '参数不正确', + 'device_name.nonempty' => '参数不正确', + 'device_name.alpha_num' => '参数不正确', ] ); @@ -29,9 +42,14 @@ class DeviceController extends BaseController $this->result(200,[],$errorMessage); } - - + $store_id = $this->request->input('store_id'); + $device_name = $this->request->input('device_name'); + + $sd = $this->deviceService->bindByStoreId($device_name,$store_id); + + return $this->result(0,[$sd],'绑定成功'); + } public function list() diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index e69de29..b022683 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -0,0 +1,29 @@ +store_id = $store_id; + $sd->device_name = $dev_name; + $sd->market_id = 1; + $sd->bind_time = time(); + $sd->saveOrFail(); + }catch(Exception $e){ + //var_dump($e); + } + return $sd; + } + public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg){ + + } +} \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index 388583f..e22e184 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -1,9 +1,7 @@ \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, + \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, ]; From 2b3adc7245e65ea79fc0ff3714ccc4bed2e1c3a5 Mon Sep 17 00:00:00 2001 From: weigang Date: Tue, 4 Aug 2020 19:59:56 +0800 Subject: [PATCH 16/72] =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=B5=81=E7=A8=8B=E8=B5=B0=E5=AE=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 37 ++++++++-- app/Constants/LogLabel.php | 24 +++++++ app/Controller/DeviceController.php | 73 ++++++++++++++++--- app/Model/Order.php | 10 +++ app/Model/OrderMain.php | 10 +++ app/Model/Store.php | 9 +++ app/Service/DeviceServiceImp.php | 88 ++++++++++++++++++++--- app/Service/DeviceServiceInterFace.php | 3 +- app/Service/IOTAliService.php | 54 ++++++++++++++ app/Service/IOTServiceInterface.php | 8 +++ app/TaskWorker/AliIotTask.php | 89 ++++++++---------------- config/autoload/dependencies.php | 1 + config/routes.php | 1 + 13 files changed, 323 insertions(+), 84 deletions(-) create mode 100644 app/Constants/LogLabel.php create mode 100644 app/Model/Order.php create mode 100644 app/Model/OrderMain.php create mode 100644 app/Model/Store.php create mode 100644 app/Service/IOTAliService.php create mode 100644 app/Service/IOTServiceInterface.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index ea4cc7d..773f0dd 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -4,26 +4,51 @@ declare(strict_types=1); namespace App\Amqp\Consumer; +use App\Model\Order; +use App\Model\SpeakerDevic; +use App\Service\DeviceServiceInterFace; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; +use Hyperf\DbConnection\Db; use PhpAmqpLib\Message\AMQPMessage; +use Hyperf\Di\Annotation\Inject; /** * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=1) */ class DevicOrderConsumer extends ConsumerMessage { - private $msgCount = 0; + /** + * @Inject + * @var DeviceServiceInterFace + */ + protected $deviceService; + public function consumeMessage($data, AMQPMessage $message): string { - var_dump($data); - var_dump($message->getBody()); - if($this->msgCount< 10){ - $this->msgCount += 1; + try { + + $orderMainId = $message->getBody(); + $order = Order::query() + ->select(['id', 'store_id', 'money']) + ->where(['order_main_id' => $orderMainId, 'type' => 4, 'dm_state' => 2]) + ->first(); + + $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); + + if ($res == true) { + return Result::ACK; + } else { + return Result::REQUEUE; + } + + } catch (\Exception $e) { return Result::REQUEUE; } - return Result::ACK; } public function isEnable(): bool diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php new file mode 100644 index 0000000..b3cadb4 --- /dev/null +++ b/app/Constants/LogLabel.php @@ -0,0 +1,24 @@ + 'required|nonempty|integer', 'device_name' => 'required|nonempty|alpha_num', - ], [ 'store_id.required' => '参数不正确', @@ -36,24 +35,80 @@ class DeviceController extends BaseController ] ); - if ($validator->fails()){ + if ($validator->fails()) { // Handle exception - $errorMessage = $validator->errors()->first(); - $this->result(200,[],$errorMessage); + throw new ValidationException($validator); + return; } - $store_id = $this->request->input('store_id'); $device_name = $this->request->input('device_name'); - $sd = $this->deviceService->bindByStoreId($device_name,$store_id); + $sd = $this->deviceService->bindByStoreId($device_name, $store_id); - return $this->result(0,[$sd],'绑定成功'); + if (is_null($sd)) { + return $this->result(100, '', '绑定失败: 设备号已经被绑定或不存在'); + } + + return $this->success($sd, '绑定成功'); } public function list() { - + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'store_id' => 'required|nonempty|integer', + ], + [ + 'store_id.required' => '参数不正确', + 'store_id.nonempty' => '参数不正确', + 'store_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $store_id = $this->request->input('store_id'); + + $devices = $this->deviceService->getListByStoreId($store_id); + + return $this->success($devices); + } + + public function unbind() + { + $validator = $this->validationFactory->make( + $this->request->all(), + [ + 'bind_id' => 'required|nonempty|integer', + ], + [ + 'bind_id.required' => '参数不正确', + 'bind_id.nonempty' => '参数不正确', + 'bind_id.integer' => '参数不正确', + ] + ); + + if ($validator->fails()) { + // Handle exception + throw new ValidationException($validator); + return; + } + + $bind_id = $this->request->input('bind_id'); + + $unbind_num = $this->deviceService->unbindById($bind_id); + + if ($unbind_num == 0) { + return $this->result(100, '', '解绑失败: 设备已经解绑或不存在'); + } + + return $this->success(['unbind' => $unbind_num]); } } \ No newline at end of file diff --git a/app/Model/Order.php b/app/Model/Order.php new file mode 100644 index 0000000..0a5bdd4 --- /dev/null +++ b/app/Model/Order.php @@ -0,0 +1,10 @@ +where(['store_id' => $store_id])->get(); } - public function bindByStoreId($dev_name,$store_id){ + + /** + * 绑定 + * @param $dev_name + * @param $store_id + * @return SpeakerDevic|null + * @throws \Throwable + */ + public function bindByStoreId($dev_name, $store_id) + { $sd = null; - try{ - $sd = new SpeakerDevic; + + if ($this->checkDeviceEnable($dev_name)) { + return $sd; + } + + try { + + // 获取市场ID + $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); + + $sd = new SpeakerDevic; $sd->store_id = $store_id; $sd->device_name = $dev_name; - $sd->market_id = 1; + $sd->market_id = $market_id; $sd->bind_time = time(); $sd->saveOrFail(); - }catch(Exception $e){ - //var_dump($e); + } catch (Exception $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]); } return $sd; } - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg){ + /** + * 解绑 + * @param $bind_id + * @return int + */ + public function unbindById($bind_id) + { + return SpeakerDevic::destroy($bind_id); + } + + /** + * 发布语音消息 + * @param $store_id + * @param $msg + */ + public function pubMsgToStoreByDevName($dev_name, $msg) + { + return $this->IOTService->pub($dev_name, $msg); } + + /** + * 当前设备是否已经被绑定 + * @param $dev_name + * @return bool + */ + protected function checkDeviceEnable($dev_name) + { + return SpeakerDevic::query()->where(['device_name' => $dev_name])->exists(); + } + } \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index e22e184..2bb9cb0 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -6,5 +6,6 @@ interface DeviceServiceInterFace { public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); - public function pubMsgByStoreIdAndDevName($dev_name,$store_id,$msg); + public function unbindById($bind_id); + public function pubMsgToStoreByDevName($dev_name,$msg); } \ No newline at end of file diff --git a/app/Service/IOTAliService.php b/app/Service/IOTAliService.php new file mode 100644 index 0000000..6b8a854 --- /dev/null +++ b/app/Service/IOTAliService.php @@ -0,0 +1,54 @@ +regionId(env('ALI_IOT_REGION')) + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host(env('ALI_IOT_HOST')) + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'), + ], + ]) + ->request(); + } catch (ClientException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ClientException发布失败:'.$e->getErrorMessage()]); + return false; + } catch (ServerException $e) { + $this->log->event(LogLabel::DEVICE_LOG, ['msg' => 'ServerException发布失败:'.$e->getErrorMessage()]); + return false; + } + + return true; + } + +} \ No newline at end of file diff --git a/app/Service/IOTServiceInterface.php b/app/Service/IOTServiceInterface.php new file mode 100644 index 0000000..931aca6 --- /dev/null +++ b/app/Service/IOTServiceInterface.php @@ -0,0 +1,8 @@ +regionId('cn-shanghai') - ->asDefaultClient(); - $result2 = ''; - - $msg = "{\"msg\":\"收款123元\"}"; - try{ - AlibabaCloud::rpc() - ->product('Iot') - // ->scheme('https') // https | http - ->version('2018-01-20') - ->action('Pub') - ->method('POST') - ->host('iot.cn-shanghai.aliyuncs.com') - ->options([ - 'query' => [ - 'RegionId' => "cn-shanghai", - 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", - 'MessageContent' => base64_encode($msg), - 'ProductKey' => "a1ZSurIJmO0", - ], - ]) - ->request(); - //var_dump($result2->toArray()); + ->regionId('cn-shanghai') + ->asDefaultClient(); + + try { + AlibabaCloud::rpc() + ->product('Iot') + ->version('2018-01-20') + ->action('Pub') + ->method('POST') + ->host('iot.cn-shanghai.aliyuncs.com') + ->options([ + 'query' => [ + 'RegionId' => "cn-shanghai", + 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'MessageContent' => base64_encode($msg), + 'ProductKey' => "a1ZSurIJmO0", + ], + ]) + ->request(); } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; } - //print_r($response); - return ""; + return true; } -// protected function getClient(){ -// AlibabaCloud::accessKeyClient('LTAI4GJEWrN6dVh7HmPKHMyF', 'wMae4ckfVGwMQPVw5ZlVDDpihVeUap') -// ->regionId('cn-shanghai') -// ->asDefaultClient(); -// $result = ''; - -// $msg = "{\"msg\":\"收款123元\"}"; -// try{ -// $result = AlibabaCloud::rpc() -// ->product('Iot') -// // ->scheme('https') // https | http -// ->version('2018-01-20') -// ->action('Pub') -// ->method('POST') -// ->host('iot.cn-shanghai.aliyuncs.com') -// ->options([ -// 'query' => [ -// 'RegionId' => "cn-shanghai", -// 'TopicFullName' => "/a1ZSurIJmO0/BOX0000000000003/user/get", -// 'MessageContent' => base64_encode($msg), -// 'ProductKey' => "a1ZSurIJmO0", -// ], -// ]) -// ->request(); -// var_dump($result->toArray()); -// } catch (ClientException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } catch (ServerException $e) { -// echo $e->getErrorMessage() . PHP_EOL; -// } -// return $result; - -// } } diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 4b46ec8..c147e40 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -15,4 +15,5 @@ return [ \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, + \App\Service\IOTServiceInterface::class => \App\Service\IOTAliService::class, ]; diff --git a/config/routes.php b/config/routes.php index 0eebd7e..a067b45 100644 --- a/config/routes.php +++ b/config/routes.php @@ -32,6 +32,7 @@ Router::addGroup('/v1/',function (){ //播报器相关 Router::post('Device/bind', 'App\Controller\DeviceController@bind'); Router::post('Device/list', 'App\Controller\DeviceController@list'); + Router::post('Device/unbind', 'App\Controller\DeviceController@unbind'); //测试路由 Router::get('test/index1', 'App\Controller\TestController@index1'); From ba181d6fb3ace7661932c20f370c0c16eb036fa0 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 09:11:04 +0800 Subject: [PATCH 17/72] =?UTF-8?q?=E8=AF=AD=E9=9F=B3=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=B8=8D=E5=AD=98=E5=9C=A8=E6=88=96=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=8F=B7=E4=B8=8D=E5=AD=98=E5=9C=A8=E6=89=93=E5=9B=9E?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 773f0dd..2bf258a 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -35,8 +35,16 @@ class DevicOrderConsumer extends ConsumerMessage ->where(['order_main_id' => $orderMainId, 'type' => 4, 'dm_state' => 2]) ->first(); + if (is_null($order)||!$order) { + return Result::REQUEUE; + } + $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + if (is_null($deviceName)||!$deviceName) { + return Result::REQUEUE; + } + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); From cae320969fe8ea51b70c85539909336755c39087 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:25:31 +0800 Subject: [PATCH 18/72] =?UTF-8?q?=E6=96=B0=E5=A2=9EIS=5FBIND=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E7=9B=B8=E5=85=B3=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 14 +++++++---- app/Model/SpeakerDevic.php | 5 ++++ app/Service/DeviceServiceImp.php | 32 ++++++++++++++++-------- app/Service/DeviceServiceInterFace.php | 2 +- app/Service/IOTAliService.php | 2 +- 5 files changed, 37 insertions(+), 18 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 2bf258a..8ba1935 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -15,7 +15,7 @@ use PhpAmqpLib\Message\AMQPMessage; use Hyperf\Di\Annotation\Inject; /** - * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=1) + * @Consumer(exchange="devicOrder", routingKey="devicOrder", queue="devicOrder", nums=4) */ class DevicOrderConsumer extends ConsumerMessage { @@ -39,14 +39,18 @@ class DevicOrderConsumer extends ConsumerMessage return Result::REQUEUE; } - $deviceName = SpeakerDevic::query()->where(['store_id' => $order['store_id']])->value('device_name'); + $deviceNames = SpeakerDevic::query() + ->select(['device_name']) + ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) + ->get() + ->toArray(); - if (is_null($deviceName)||!$deviceName) { + if (empty($deviceNames)||!$deviceNames) { return Result::REQUEUE; } $msg = "{\"msg\":\"到账".$order['money']."元\"}"; - $res = $this->deviceService->pubMsgToStoreByDevName($deviceName, $msg); + $res = $this->deviceService->pubMsgToStoreByDevName($deviceNames, $msg); if ($res == true) { return Result::ACK; @@ -61,7 +65,7 @@ class DevicOrderConsumer extends ConsumerMessage public function isEnable(): bool { - //if(env('APP_ENV')!='prod') return false; + // if(env('APP_ENV')!='prod') return false; return parent::isEnable(); } } diff --git a/app/Model/SpeakerDevic.php b/app/Model/SpeakerDevic.php index 4512111..4c4816e 100644 --- a/app/Model/SpeakerDevic.php +++ b/app/Model/SpeakerDevic.php @@ -6,6 +6,11 @@ use App\Model\Model; class SpeakerDevic extends Model { + const IS_BIND_YES = 1; + const IS_BIND_NO = 0; + protected $table = 'lanzu_service_speakers'; + protected $fillable = ['store_id', 'device_name', 'state', 'market_id', 'bind_time', 'is_bind']; + } \ No newline at end of file diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 3d27426..61744c2 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -31,7 +31,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ public function getListByStoreId($store_id) { - return SpeakerDevic::query()->where(['store_id' => $store_id])->get(); + return SpeakerDevic::query()->where(['store_id' => $store_id, 'is_bind' => SpeakerDevic::IS_BIND_YES])->get()->toArray(); } /** @@ -54,12 +54,18 @@ class DeviceServiceImp implements DeviceServiceInterFace // 获取市场ID $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); - $sd = new SpeakerDevic; - $sd->store_id = $store_id; - $sd->device_name = $dev_name; - $sd->market_id = $market_id; - $sd->bind_time = time(); - $sd->saveOrFail(); + // $sd = new SpeakerDevic; + // $sd->store_id = $store_id; + // $sd->device_name = $dev_name; + // $sd->market_id = $market_id; + // $sd->bind_time = time(); + // $sd->saveOrFail(); + + $sd = SpeakerDevic::query()->updateOrCreate( + ['store_id' => $store_id, 'device_name' => $dev_name], + ['market_id' => $market_id, 'bind_time' => time(), 'is_bind' => SpeakerDevic::IS_BIND_YES] + ); + } catch (Exception $e) { $this->log->event(LogLabel::DEVICE_LOG, ['msg' => '绑定设备异常:'.$e->getMessage()]); } @@ -73,7 +79,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ public function unbindById($bind_id) { - return SpeakerDevic::destroy($bind_id); + return SpeakerDevic::query()->where(['id' => $bind_id])->update(['is_bind' => SpeakerDevic::IS_BIND_NO]); } /** @@ -81,9 +87,13 @@ class DeviceServiceImp implements DeviceServiceInterFace * @param $store_id * @param $msg */ - public function pubMsgToStoreByDevName($dev_name, $msg) + public function pubMsgToStoreByDevName($dev_names, $msg) { - return $this->IOTService->pub($dev_name, $msg); + foreach ($dev_names as $key => $dev_name) { + $this->IOTService->pub($dev_name, $msg); + } + + return true; } /** @@ -93,7 +103,7 @@ class DeviceServiceImp implements DeviceServiceInterFace */ protected function checkDeviceEnable($dev_name) { - return SpeakerDevic::query()->where(['device_name' => $dev_name])->exists(); + return SpeakerDevic::query()->where(['device_name' => $dev_name, 'is_bind' => SpeakerDevic::IS_BIND_YES])->exists(); } } \ No newline at end of file diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterFace.php index 2bb9cb0..15aa23b 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterFace.php @@ -7,5 +7,5 @@ interface DeviceServiceInterFace public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); public function unbindById($bind_id); - public function pubMsgToStoreByDevName($dev_name,$msg); + public function pubMsgToStoreByDevName($dev_names,$msg); } \ No newline at end of file diff --git a/app/Service/IOTAliService.php b/app/Service/IOTAliService.php index 6b8a854..88c4d4c 100644 --- a/app/Service/IOTAliService.php +++ b/app/Service/IOTAliService.php @@ -34,7 +34,7 @@ class IOTAliService implements IOTServiceInterface ->options([ 'query' => [ 'RegionId' => "cn-shanghai", - 'TopicFullName' => "/a1ZSurIJmO0/".$device_name."/user/get", + 'TopicFullName' => "/".env('ALI_IOT_PRODUCT_KEY')."/".$device_name."/user/get", 'MessageContent' => base64_encode($msg), 'ProductKey' => env('ALI_IOT_PRODUCT_KEY'), ], From b81edf8cd558ffca3ba77beba446c1d19ed8873f Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:32:03 +0800 Subject: [PATCH 19/72] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=88=96=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E5=8F=B7=E5=BC=82=E5=B8=B8=E7=9B=B4=E6=8E=A5ACK?= =?UTF-8?q?=E5=BA=94=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index 8ba1935..d0aa997 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -36,7 +36,7 @@ class DevicOrderConsumer extends ConsumerMessage ->first(); if (is_null($order)||!$order) { - return Result::REQUEUE; + return Result::ACK; } $deviceNames = SpeakerDevic::query() @@ -46,7 +46,7 @@ class DevicOrderConsumer extends ConsumerMessage ->toArray(); if (empty($deviceNames)||!$deviceNames) { - return Result::REQUEUE; + return Result::ACK; } $msg = "{\"msg\":\"到账".$order['money']."元\"}"; From c46c142f6472e0b191975198d59694e9aaa0c768 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 5 Aug 2020 11:40:41 +0800 Subject: [PATCH 20/72] =?UTF-8?q?=E5=BE=AA=E7=8E=AF=E6=92=AD=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/DeviceServiceImp.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 61744c2..2b4962c 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -90,7 +90,7 @@ class DeviceServiceImp implements DeviceServiceInterFace public function pubMsgToStoreByDevName($dev_names, $msg) { foreach ($dev_names as $key => $dev_name) { - $this->IOTService->pub($dev_name, $msg); + $this->IOTService->pub($dev_name['device_name'], $msg); } return true; From 8e01b4e319c735794df2ee743fb9538192cf9e9f Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 10 Aug 2020 21:01:20 +0800 Subject: [PATCH 21/72] =?UTF-8?q?=E4=BF=AE=E6=94=B9log=20host=E5=9C=B0?= =?UTF-8?q?=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Commons/Log.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Commons/Log.php b/app/Commons/Log.php index bf5fb24..29a4e84 100644 --- a/app/Commons/Log.php +++ b/app/Commons/Log.php @@ -61,7 +61,7 @@ class Log ] ]; $client->post( - 'http://39.96.12.39:3100/loki/api/v1/push', + env('LOG_HOST','http://39.96.12.39:3100').'/loki/api/v1/push', [ 'headers'=>[ 'Content-Type'=>'application/json' From 5ef2076b7402b8d64d3cb7c5d422bef43422aa43 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 11:49:24 +0800 Subject: [PATCH 22/72] =?UTF-8?q?=E5=A4=96=E5=8D=96=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 10 + app/Controller/OrderController.php | 23 + app/Controller/PaymentController.php | 10 + app/Libs/MQTTClient.php | 1098 ++++++++++++++++++++++++ app/Middleware/Auth/ApiMiddleware.php | 2 +- app/Model/Coupon.php | 3 + app/Model/CouponUserRec.php | 10 + app/Model/CouponUserUse.php | 10 + app/Model/Goods.php | 12 + app/Model/Order.php | 11 + app/Model/OrderGoods.php | 8 + app/Model/OrderMain.php | 81 ++ app/Model/SpecCombination.php | 17 + app/Request/OrderOnlineRequest.php | 72 ++ app/Service/CoupnoServiceInterface.php | 20 + app/Service/CouponService.php | 85 ++ app/Service/OrderService.php | 423 +++++++++ app/Service/OrderServiceInterface.php | 29 + app/TaskWorker/MQTTClientTask.php | 27 + composer.json | 5 +- config/autoload/dependencies.php | 4 +- config/autoload/server.php | 3 - config/autoload/snowflake.php | 24 + config/routes.php | 1 + 24 files changed, 1982 insertions(+), 6 deletions(-) create mode 100644 app/Controller/NotifyController.php create mode 100644 app/Controller/OrderController.php create mode 100644 app/Controller/PaymentController.php create mode 100644 app/Libs/MQTTClient.php create mode 100644 app/Model/CouponUserRec.php create mode 100644 app/Model/CouponUserUse.php create mode 100644 app/Model/Goods.php create mode 100644 app/Model/Order.php create mode 100644 app/Model/OrderGoods.php create mode 100644 app/Model/OrderMain.php create mode 100644 app/Model/SpecCombination.php create mode 100644 app/Request/OrderOnlineRequest.php create mode 100644 app/Service/CoupnoServiceInterface.php create mode 100644 app/Service/CouponService.php create mode 100644 app/Service/OrderService.php create mode 100644 app/Service/OrderServiceInterface.php create mode 100644 app/TaskWorker/MQTTClientTask.php create mode 100644 config/autoload/snowflake.php diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php new file mode 100644 index 0000000..8aa0ba0 --- /dev/null +++ b/app/Controller/NotifyController.php @@ -0,0 +1,10 @@ +orderService->addOnlineOrder($request->validated()); + return $this->success(['order_main_id' => $orderMainId]); + } +} \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php new file mode 100644 index 0000000..86ce06c --- /dev/null +++ b/app/Controller/PaymentController.php @@ -0,0 +1,10 @@ +setConnection($address, $port, $protocol)) { + ; + } + $this->packetId = rand(1,100)*100; // Reduce risk of creating duplicate ids in sequential sessions + } + + /** + * Class destructor - Close socket + */ + function __destruct(){ + $this->close(); + } + + /** + * Setup conection parameters + * + * @param string $address + * @param string $port + * @param string $protocol + * @return boolean If return false then using default parameters where validation failed + */ + function setConnection($address, $port=null, $protocol='tcp'){ + $this->serverAddress = $address; + $this->serverPort = $port; + + // Validate protocol + $protocol = strtolower($protocol); + if (($protocol != 'tcp') && !self::isEncryptionProtocol($protocol)) { + $this->debugMessage('Invalid protocol ('.$protocol.'). Setting to default (tcp).'); + $this->protocol = 'tcp'; + return false; + } + $this->protocol = $protocol; + + return true; + } + + /** + * Build url for connecting to stream + * + * @return string + */ + private function getUrl() { + $url = ''; + if ($this->protocol) $url .= $this->protocol .'://'; + $url .= $this->serverAddress; + if ($this->serverPort) $url .= ':'. $this->serverPort; + return $url; + } + + /** + * Check if encryption protocol is supported + * + * @param string $protcol + * @return boolean + */ + private static function isEncryptionProtocol($protocol) { + return in_array(strtolower($protocol), ['ssl', 'tls', 'tlsv1.0', 'tlsv1.1', 'tlsv1.2', 'sslv3']); + } + + /** + * Sets server certificate and protocol for ssl/tls encryption + * + * @param string $caFile CA file to identify server + * @param string $protocl Crypto protocol (See http://php.net/manual/en/migration56.openssl.php) + * @return boolean False if settings failed, else true + */ + public function setEncryption($caFile, $protocol = null) { + if (file_exists($caFile)) { + $this->caFile = $caFile; + } else { + $this->debugMessage('CA file not found'); + return false; + } + if(self::isEncryptionProtocol($protocol)) { + $this->protocol = $protocol; + } else if (!is_null($protocol)) { + $this->debugMessage('Unknown encryption protocol'); + return false; + } + return true; + } + + /** + * Sets client crt and key files for client-side authentication + * + * @param string $crtFile Client certificate file + * @param string $keyFile Client key file + * @return boolean False if settings failed, else true + */ + public function setClientEncryption($certificateFile, $keyFile) { + if (!file_exists($certificateFile)) { + $this->debugMessage('Client certificate file not found'); + return false; + } + if (!file_exists($keyFile)) { + $this->debugMessage('Client key file not found'); + return false; + } + $this->localCert= $certificateFile; + $this->localPrivateKey = $keyFile; + return true; + } + + /** + * Set authentication details to be used when connecting + * + * @param string $username Username + * @param string $password Password + */ + public function setAuthentication($username, $password) { + $this->connectUsername= $username; + $this->connectPassword = $password; + } + + /** + * Set will (last message defined by MQTT) to send when connection is lost + * + * @param string $topic + * @param string $message + * @param integer $qos + * @param boolean $retain + */ + public function setWill($topic, $message, $qos=1, $retain=false) { + $this->connectWill = true; + $this->connectWillQos = $qos; + $this->connectWillRetain = $retain; + $this->willTopic = $topic; + $this->willMessage = $message; + } + + /** + * Connect to MQTT server + * + * @param string $clientId Unique id used by the server to identify the client + * @param boolean $cleanSession Set true to clear session on server, ie queued messages are purged (not recieved) + * @param integer $keepAlive Number of seconds a connection is considered to be alive without traffic + * @param integer $timeout Number of millliseconds before timeout when reading from socket + * @return boolean Returns false if connection failed + */ + public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { + if (!$this->serverAddress) return false; + + // Basic validation of clientid + // Note: A MQTT server may accept other chars and more than 23 chars in the clientid but that is optional, + // all chars below up to 23 chars are required to be accepted (see section "3.1.3.1 Client Identifier" of the standard) + if(preg_match("/[^0-9a-zA-Z]/",$clientId)) { + $this->debugMessage('ClientId can only contain characters 0-9,a-z,A-Z'); + return false; + } + if(strlen($clientId) > 23) { + $this->debugMessage('ClientId max length is 23 characters/numbers'); + return false; + } + $this->clientId = $clientId; + + $this->connectCleanSession = $cleanSession; + $this->connectKeepAlive = $keepAlive; + $this->socketTimeout = $timeout; + + // Setup certificates if encryption protocol selected + if ($this->isEncryptionProtocol($this->protocol)) { + $mozillaCiphers = implode(':', array( + 'ECDHE-RSA-AES128-GCM-SHA256', + 'ECDHE-ECDSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES256-GCM-SHA384', + 'ECDHE-ECDSA-AES256-GCM-SHA384', + 'DHE-RSA-AES128-GCM-SHA256', + 'DHE-DSS-AES128-GCM-SHA256', + 'kEDH+AESGCM', + 'ECDHE-RSA-AES128-SHA256', + 'ECDHE-ECDSA-AES128-SHA256', + 'ECDHE-RSA-AES128-SHA', + 'ECDHE-ECDSA-AES128-SHA', + 'ECDHE-RSA-AES256-SHA384', + 'ECDHE-ECDSA-AES256-SHA384', + 'ECDHE-RSA-AES256-SHA', + 'ECDHE-ECDSA-AES256-SHA', + 'DHE-RSA-AES128-SHA256', + 'DHE-RSA-AES128-SHA', + 'DHE-DSS-AES128-SHA256', + 'DHE-RSA-AES256-SHA256', + 'DHE-DSS-AES256-SHA', + 'DHE-RSA-AES256-SHA', + 'AES128-GCM-SHA256', + 'AES256-GCM-SHA384', + 'ECDHE-RSA-RC4-SHA', + 'ECDHE-ECDSA-RC4-SHA', + 'AES128', + 'AES256', + 'RC4-SHA', + 'HIGH', + '!aNULL', + '!eNULL', + '!EXPORT', + '!DES', + '!3DES', + '!MD5', + '!PSK' + )); + // Secure socket communication with these parameters, a ca-file is required + $options = []; + $options['verify_peer'] = true; + $options['verify_peer_name'] = true; + $options['verify_depth'] = 5; + $options['disable_compression'] = true; + $options['SNI_enabled'] = true; + $options['ciphers'] = $mozillaCiphers; + if($this->caFile) { + $options['cafile'] = $this->caFile; + } + if($this->localCert) { + $options['local_cert'] = $this->localCert; + if ($this->localPrivateKey) { + $options['local_pk'] = $this->localPrivateKey; + } + } + $socketContext = stream_context_create(['ssl' => $options]); + $this->debugMessage('Settings socket options: '. var_export($options, true)); + } else { + $socketContext = null; + } + + // Try to open socket + try { + $this->debugMessage('Opening socket to: '. $this->getUrl()); + if ($socketContext) { + $this->socket = stream_socket_client($this->getUrl(), $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $socketContext); + } else { + $this->socket = stream_socket_client($this->getUrl(), $errno, $errstr, 10, STREAM_CLIENT_CONNECT); + } + } catch (\ErrorException $error) { + $this->debugMessage('Exception: Could not open stream with error message: '. $error->getMessage()); + $this->socket = null; + return false; + } + + // Check if socket was opened successfully + if ($this->socket === false) { + $this->socket = null; + $this->debugMessage('Connection failed. Error-no:'. $errno .' Error message: '. $errstr); + return false; + } + + // Set socket timeout + ini_set('default_socket_timeout', 10); + stream_set_timeout($this->socket, 0, $this->socketTimeout * 1000); + // Set stream to non-blocking mode, ie do not wait to read if stream is empty + stream_set_blocking($this->socket, true); + + // Calculate connect flags to use in CONNECT header + $connectFlags = 0; + if ($this->connectCleanSession) $connectFlags += 0x02; + if ($this->connectWill) { + $connectFlags += 0x04; + if ($this->connectWillQos) $connectFlags += ($this->connectWill << 3); + if ($this->connectWillRetain) $connectFlags += 0x20; + } + if ($this->connectUsername) { + $connectFlags += 0x80; + if ($this->connectPassword) $connectFlags += 0x40; + } + + // Build payload and header for CONNECT-packet + $payload = chr(0x00).chr(0x04); // MSB & LSB length of MQTT = 4 + $payload .= 'MQTT'; + $payload .= chr(0x04); // Protocol level (3.1.1) + $payload .= chr($connectFlags); // Connect flags + $payload .= chr($this->connectKeepAlive >> 8); // Keepalive (MSB) + $payload .= chr($this->connectKeepAlive & 0xff); // Keepalive (LSB) + if ($this->connectCleanSession && empty($this->clientId)) { + $this->clientId = rand(1,999999999); + } + if ($this->clientId) { + $payload .= $this->createPayload($this->clientId); + } + if($this->connectWill){ + $payload .= $this->createPayload($this->willTopic); + $payload .= $this->createPayload($this->willMessage); + } + if($this->connectUsername) { + $payload .= $this->createPayload($this->connectUsername); + } + if ($this->connectPassword) { + $payload .= $this->createPayload($this->connectPassword); + } + $header = $this->createHeader(self::MQTT_CONNECT, $payload); + $this->debugMessage('Sending CONNECT'); + $this->send($header . $payload); + + // Wait for CONNACK packet + $response = $this->waitForPacket(self::MQTT_CONNACK); + if($response !== false && ($response[2] == chr(0))) { + $this->debugMessage('Connected to MQTT'); + $this->lastConnectResult = 0; + return true; + } else { + $this->debugMessage('Connection failed! Error: '. ord($response[2])); + $this->lastConnectResult = ord($response[2]); + $this->close(); + return false; + } + } + + /** + * Publish a topic and message (QoS 0,1,2 supported) + * + * @param string $topic + * @param string $message + * @param byte $qos + * @return boolean + */ + public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { + if(!$this->isConnected()) return false; + + if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->createPayload($topic); + if($qos >= self::MQTT_QOS1) { + // Packet identifier required for QoS level >= 1 + $payload .= $this->getPacketIdPayload(); + } + $payload .= $message; + + $dupFlag = 0; + $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); + $this->debugMessage('Sending PUBLISH'); + $this->send($header . $payload); + + if($qos == self::MQTT_QOS1) { + // If QoS level 1, only a PUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_PUBACK, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBACK'); + return false; + } + } elseif($qos == self::MQTT_QOS2) { + // If QoS level 2, a PUBREC packet is expected + $response = $this->waitForPacket(self::MQTT_PUBREC, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBREC'); + return false; + } + + // Send PUBREL + $response = $this->sendPubRel($packetId); + if($response === false) { + $this->debugMessage('Failed to send PUBREL'); + return false; + } + + // A PUBCOMP packet is expected + $response = $this->waitForPacket(self::MQTT_PUBCOMP, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBCOMP'); + return false; + } + } + + return true; + } + + /** + * Send PUBACK as response to a recieved PUBLISH packet (QoS Level 1) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubAck($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBACK, $payload); + $this->debugMessage('Sending PUBACK'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBREC as response to a recieved PUBLISH packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubRec($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBREC, $payload); + $this->debugMessage('Sending PUBREC'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBREL as response to a recieved PUBREC packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubRel($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBREL, $payload); + $this->debugMessage('Sending PUBREL'); + $this->send($header . $payload); + + return true; + } + + /** + * Send PUBCOMP as response to a recieved PUBREL packet (QoS Level 2) + * + * @param integer $packetId Packet identifier of PUBLISH packet + * @return boolean Returns true if packet sent successfully + */ + public function sendPubComp($packetId) { + if(!$this->isConnected()) return false; + + $payload = chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + $header = $this->createHeader(self::MQTT_PUBCOMP, $payload); + $this->debugMessage('Sending PUBCOMP'); + $this->send($header . $payload); + + return true; + } + + /** + * Subscribe to topics with a quality of service + * + * @param string[] $topics Topics to subscribe for + * @param integer $qos Quality of serivce for all topics + * @return boolean Returns true if SUBACK was recieved + */ + public function sendSubscribe($topics, $qos = self::MQTT_QOS1) { + if (!is_array($topics)) $topics = [$topics]; + if(!$this->isConnected()) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->getPacketIdPayload(); + foreach($topics as $topic) { + $payload .= $this->createPayload($topic); + $payload .= chr($qos); + } + $header = $this->createHeader(self::MQTT_SUBSCRIBE + 0x02, $payload); + $this->debugMessage('Sending SUBSCRIBE'); + $this->send($header . $payload); + + // A SUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_SUBACK, $packetId); + if($response === false) { + $this->debugMessage('Packet missing, expecting SUBACK'); + return false; + } + $responsePayload = substr($response, 3); // skip header and identifier (3 bytes) + if (strlen($responsePayload) != count($topics)) { + $this->debugMessage('Did not recieve SUBACK for all topics'); + return false; + } + + // Check which subscriptions that were approved + $topicsResult = []; + $i = 0; + foreach ($topics as $topic) { + $topicsResult[$topic] = []; + if ($responsePayload[$i] > 0x02) { + $topicsResult[$topic]['success'] = false; + $topicsResult[$topic]['qosGiven'] = null; + } else { + $topicsResult[$topic]['success'] = true; + $topicsResult[$topic]['qosGiven'] = (int) ord($responsePayload[$i]); + } + $i++; + } + + return $topicsResult; + } + + /** + * Send unsubscribe packet for given topics + * + * @param string[] $topics + * @return boolean Returns true if UNSUBACK was recieved + */ + public function sendUnsubscribe($topics) { + if(!$this->isConnected()) return false; + + $packetId = $this->getNextPacketId(); + $payload = $this->getPacketIdPayload(); + foreach($topics as $topic) { + $payload .= $this->createPayload($topic); + } + $header = $this->createHeader(self::MQTT_UNSUBSCRIBE + 0x02, $payload); + $this->debugMessage('Sending UNSUBSCRIBE'); + $this->send($header . $payload); + + // An UNSUBACK packet is expected + $response = $this->waitForPacket(self::MQTT_UNSUBACK, $packetId); + if($response === false) { + $this->debugMessage('Invalid packet received, expecting UNSUBACK'); + return false; + } + return true; + } + + /** + * Sends PINGREQ packet to server + * + * @return boolean Returns true if PINGRESP was recieved + */ + public function sendPing() { + if(!$this->isConnected()) return false; + + $this->timeSincePingReq = time(); + $header = $this->createHeader(self::MQTT_PINGREQ); + $this->debugMessage('Sending PING'); + $this->send($header); + $this->pingReqTime = time(); + + // A PINGRESP packet is expected + $response = $this->waitForPacket(self::MQTT_PINGRESP); + if($response === false) { + $this->debugMessage('Invalid packet received, expecting PINGRESP'); + return false; + } + + return true; + } + + /** + * Send disconnect and close socket + */ + public function sendDisconnect() { + if($this->isConnected()) { + $header = $this->createHeader(self::MQTT_DISCONNECT); + $this->debugMessage('Sending DISCONNECT'); + $this->send($header); + $this->close(); + } + } + + /** + * Close socket + */ + public function close() { + if($this->isConnected()) { + $this->debugMessage('Closing socket'); + stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); + $this->socket = null; + $this->serverAliveTime = null; + } + } + + /** + * Check if connected to stream + * @return boolean + */ + public function isConnected() { + return !empty($this->socket); + } + + /** + * Check if connection is alive + * @return boolean + */ + public function isAlive() { + return $this->isConnected() && ($this->serverAliveTime + $this->connectKeepAlive <= time()); + } + + /** + * Set debug mode, if true then output progress messages + * + * @param boolean $mode + */ + public function setDebug($mode = true) { + $this->debug = $mode; + } + + /** + * Print message to console if debug mode is on + * + * @param string $message + */ + private function debugMessage($message) { + if ($this->debug) { + echo 'MQTT: '. $message .PHP_EOL; + } + } + + /** + * Return next packet identifier to use in MQTT packet + * Max 2 bytes to be used, restart on 0 if end reached + * + * @return integer + */ + private function getNextPacketId() { + return ($this->packetId = ($this->packetId + 1) & 0xffff); + } + + /** + * Return payload of packet id, use latest generated packet id as default + * + * @param integer $packetId + * @return string Two chars with apyload to add in MQTT-message + */ + private function getPacketIdPayload($packetId = null) { + if (empty($packetId)) $packetId = $this->packetId; + return chr(($packetId & 0xff00)>>8) . chr($packetId & 0xff); + } + + /** + * Add payload length as bytes to begining of string and return + * + * @param string $payload + * @return string + */ + private function createPayload($payload) { + $fullLength = strlen($payload); + $retval = chr($fullLength>>8).chr($fullLength&0xff).$payload; + return $retval; + } + + /** + * Decode payload using inital length (2 bytes) and return as string array + * + * @param string $payload + * @return string[] + */ + private function decodePayload($payload) { + $result = []; + while (strlen($payload) >= 2) { + $length = ord($payload[0])<<8 + ord($payload[1]); + if (strlen($payload) <= $length + 2) { + $result[] = substr($payload, 2, $length); + } + $payload = substr($payload, min($length + 2, strlen($payload))); + } + return $result; + } + + /** + * Send data to open socket + * + * @param string $data + * @return boolean Only returns true if all data was sent + */ + private function send($data) { + if ($this->socket) { + $result = fwrite($this->socket, $data); + if (($result !== false) && ($result == strlen($data))) { + $this->serverAliveTime = time(); + return true; + } + } + return false; + } + + /** + * Read bytes from socket until x bytes read, eof reached or socket timeout + * + * @param int $bytes Number of bytes to read + * @return string Return bytes read as a string + */ + private function readBytes($bytes) { + if (!$this->socket) return false; + //if ($bytes == 0) return ''; + $bytesLeft = $bytes; + $result = ''; + do { + // If stream at end, close down socket and exit + if(feof($this->socket)) { + $this->debugMessage('Reached EOF for stream'); + $this->close(); + return $result; + } + // Try to read from stream + $str = fread($this->socket, $bytesLeft); + if ($str !== false && strlen($str) > 0) { + $result .= $str; + $bytesLeft -= strlen($str); + } + if ($bytesLeft <= 0) { + // If all bytes read, then return them + $this->serverAliveTime = time(); + return $result; + } + // Check if timeout + $info = stream_get_meta_data($this->socket); + if ($info['timed_out']) { + $this->debugMessage('Read timeout'); + return false; + } + // Wait a while before trying to read again (in micro seconds) + usleep($this->socketReadDelay * 1000); + } while (true); + } + + /** + * Encode length to bytes to send in stream + * + * @param integer $len + * @return string + */ + private function encodeLength($len) { + if ($len < 0 || $len >= 128*128*128*128) { + // illegal length + return false; + } + $output = ''; + do { + $byte = $len & 0x7f; // keep lowest 7 bits + $len = $len >> 7; // shift away lowest 7 bits + if ($len > 0) { + $byte = $byte | 0x80; // set high bit to indicate continuation + } + $output .= chr($byte); + } while ($len > 0); + return $output; + } + + /** + * Return length of packet by reading from stream + * + * @return integer + */ + private function readPacketLength() { + $bytesRead = 0; + $len = 0; + $multiplier = 1; + do { + if ($bytesRead > 4) { + return false; // Malformed length + } + $str = $this->readBytes(1); + if ($str === false || strlen($str) != 1) { + return false; // Unexpected end of stream + } + $byte = ord($str[0]); + $len += ($byte & 0x7f) * $multiplier; + $isContinued = ($byte & 0x80); + if ($isContinued) { + $multiplier *= 128; + } + $bytesRead++; + } while ($isContinued); + return $len; + } + + /** + * Create MQTT header from command and payload + * + * @param int $command Command to send + * @param string $payload Payload to be sent + * + * @return string Header to send + */ + private function createHeader($command, $payload = '') { + return chr($command) . $this->encodeLength(strlen($payload)); + } + + /** + * Read next packet from stream + * + * @return boolean + */ + private function readNextPacket() { + do { + $header = $this->readBytes(1); + if ($header === false) { + $this->lastReadStatus = self::READ_STATUS_ERROR_HEADER; + return false; + } + } while ((ord($header)&0xf0) == 0); // 0 is illegal control code to start with + + $packetLength = $this->readPacketLength(); + if ($packetLength === false) { + $this->debugMessage('Could not decode packet length'); + $this->lastReadStatus = self::READ_STATUS_ERROR_PACKETLENGTH; + return false; + } + + $payload = $packetLength > 0 ? $this->readBytes($packetLength) : ''; + if ($payload === false) { + $this->lastReadStatus = self::READ_STATUS_ERROR_PAYLOAD; + return false; + } + $this->debugMessage('Packet response: '. self::str2hex($header . $payload)); + $this->lastReadStatus = self::READ_STATUS_OK; + return $header . $payload; + } + + public function getLastReadStatus() { + return $this->lastReadStatus; + } + + public function hasMoreToRead() { + return ($this->lastReadStatus == self::READ_STATUS_OK) && $this->isConnected(); + } + + /** + * Read packets from stream and save to queue. Quit after x packets or timeout. + * + * @param integer $maxPackets Packet id the message must match + * @return integer Number of packets read + */ + private function readPackets($maxPackets = 100) { + $receivedPackets = 0; + while (($receivedPackets < $maxPackets) && ($packet = $this->readNextPacket()) !== false) { + $this->packetQueue[] = $packet; + $receivedPackets++; + } + return $receivedPackets; + } + + /** + * Wait until a certain packet is found in the stream. + * Save other recieved packets in queue. + * + * @param byte $header Header to look for (only 4 high bits) 0xf0 + * @param integer $verifyPacketId Packet id the message must match + * @return boolean + */ + private function waitForPacket($header, $verifyPacketId = false) { + // first check unhandled packets + foreach ($this->packetQueue as $key => $packet) { + if ($this->isPacketVerified($packet, $header, $verifyPacketId)) { + // if found, remove from queue and return packet + unset($this->packetQueue[$key]); + return $packet; + } + } + // if not found in queue, start reading from stream until found or timeout + do { + $packet = $this->readNextPacket(); + if ($packet === false || empty($packet)) return false; + if ($this->isPacketVerified($packet, $header, $verifyPacketId)) { + return $packet; + } + // another packet found, save it to queue + $this->packetQueue[] = $packet; + } while(true); + } + + /** + * Check if packet is of a given type and packet id match latest sent packet id + * + * @param string $packet + * @param char $header + * @param integer $verifyPacketId + * @return boolean + */ + private function isPacketVerified($packet, $header, $verifyPacketId = false) { + if (is_string($packet) && strlen($packet) >= 1) { + if ((int)(ord($packet[0])&0xf0) == (int)($header&0xf0)) { + if ($verifyPacketId === false) return true; + if (strlen($packet) >= 3) { + $receivedPacketId = (int)(ord($packet[1])<<8) + ord($packet[2]); + if($verifyPacketId == $receivedPacketId) { + return true; + } + } + } + } + return false; + } + + /** + * Get packets matching a header from the queue and remove from queue + * + * @param char $header + * @return string[] + */ + public function getQueuePackets($header) { + $foundPackets = []; + foreach ($this->packetQueue as $key => $packet) { + if ($this->isPacketVerified($packet, $header)) { + $foundPackets[] = $packet; + unset($this->packetQueue[$key]); + } + } + return $foundPackets; + } + + /** + * Get PUBLISH packets and return them as messages + * + * @param integer $maxMessages Max messages to read + * @param boolean $sendPubAck If true, then send PUBACK to MQTT-server (QoS 1) + * @param boolean $sendPubRec If true, then send PUBREC to MQTT-server, wait for PUBREL and send PUBCOMP (QoS 2) + * @return string[] All PUBLISH messages which were confirmed or no confirmation needed/wanted + */ + public function getPublishMessages($maxMessages = 100, $sendPubAck = false, $sendPubRec = false) { + $packetsRead = $this->readPackets($maxMessages); + $packets = $this->getQueuePackets(self::MQTT_PUBLISH); + $messages = []; + foreach ($packets as $key => $packet) { + $message = $this->decodePublish($packet); + if ($message === false) { + $this->debugMessage('Message could not be decoded'); + continue; + } + + if ($sendPubAck && ($message['qos'] == self::MQTT_QOS1)) { + if($this->sendPubAck($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBACK'); + continue; + } + } elseif ($sendPubRec && ($message['qos'] == self::MQTT_QOS2)) { + // Send PUBREC + if($this->sendPubRec($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBREC'); + continue; + } + // A PUBREL packet is expected + $response = $this->waitForPacket(self::MQTT_PUBREL, $message['packetId']); + if($response === false) { + $this->debugMessage('Packet missing, expecting PUBREL'); + continue; + } + // Send PUBCOMP + if($this->sendPubComp($message['packetId']) === false) { + $this->debugMessage('Failed to send PUBCOMP'); + continue; + } + } + + // Package was successfully confirmed or no confirmation needed/wanted --> store it + $messages[] = $message; + } + return $messages; + } + + /** + * Decode a publish packet to its attributes + * + * @param string $packet + * @return array|boolean Return message or false if decode failed + */ + public function decodePublish($packet) { + if (!is_string($packet) || (strlen($packet) <= 3)) { + return false; + } + $flags = ord($packet[0]) & 0x0f; + $duplicate = ($flags == 0x80); + $retain = ($flags == 0x01); + $qos = ($flags>>1) & 0x03; + $topicLength = (ord($packet[1])<<8) + ord($packet[2]); + $topic = substr($packet, 3, $topicLength); + + $payload = substr($packet, 3 + $topicLength); // Get the payload of the packet + if ($qos == 0) { + // no packet id for QoS 0, the payload is the message + $message = $payload; + $packetId = NULL; + } else { + if (strlen($payload) >= 2) { + $packetId = (ord($payload[0])<<8) + ord($payload[1]); + $message = substr($payload, 2); // skip packet id (2 bytes) for QoS 1 and 2 + } else { + // 2 byte packet id required, but not found. exit gracefully (no failure) + $packetId = NULL; + $message = ''; + } + } + return [ + 'topic' => self::convertActiveMqTopic($topic), + 'message' => $message, + 'retain' => $retain, + 'duplicate' => $duplicate, + 'qos' => $qos, + 'packetId' => $packetId, + ]; + } + + /** + * Replace ActiveMQ special characters to MQTT-standard + * + * @param string $topic + * @return string + */ + private static function convertActiveMqTopic($topic) { + $topic = str_replace(".","/", $topic); + $topic = str_replace("*","+", $topic); + $topic = str_replace(">","#", $topic); + return $topic; + } + + /** + * Return a string interpreted as hex and ASCII (between 0x20-0x7f) + * Good for displaying recieved packets + * + * @param string $str + * @return string + */ + private function str2hex($str) { + $hex = ''; + $ascii = ''; + for ($i=0; $i= 0x20 && ord($char) <= 0x7f) { + $ascii .= $char; + } else { + $ascii .= '.'; + } + $hex .= dechex(ord($char)).' '; + } + return $hex . '"'. $ascii .'"'; + } + + public function dumpQueue() { + foreach ($this->packetQueue as $packet) { + $this->str2hex($packet) . PHP_EOL; + } + } +} \ No newline at end of file diff --git a/app/Middleware/Auth/ApiMiddleware.php b/app/Middleware/Auth/ApiMiddleware.php index ce06bff..44cf3fc 100644 --- a/app/Middleware/Auth/ApiMiddleware.php +++ b/app/Middleware/Auth/ApiMiddleware.php @@ -39,7 +39,7 @@ class ApiMiddleware implements MiddlewareInterface public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - if (env('APP_ENV') == 'dev') { + if (env('APP_ENV') == 'dev' || env('APP_ENV') == 'local') { return $handler->handle($request); } diff --git a/app/Model/Coupon.php b/app/Model/Coupon.php index b6d984d..e50574b 100644 --- a/app/Model/Coupon.php +++ b/app/Model/Coupon.php @@ -6,6 +6,9 @@ use App\Model\Model; class Coupon extends Model { + const DISCOUNT_TYPE_CASH = 1; + const DISCOUNT_TYPE_RATE = 2; + protected $table = 'ims_system_coupon_user'; } diff --git a/app/Model/CouponUserRec.php b/app/Model/CouponUserRec.php new file mode 100644 index 0000000..c5c2608 --- /dev/null +++ b/app/Model/CouponUserRec.php @@ -0,0 +1,10 @@ +belongsTo(Goods::class, 'good_id', 'id'); + } + +} \ No newline at end of file diff --git a/app/Request/OrderOnlineRequest.php b/app/Request/OrderOnlineRequest.php new file mode 100644 index 0000000..dfe0ae6 --- /dev/null +++ b/app/Request/OrderOnlineRequest.php @@ -0,0 +1,72 @@ + 'nonempty', + 'delivery_no' => '', + 'dada_fee' => 'nonempty', + 'market_id' => 'required|nonempty|integer', + 'user_id' => 'required|nonempty|integer', + 'money' => 'required|nonempty', + 'box_money' => '', + 'ps_money' => '', + 'mj_money' => '', + 'xyh_money' => '', + 'yhq_money' => '', + 'yhq_money2' => '', + 'zk_money' => '', + 'tel' => 'required|nonempty', + 'name' => 'required|nonempty', + 'address' => 'required|nonempty', + 'area' => '', + 'lat' => 'required|nonempty', + 'lng' => 'required|nonempty', + 'note' => '', + 'type' => 'required|nonempty', + 'form_id' => '', + 'form_id2' => '', + 'delivery_time' => '', + 'order_type' => 'nonempty', + 'pay_type' => 'nonempty', + 'coupon_id' => '', + 'coupon_id2' => '', + 'uniacid' => 'nonempty', + 'store_list' => 'nonempty', + 'receive_coupon_ids' => '', + ]; + } + + public function messages(): array + { + return [ + '*.*' => ':attribute 参数异常' + ]; + } + + public function attributes(): array + { + return [ + + ]; + } +} diff --git a/app/Service/CoupnoServiceInterface.php b/app/Service/CoupnoServiceInterface.php new file mode 100644 index 0000000..4e3d9a4 --- /dev/null +++ b/app/Service/CoupnoServiceInterface.php @@ -0,0 +1,20 @@ +get(Redis::class); + $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId); + + $currentTime = time(); + + $builder = Db::table('ims_system_coupon_user_receive as receive') + ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner'); + + if (is_array($fields)&&!empty($fields)) { + $builder->select([ + 'receive.id as receive_id', + 'receive.user_id', + 'receive.number_remain', + 'coupon.id', + 'coupon.title', + 'coupon.full_amount', + 'coupon.discounts', + 'coupon.usable_start_time', + 'coupon.usable_end_time', + 'coupon.discount_type' + ]); + } + + if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) { + $builder->whereNotIn('coupon.id', $couponTodayUsedIds); + } + + return $builder->where(['receive.user_id' => $userId]) + ->whereIn('receive.status', [0,1]) + ->where('receive.number_remain', '>', 0) + ->whereIn('coupon.type', [1,$type]) + ->where('coupon.full_amount', '<=', $orderAmount) + ->where('coupon.usable_start_time', '<=', $currentTime) + ->where('coupon.usable_end_time', '>=', $currentTime) + ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain')) + ->where('coupon.market_id', 'in', [0, $marketId]) + ->whereIn('coupon.storetype_id', $storeTypeIds) + ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC') + ->get() + ->toArray(); + } + + /** + * 缓存优惠券今日使用情况 + * @param $userId + * @param $couponId + * @param $couponRecId + * @return bool + */ + function cacheTodayCouponUsed($userId, $couponId, $couponRecId) + { + + $redis = ApplicationContext::getContainer()->get(Redis::class); + + $setRes = $redis->sAdd( + 'coupon_'.date('Ymd').'_used_'.$userId, + $couponId + ); + + $expireRes = $redis->expire( + 'coupon_'.date('Ymd').'_used_'.$userId, + strtotime(date('Y-m-d').' 23:59:59')-time() + ); + + return $setRes&&$expireRes; + } +} \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php new file mode 100644 index 0000000..e16d2cb --- /dev/null +++ b/app/Service/OrderService.php @@ -0,0 +1,423 @@ +existsByOrderNum($data['order_num'])) { + return $orderMainId; + } + + Db::beginTransaction(); + try { + + // 计算当前订单可用红包优惠金额 + $couponMoney = 0; + if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) { + $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids'])); + $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']); + } + $dataMain['yhq_money2'] = $couponMoney; + + // 获取分布式全局ID + $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class); + $dataMain['global_order_id'] = $generator->generate(); + + // 店铺IDs + $dataMain['store_ids'] = ''; + $storeList = json_decode(json_encode($data['store_list']), true); + if (!is_array($storeList)||empty($storeList)) { + Db::rollBack(); + return '订单中商品不存在或已失效'; + } + + // 获取商户IDs + foreach ($storeList as &$item) { + $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; + } + + // 主订单插入数据 + $currentTime = time(); + $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); + $dataMain['time_add'] = $currentTime; + $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; + $dataMain['code'] = $dataMain['global_order_id']; + + // 主订单模型保存 + $orderMain = OrderMain::create($dataMain); + $orderMainId = $orderMain->id; + + // 统计订单中所有店铺当日订单数,做店铺订单序号 + $countsArr = Order::query()->select('COUNT(*) AS count, id') + ->whereIn('store_id', explode(',', $dataMain['store_ids'])) + ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) + ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) + ->get() + ->toArray(); + + $storeOrderCounts = []; + foreach ($countsArr as $key => &$row) { + $storeOrderCounts[$row['id']] = $row['count']; + } + + // 循环处理订单总额、子订单总额、商品、商户订单等信息 + $orderAmountTotal = 0; # 总订单金额 + foreach ($storeList as $key => &$item) { + + // 子订单数据处理 + $dataChild = [ + 'uniacid' => $data['uniacid'], + 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), + 'user_id' => $orderMain->user_id, + 'store_id' => $item['store_id'], + 'order_main_id' => $orderMain, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'tel' => $orderMain->tel, + 'name' => $orderMain->name, + 'address' => $orderMain->address, + 'area' => $orderMain->area, + 'time' => date("Y-m-d H:i:s"), + 'note' => $item['note'], + 'delivery_time' => $orderMain->delivery_time, + 'type' => $orderMain->type, + 'lat' => $orderMain->lat, + 'lng' => $orderMain->lng, + 'pay_type' => $orderMain->pay_type, + 'order_type' => $orderMain->order_type, + 'money' => floatval($item['subtotal']), + 'box_money' => floatval($item['box_money']), + 'mj_money' => floatval($item['mj_money']), + 'yhq_money' => floatval($item['yhq_money']), + 'yhq_money2' => floatval($item['yhq_money2']), + 'zk_money' => floatval($item['zk_money']), + 'coupon_id' => $item['coupon_id'], + 'coupon_id2' => $item['coupon_id2'], + 'xyh_money' => floatval($item['xyh_money']), + 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1, + 'time_add' => date("Y-m-d H:i:s"), + ]; + + $order = Order::create($dataChild); + $orderChildId = $order->id; + + // 子订单内商品处理 + $goodsAmountTotal = 0; + $orderGoods = []; + if (!is_array($item['good_list'])||empty($item['good_list'])) { + Db::rollBack(); + return '订单商品异常'; + } + foreach ($item['good_list'] as &$goods) { + + $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money'])); + $goodsAmount = bcmul($goodsAmount, $goods['num']); + $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount); + + $orderGoods[$goods['id']] = $goods; + $orderGoods[$goods['id']]['uniacid'] = $data['uniacid']; + $orderGoods[$goods['id']]['order_id'] = $orderChildId; + $orderGoods[$goods['id']]['user_id'] = $dataMain['user_id']; + $orderGoods[$goods['id']]['store_id'] = $item['store_id']; + } + + // 子订单优惠总额 + $discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']); + + $goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2); + $orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2); + + // 校验子订单金额 + if ($goodsAmountTotal != $dataChild['money']) { + Db::rollBack(); + return '店铺订单总金额错误'; + } + + } + + // 校验库存 + foreach ($orderGoods as $Key=>&$goodsItem) { + + $goodsItem['combination_id'] = intval($goodsItem['combination_id']); + + // 存在规格,则去规格处查库存,整个接口还有很多别的问题,目前 + $goods = (object)[]; + if ($goodsItem['combination_id'] > 0) { + + $goods = SpecCombination::query() + ->select('id, number AS inventory') + ->where(['id' => $goodsItem['combination_id']]) + ->first(); + $goods->name = $goods->goods->name; + $goods->is_max = $goods->goods->is_max; + + } else { + + $goods = Goods::query() + ->select('id, name, is_max, inventory') + ->where(['id' => $goodsItem['good_id']]) + ->first(); + + } + + if (!$goods) { + Db::rollBack(); + return '缺少商品'; + } + + if($goodsItem['num'] > $goods->inventory && $goods->is_max != Goods::INVENTORY_NOLIMIT){ + Db::rollBack(); + return '商品 '.$goods->name.' 库存不足!'; + } + + } + + // 校验总订单金额 + $deliveryAmount = 0; # 配送费用 + if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){ + $deliveryAmount = $dataMain['dada_fee']; + } + + $orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount); + # 总订单优惠总额 + $discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']); + $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']); + $orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2); + + if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) { + Db::rollBack(); + return '订单总金额错误'; + } + + // 添加订单商品 + $tempGoods = $orderGoods; + $orderGoods = []; + foreach ($tempGoods as $key => &$value) { + $goods['good_id'] = $value['good_id']; + $goods['img'] = $value['logo']; + $goods['number'] = $value['num']; + $goods['order_id'] = $value['order_id']; + $goods['name'] = $value['name']; + $goods['money'] = $value['money']; + $goods['dishes_id'] = $value['dishes_id']; + $goods['spec'] = $value['spec']; + $goods['is_qg'] = $value['is_qg']; + $goods['good_unit'] = $value['good_unit']; + $goods['uniacid'] = $value['uniacid']; + $goods['combination_id'] = $value['combination_id']; + $orderGoods[] = $goods; + } + + $addOrderGoods = OrderGoods::query()->insert($orderGoods); + if (!$addOrderGoods) { + Db::rollBack(); + return '订单商品异常'; + } + + // 修改总订单金额,金额是计算来的 + // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多 + $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]); + if (!$updateOrderMain) { + Db::rollBack(); + return '订单总金额记录失败'; + } + + // 处理红包的使用 + $canUseConpons = $this->couponService->getOrderCanUseCoupons( + $data['money'], + $data['market_id'], + $data['user_id'], + [ + 'receive.id', + 'receive.user_id', + 'receive.number', + 'receive.number_remain', + 'receive.system_coupon_user_id', + 'coupon.discounts', + 'coupon.discount_type', + ] + ); + + if (is_array($canUseConpons)&&!empty($canUseConpons)) { + # 使用记录、更新当前优惠券 + foreach ($canUseConpons as $key => &$coupon) { + $couponUse = [ + 'user_id' => $coupon['user_id'], + 'user_receive_id' => $coupon['id'], + 'system_coupon_id' => $coupon['system_coupon_user_id'], + 'order_main_id' => $orderMainId, + 'use_time' => $currentTime, + 'return_time' => 0, + 'number' => 1, + 'status' => 1, + 'update_time' => 0, + ]; + + $insertRes = CouponUserUse::query()->insert($couponUse); + + if ($insertRes) { + $numberRemain = $coupon['number_remain'] - 1; + if ($numberRemain == 0) { + $status = 2; + } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { + $status = 1; + } elseif ($numberRemain == $coupon['number']) { + $status = 0; + } + + $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); + + if (!$upRes) { + Db::rollBack(); + return '优惠券使用失败'; + } + + // 缓存使用记录 + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); + if (!$usedRes) { + Db::rollBack(); + return '优惠券使用失败'; + } + + } else { + Db::rollBack(); + return '优惠券使用失败'; + } + + } + } + + Db::commit(); + + + } catch (Exception $e) { + + Db::rollBack(); + return $e->getMessage(); + + } + + // 订单成功后处理 + if ($orderMainId) { + + // 处理喇叭播报 + + + } + + return $orderMainId; + } + + /** + * @inheritDoc + */ + public function addOfflineOrder() + { + // TODO: Implement addOfflineOrder() method. + } + + + + /** + * 计算和校验当前订单可用红包及金额 + * @param $couponIds + * @param $orderAmount + * @param $userId + * @param $marketId + * @throws Exception + */ + protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId) + { + + // 用户当前订单可用优惠券 + $couponsCanUse = $this->couponService->getOrderCanUseCoupons( + $orderAmount, + $marketId, + $userId, + [ + 'receive.id', + 'receive.user_id', + 'receive.number', + 'receive.number_remain', + 'receive.system_coupon_user_id', + 'coupon.discounts', + 'coupon.discount_type', + ] + ); + + $couponCanUseIds = array_column($couponsCanUse, 'id'); + $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds); + $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds); + + if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) { + throw new Exception('您的订单中有优惠券已经失效'); + } + + // 计算红包折扣金额 + $couponMoney = 0; + foreach ($couponsCanUse as $key => $coupon) { + + if (!in_array($coupon->id, $couponIds)) { + continue; + } + + if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) { + $couponMoney = bcadd($couponMoney, $coupon->discounts, 2); + } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) { + $discountRate = bcdiv($coupon->discounts,10); + $discountRate = bcsub(1,$discountRate); + $discountMoney = bcmul($orderAmount, $discountRate); + $couponMoney = bcadd($couponMoney, $discountMoney, 2); + } + } + + return $couponMoney; + + } + + /** + * 订单是否存在 + * @param $orderNum + * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null + */ + public function existsByOrderNum($orderNum) + { + return OrderMain::query()->where(['order_num' => $orderNum])->value('id'); + } +} \ No newline at end of file diff --git a/app/Service/OrderServiceInterface.php b/app/Service/OrderServiceInterface.php new file mode 100644 index 0000000..08ee815 --- /dev/null +++ b/app/Service/OrderServiceInterface.php @@ -0,0 +1,29 @@ +mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); + $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + + if (env('MQTT_CERT')) { + $this->mqttClient->setEncryption(env('MQTT_CERT')); + } + + return $this->mqttClient; + } +} \ No newline at end of file diff --git a/composer.json b/composer.json index 1ac7889..d8f86c6 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,10 @@ "hyperf/constants": "~2.0.0", "hyperf/model-cache": "~2.0.0", "hyperf/validation": "^2.0", - "hyperf/paginator": "^2.0" + "hyperf/paginator": "^2.0", + "hyperf/snowflake": "^2.0", + "ext-bcmath": "*", + "hyperf/task": "^2.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index cccee93..a4028ee 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -10,5 +10,7 @@ declare(strict_types=1); * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ - \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class + \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, + \App\Service\OrderServiceInterface::class => \App\Service\OrderService::class, + \App\Service\CoupnoServiceInterface::class => \App\Service\CouponService::class, ]; diff --git a/config/autoload/server.php b/config/autoload/server.php index e0e6cd8..f44b083 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -36,16 +36,13 @@ return [ 'max_request' => 100000, 'socket_buffer_size' => 2 * 1024 * 1024, 'buffer_output_size' => 2 * 1024 * 1024, - // Task Worker 数量,根据您的服务器配置而配置适当的数量 'task_worker_num' => 8, - // 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况 'task_enable_coroutine' => false, ], 'callbacks' => [ SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], - // Task callbacks SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], diff --git a/config/autoload/snowflake.php b/config/autoload/snowflake.php new file mode 100644 index 0000000..279de42 --- /dev/null +++ b/config/autoload/snowflake.php @@ -0,0 +1,24 @@ + MetaGeneratorInterface::DEFAULT_BEGIN_SECOND, + RedisMilliSecondMetaGenerator::class => [ + 'pool' => 'default', + ], + RedisSecondMetaGenerator::class => [ + 'pool' => 'default', + ], +]; diff --git a/config/routes.php b/config/routes.php index 706a9ab..c14f389 100644 --- a/config/routes.php +++ b/config/routes.php @@ -23,4 +23,5 @@ Router::addGroup('/v1/',function (){ Router::post('ServiceEvaluate/isPersonnel', 'App\Controller\ServiceEvaluateController@isPersonnel'); Router::post('ServiceEvaluate/getPersonnelInfo', 'App\Controller\ServiceEvaluateController@getPersonnelInfo'); Router::post('ServiceEvaluate/getEvaluateList', 'App\Controller\ServiceEvaluateController@getEvaluateList'); + Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); }); \ No newline at end of file From e99bcfdbf051b350f385ebbd2645d260116f0e7c Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 14:35:51 +0800 Subject: [PATCH 23/72] =?UTF-8?q?=E5=A4=96=E5=8D=96=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 +- app/Controller/OrderController.php | 12 +++++- app/Model/OrderMain.php | 36 +++++++++-------- app/Service/CouponService.php | 14 +------ app/Service/OrderService.php | 50 ++++++++++++------------ 5 files changed, 61 insertions(+), 55 deletions(-) diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index d0aa997..f6e58bc 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -65,7 +65,9 @@ class DevicOrderConsumer extends ConsumerMessage public function isEnable(): bool { - // if(env('APP_ENV')!='prod') return false; + if(env('APP_ENV') == 'local') { + return false; + } return parent::isEnable(); } } diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 0973da0..8757ff9 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -5,6 +5,7 @@ namespace App\Controller; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; +use Hyperf\HttpMessage\Stream\SwooleStream; class OrderController extends BaseController { @@ -18,6 +19,15 @@ class OrderController extends BaseController public function addOnlineOrder(OrderOnlineRequest $request) { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); - return $this->success(['order_main_id' => $orderMainId]); + if (!is_int($orderMainId)) { + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus(500) + ->withBody(new SwooleStream($orderMainId)); + } + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus(200) + ->withBody(new SwooleStream($orderMainId)); } } \ No newline at end of file diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index 1a0a7e9..ee3840c 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -6,41 +6,43 @@ namespace App\Model; class OrderMain extends Model { - // ϶ + // 线上订单,外卖 const ORDER_TYPE_ONLINE = 1; - // ¶渶 + // 线下订单,当面付 const ORDER_TYPE_OFFLINE = 4; - // ״̬ - // + // 订单状态 + // 待付款 const ORDER_STATE_UNPAY = 1; - // ӵ + // 待接单 const ORDER_STATE_UNTAKE = 2; - // ʹ + // 待送达 const ORDER_STATE_DELIVERY = 3; - // + // 已完成 const ORDER_STATE_COMPLETE = 4; - // + // 已评价 const ORDER_STATE_EVALUATED = 5; - // ȡ + // 已取消 const ORDER_STATE_CANCEL = 6; - // Ѿܵ + // 已拒单 const ORDER_STATE_REFUSE = 7; - // ˿ + // 退款中 const ORDER_STATE_REFUNDING = 8; - // ˿ + // 已退款 const ORDER_STATE_REFUNDED = 9; - // ܾ˿ + // 拒绝退款 const ORDER_STATE_UNREFUND = 10; - // ֧ʽ - // ΢֧ + // 订单支付方式 + // 微信支付 const ORDER_PAY_WX = 1; - // ֧ + // 余额支付 const ORDER_PAY_BALANCE = 2; protected $table = 'ims_cjdc_order_main'; + public $timestamps = false; + protected $fillable = [ 'order_num', 'delivery_no', @@ -75,6 +77,8 @@ class OrderMain extends Model 'state', 'time', 'time_add', + 'pay_time', + 'jj_note', 'global_order_id', ]; diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index f1d4bf5..f4f8af9 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -18,25 +18,13 @@ class CouponService implements CoupnoServiceInterface // 用户今日使用过的优惠券 $redis = ApplicationContext::getContainer()->get(Redis::class); $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId); - $currentTime = time(); $builder = Db::table('ims_system_coupon_user_receive as receive') ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner'); if (is_array($fields)&&!empty($fields)) { - $builder->select([ - 'receive.id as receive_id', - 'receive.user_id', - 'receive.number_remain', - 'coupon.id', - 'coupon.title', - 'coupon.full_amount', - 'coupon.discounts', - 'coupon.usable_start_time', - 'coupon.usable_end_time', - 'coupon.discount_type' - ]); + $builder->select($fields); } if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) { diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index e16d2cb..25a44e5 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -57,7 +57,7 @@ class OrderService implements OrderServiceInterface // 店铺IDs $dataMain['store_ids'] = ''; - $storeList = json_decode(json_encode($data['store_list']), true); + $storeList = json_decode(html_entity_decode($data['store_list']), true); if (!is_array($storeList)||empty($storeList)) { Db::rollBack(); return '订单中商品不存在或已失效'; @@ -72,15 +72,19 @@ class OrderService implements OrderServiceInterface $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['time_add'] = $currentTime; + $dataMain['pay_time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; $dataMain['code'] = $dataMain['global_order_id']; + $dataMain['jj_note'] = ''; // 主订单模型保存 $orderMain = OrderMain::create($dataMain); $orderMainId = $orderMain->id; // 统计订单中所有店铺当日订单数,做店铺订单序号 - $countsArr = Order::query()->select('COUNT(*) AS count, id') + $countsArr = Order::query() + ->selectRaw('COUNT(*) AS count') + ->select('id') ->whereIn('store_id', explode(',', $dataMain['store_ids'])) ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) @@ -102,14 +106,14 @@ class OrderService implements OrderServiceInterface 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), 'user_id' => $orderMain->user_id, 'store_id' => $item['store_id'], - 'order_main_id' => $orderMain, + 'order_main_id' => $orderMainId, 'state' => OrderMain::ORDER_STATE_UNPAY, 'tel' => $orderMain->tel, 'name' => $orderMain->name, 'address' => $orderMain->address, 'area' => $orderMain->area, 'time' => date("Y-m-d H:i:s"), - 'note' => $item['note'], + 'note' => $item['note'] ?? '', 'delivery_time' => $orderMain->delivery_time, 'type' => $orderMain->type, 'lat' => $orderMain->lat, @@ -127,10 +131,13 @@ class OrderService implements OrderServiceInterface 'xyh_money' => floatval($item['xyh_money']), 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1, 'time_add' => date("Y-m-d H:i:s"), + 'jj_note' => '', + 'form_id' => '', + 'form_id2' => '', + 'code' => '', ]; - $order = Order::create($dataChild); - $orderChildId = $order->id; + $orderChildId = Order::query()->insertGetId($dataChild); // 子订单内商品处理 $goodsAmountTotal = 0; @@ -140,7 +147,6 @@ class OrderService implements OrderServiceInterface return '订单商品异常'; } foreach ($item['good_list'] as &$goods) { - $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money'])); $goodsAmount = bcmul($goodsAmount, $goods['num']); $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount); @@ -170,7 +176,7 @@ class OrderService implements OrderServiceInterface } // 校验库存 - foreach ($orderGoods as $Key=>&$goodsItem) { + foreach ($orderGoods as $Key => &$goodsItem) { $goodsItem['combination_id'] = intval($goodsItem['combination_id']); @@ -179,21 +185,27 @@ class OrderService implements OrderServiceInterface if ($goodsItem['combination_id'] > 0) { $goods = SpecCombination::query() - ->select('id, number AS inventory') + ->with(['goods' => function($query){ + $query->select(['name', 'is_max']); + }]) + ->select(['id', 'number AS inventory']) ->where(['id' => $goodsItem['combination_id']]) - ->first(); + ->first() + ->toArray(); $goods->name = $goods->goods->name; $goods->is_max = $goods->goods->is_max; } else { $goods = Goods::query() - ->select('id, name, is_max, inventory') + ->select(['id', 'name', 'is_max', 'inventory']) ->where(['id' => $goodsItem['good_id']]) - ->first(); + ->first() + ->toArray(); } + var_dump('$goods', $goods); if (!$goods) { Db::rollBack(); return '缺少商品'; @@ -243,7 +255,7 @@ class OrderService implements OrderServiceInterface $goods['combination_id'] = $value['combination_id']; $orderGoods[] = $goods; } - + var_dump('$orderGoods', $orderGoods); $addOrderGoods = OrderGoods::query()->insert($orderGoods); if (!$addOrderGoods) { Db::rollBack(); @@ -324,7 +336,7 @@ class OrderService implements OrderServiceInterface } Db::commit(); - + return $orderMainId; } catch (Exception $e) { @@ -332,16 +344,6 @@ class OrderService implements OrderServiceInterface return $e->getMessage(); } - - // 订单成功后处理 - if ($orderMainId) { - - // 处理喇叭播报 - - - } - - return $orderMainId; } /** From 88ae5b544be899640afd4ac40faa29935fb5d9e0 Mon Sep 17 00:00:00 2001 From: Mike Date: Wed, 12 Aug 2020 14:52:32 +0800 Subject: [PATCH 24/72] =?UTF-8?q?=E5=B0=81=E8=A3=85w7=E6=97=A7=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=95=B0=E6=8D=AE=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/BaseController.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/Controller/BaseController.php b/app/Controller/BaseController.php index 40d2813..ffa8c77 100644 --- a/app/Controller/BaseController.php +++ b/app/Controller/BaseController.php @@ -13,9 +13,18 @@ namespace App\Controller; use Hyperf\HttpServer\Contract\ResponseInterface; use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface; +use Hyperf\HttpMessage\Stream\SwooleStream; class BaseController extends AbstractController { + + public function w7result($statusCode,$data = ''){ + return $this->response + ->withHeader('Content-Type', 'application/text') + ->withStatus($statusCode) + ->withBody(new SwooleStream($data)); + } + public function result($code, $data, $message = '成功'):Psr7ResponseInterface { $status = 'ok'; From 5729da8d1c04ad28a31f018ac9deaa7fe1a1b237 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 15:18:39 +0800 Subject: [PATCH 25/72] =?UTF-8?q?=E5=A4=96=E5=8D=96=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/OrderController.php | 10 +---- app/Service/OrderService.php | 67 +++++++++++++++--------------- 2 files changed, 36 insertions(+), 41 deletions(-) diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 8757ff9..8d93c54 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -20,14 +20,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->response - ->withHeader('Content-Type', 'application/text') - ->withStatus(500) - ->withBody(new SwooleStream($orderMainId)); + return $this->w7result(500, $orderMainId); } - return $this->response - ->withHeader('Content-Type', 'application/text') - ->withStatus(200) - ->withBody(new SwooleStream($orderMainId)); + return $this->w7result(200, $orderMainId); } } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 25a44e5..374631e 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -180,20 +180,22 @@ class OrderService implements OrderServiceInterface $goodsItem['combination_id'] = intval($goodsItem['combination_id']); - // 存在规格,则去规格处查库存,整个接口还有很多别的问题,目前 - $goods = (object)[]; + // 存在规格,则去规格处查库存 + $goods = []; if ($goodsItem['combination_id'] > 0) { - $goods = SpecCombination::query() - ->with(['goods' => function($query){ - $query->select(['name', 'is_max']); - }]) - ->select(['id', 'number AS inventory']) + $combination = SpecCombination::query() + ->select(['good_id AS id', 'number AS inventory']) ->where(['id' => $goodsItem['combination_id']]) ->first() ->toArray(); - $goods->name = $goods->goods->name; - $goods->is_max = $goods->goods->is_max; + + $goods = Goods::query() + ->select(['id', 'name', 'is_max']) + ->where(['id' => $combination['id']]) + ->first() + ->toArray(); + $goods['inventory'] = $combination['inventory']; } else { @@ -205,13 +207,12 @@ class OrderService implements OrderServiceInterface } - var_dump('$goods', $goods); if (!$goods) { Db::rollBack(); return '缺少商品'; } - if($goodsItem['num'] > $goods->inventory && $goods->is_max != Goods::INVENTORY_NOLIMIT){ + if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){ Db::rollBack(); return '商品 '.$goods->name.' 库存不足!'; } @@ -241,21 +242,21 @@ class OrderService implements OrderServiceInterface $tempGoods = $orderGoods; $orderGoods = []; foreach ($tempGoods as $key => &$value) { - $goods['good_id'] = $value['good_id']; - $goods['img'] = $value['logo']; - $goods['number'] = $value['num']; - $goods['order_id'] = $value['order_id']; - $goods['name'] = $value['name']; - $goods['money'] = $value['money']; - $goods['dishes_id'] = $value['dishes_id']; - $goods['spec'] = $value['spec']; - $goods['is_qg'] = $value['is_qg']; - $goods['good_unit'] = $value['good_unit']; - $goods['uniacid'] = $value['uniacid']; - $goods['combination_id'] = $value['combination_id']; - $orderGoods[] = $goods; + $goodsTemp['good_id'] = $value['good_id']; + $goodsTemp['img'] = $value['logo']; + $goodsTemp['number'] = $value['num']; + $goodsTemp['order_id'] = $value['order_id']; + $goodsTemp['name'] = $value['name']; + $goodsTemp['money'] = $value['money']; + $goodsTemp['dishes_id'] = $value['dishes_id']; + $goodsTemp['spec'] = $value['spec']; + $goodsTemp['is_qg'] = $value['is_qg']; + $goodsTemp['good_unit'] = $value['good_unit']; + $goodsTemp['uniacid'] = $value['uniacid']; + $goodsTemp['combination_id'] = $value['combination_id']; + $orderGoods[] = $goodsTemp; } - var_dump('$orderGoods', $orderGoods); + $addOrderGoods = OrderGoods::query()->insert($orderGoods); if (!$addOrderGoods) { Db::rollBack(); @@ -290,9 +291,9 @@ class OrderService implements OrderServiceInterface # 使用记录、更新当前优惠券 foreach ($canUseConpons as $key => &$coupon) { $couponUse = [ - 'user_id' => $coupon['user_id'], - 'user_receive_id' => $coupon['id'], - 'system_coupon_id' => $coupon['system_coupon_user_id'], + 'user_id' => $coupon->user_id, + 'user_receive_id' => $coupon->id, + 'system_coupon_id' => $coupon->system_coupon_user_id, 'order_main_id' => $orderMainId, 'use_time' => $currentTime, 'return_time' => 0, @@ -304,16 +305,16 @@ class OrderService implements OrderServiceInterface $insertRes = CouponUserUse::query()->insert($couponUse); if ($insertRes) { - $numberRemain = $coupon['number_remain'] - 1; + $numberRemain = $coupon->number_remain - 1; if ($numberRemain == 0) { $status = 2; - } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { + } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) { $status = 1; - } elseif ($numberRemain == $coupon['number']) { + } elseif ($numberRemain == $coupon->number) { $status = 0; } - $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); + $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]); if (!$upRes) { Db::rollBack(); @@ -321,7 +322,7 @@ class OrderService implements OrderServiceInterface } // 缓存使用记录 - $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id); if (!$usedRes) { Db::rollBack(); return '优惠券使用失败'; From 3828ac8225e24eea84131479d6a3224751d9a7d1 Mon Sep 17 00:00:00 2001 From: Mike Date: Wed, 12 Aug 2020 15:35:19 +0800 Subject: [PATCH 26/72] =?UTF-8?q?=E5=BE=AE=E4=BF=A1=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++ app/Request/BaseFormRequest.php | 26 +++++++++++++ app/Request/WxminiPayRequest.php | 58 ++++++++++++++++++++++++++++ config/routes.php | 4 ++ 4 files changed, 92 insertions(+) create mode 100644 app/Request/BaseFormRequest.php create mode 100644 app/Request/WxminiPayRequest.php diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 86ce06c..14fbc48 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -7,4 +7,8 @@ namespace App\Controller; class PaymentController extends BaseController { + public function wxminiPay(){ + + } + } \ No newline at end of file diff --git a/app/Request/BaseFormRequest.php b/app/Request/BaseFormRequest.php new file mode 100644 index 0000000..14bbc31 --- /dev/null +++ b/app/Request/BaseFormRequest.php @@ -0,0 +1,26 @@ +withStatus(200); + // } +} \ No newline at end of file diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php new file mode 100644 index 0000000..0a7f6dd --- /dev/null +++ b/app/Request/WxminiPayRequest.php @@ -0,0 +1,58 @@ + 'required|nonempty|integer', + 'c_service' => 'required|nonempty|integer', + 'c_quality' => 'required|nonempty|integer', + 'content' => 'required|nonempty|strlen:15,150', + 'user_id' => 'required|nonempty|integer|exists:ims_cjdc_user,id', + 'service_personnel_id' => 'required|nonempty|integer|exists_enable:lanzu_service_personnel,id,status=1|not_equal:user_id,lanzu_service_personnel,id,user_id', + 'market_id' => 'required|nonempty|integer|exists:ims_cjdc_market,id', + ]; + } + + public function messages(): array + { + return [ + 'user_id.exists' => ':attribute不存在', + 'service_personnel_id.exists' => ':attribute不存在', + 'market_id.exists' => ':attribute不存在', + 'user_id.*' => ':attribute信息不正确', + 'service_personnel_id.exists_enable' => ':attribute不存在或被禁用', + 'service_personnel_id.not_equal' => ':attribute不能是自己', + 'service_personnel_id.*' => ':attribute信息不正确', + 'market_id.*' => ':attribute信息不正确', + 'c_attitude.*' => ':attribute信息不正确', + 'c_service.*' => ':attribute信息不正确', + 'c_quality.*' => ':attribute信息不正确', + 'content.strlen' => ':attribute字数限制在:min~:max字', + 'content.*' => ':attribute信息不正确', + ]; + } + + public function attributes(): array + { + return [ + 'user_id' => '用户', + 'service_personnel_id' => '服务专员', + 'market_id' => '服务专员市场', + 'c_attitude' => '服务态度评分', + 'c_service' => '服务值评分', + 'c_quality' => '服务质量评分', + 'content' => '服务评价内容', + ]; + } +} \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 3979aa7..dfdf5ab 100644 --- a/config/routes.php +++ b/config/routes.php @@ -39,4 +39,8 @@ Router::addGroup('/v1/',function (){ //订单相关 Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); + + //小程序支付相关 + Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); + }); \ No newline at end of file From b6e4ae364e5844c6d6f3c0bb2e990846ac355f87 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 17:16:02 +0800 Subject: [PATCH 27/72] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E6=94=AF=E4=BB=98JSAPI?= =?UTF-8?q?=EF=BC=8CTODO=20=E6=94=AF=E4=BB=98=E6=88=90=E5=8A=9F=E9=80=9A?= =?UTF-8?q?=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/LogLabel.php | 5 +++ app/Controller/NotifyController.php | 10 ++++- app/Controller/OrderController.php | 4 +- app/Controller/PaymentController.php | 37 +++++++++++++++++-- .../Handler/ValidationExceptionHandler.php | 2 +- app/Request/OrderOnlineRequest.php | 4 +- app/Request/WxminiPayRequest.php | 34 ++++------------- app/Service/OrderService.php | 2 +- composer.json | 3 +- config/config.php | 11 +++++- config/routes.php | 1 + 11 files changed, 71 insertions(+), 42 deletions(-) diff --git a/app/Constants/LogLabel.php b/app/Constants/LogLabel.php index b3cadb4..aafacd8 100644 --- a/app/Constants/LogLabel.php +++ b/app/Constants/LogLabel.php @@ -21,4 +21,9 @@ class LogLabel extends AbstractConstants * @Message("Device Speaker Log Label") */ const DEVICE_LOG = 'device_log'; + + /** + * @Message("Pay Notice Log Label") + */ + const PAY_NOTIFY_WXMINI = 'notify_wxmini'; } diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 8aa0ba0..02aa0a3 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -1,10 +1,16 @@ log->event( + LogLabel::PAY_NOTIFY_WXMINI, + json_encode($this->request->input()) + ); + } } \ No newline at end of file diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 8d93c54..89a1cad 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -20,8 +20,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->w7result(500, $orderMainId); + return $this->w7result(500, (string)$orderMainId); } - return $this->w7result(200, $orderMainId); + return $this->w7result(200, (string)$orderMainId); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 14fbc48..29b88e3 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -1,14 +1,45 @@ validated(); + + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 待支付的,类型一致的,未超时(15min,900sec)的订单 + $orderMain = OrderMain::query() + ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'type' => $data['type'], 'id' => $data['order_id']]) + ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + return $this->result(200, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + $result = $app->order->unify([ + 'body' => '懒族生活 - 外卖下单', + 'out_trade_no' => $orderMain->global_order_id, + 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'notify_url' => config('site_host') . '/v1/notify/wxmini', + 'trade_type' => 'JSAPI', + 'openid' => $data['openid'], + ]); + + return $this->success($result); } } \ No newline at end of file diff --git a/app/Exception/Handler/ValidationExceptionHandler.php b/app/Exception/Handler/ValidationExceptionHandler.php index cc2384c..cee5579 100644 --- a/app/Exception/Handler/ValidationExceptionHandler.php +++ b/app/Exception/Handler/ValidationExceptionHandler.php @@ -24,7 +24,7 @@ class ValidationExceptionHandler extends ExceptionHandler ]); return $response->withHeader('Content-Type', 'application/json') - ->withStatus($throwable->status) + ->withStatus(200) ->withBody(new SwooleStream($content)); } diff --git a/app/Request/OrderOnlineRequest.php b/app/Request/OrderOnlineRequest.php index dfe0ae6..019cc99 100644 --- a/app/Request/OrderOnlineRequest.php +++ b/app/Request/OrderOnlineRequest.php @@ -4,9 +4,7 @@ declare(strict_types=1); namespace App\Request; -use Hyperf\Validation\Request\FormRequest; - -class OrderOnlineRequest extends FormRequest +class OrderOnlineRequest extends BaseFormRequest { /** * Determine if the user is authorized to make this request. diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php index 0a7f6dd..2307691 100644 --- a/app/Request/WxminiPayRequest.php +++ b/app/Request/WxminiPayRequest.php @@ -14,45 +14,25 @@ class WxminiPayRequest extends BaseFormRequest public function rules(): array { return [ - 'c_attitude' => 'required|nonempty|integer', - 'c_service' => 'required|nonempty|integer', - 'c_quality' => 'required|nonempty|integer', - 'content' => 'required|nonempty|strlen:15,150', - 'user_id' => 'required|nonempty|integer|exists:ims_cjdc_user,id', - 'service_personnel_id' => 'required|nonempty|integer|exists_enable:lanzu_service_personnel,id,status=1|not_equal:user_id,lanzu_service_personnel,id,user_id', - 'market_id' => 'required|nonempty|integer|exists:ims_cjdc_market,id', + 'order_id' => 'required|nonempty|integer', + 'type' => 'required|nonempty|integer', + 'openid' => 'required|nonempty', ]; } public function messages(): array { return [ - 'user_id.exists' => ':attribute不存在', - 'service_personnel_id.exists' => ':attribute不存在', - 'market_id.exists' => ':attribute不存在', - 'user_id.*' => ':attribute信息不正确', - 'service_personnel_id.exists_enable' => ':attribute不存在或被禁用', - 'service_personnel_id.not_equal' => ':attribute不能是自己', - 'service_personnel_id.*' => ':attribute信息不正确', - 'market_id.*' => ':attribute信息不正确', - 'c_attitude.*' => ':attribute信息不正确', - 'c_service.*' => ':attribute信息不正确', - 'c_quality.*' => ':attribute信息不正确', - 'content.strlen' => ':attribute字数限制在:min~:max字', - 'content.*' => ':attribute信息不正确', + '*.*' => ':attribute 参数异常', ]; } public function attributes(): array { return [ - 'user_id' => '用户', - 'service_personnel_id' => '服务专员', - 'market_id' => '服务专员市场', - 'c_attitude' => '服务态度评分', - 'c_service' => '服务值评分', - 'c_quality' => '服务质量评分', - 'content' => '服务评价内容', + 'order_id' => '订单', + 'type' => '订单类型', + 'openid' => '用户标识', ]; } } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 374631e..321c1f7 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -72,7 +72,7 @@ class OrderService implements OrderServiceInterface $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); $dataMain['time_add'] = $currentTime; - $dataMain['pay_time'] = date('Y-m-d H:i:s', $currentTime); + $dataMain['pay_time'] = ''; $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY; $dataMain['code'] = $dataMain['global_order_id']; $dataMain['jj_note'] = ''; diff --git a/composer.json b/composer.json index dfc0c2b..0e16cf6 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,8 @@ "alibabacloud/iot": "^1.8", "hyperf/amqp": "^2.0", "hyperf/snowflake": "^2.0", - "ext-bcmath": "*" + "ext-bcmath": "*", + "overtrue/wechat": "~4.0" }, "require-dev": { "swoole/ide-helper": "^4.5", diff --git a/config/config.php b/config/config.php index c5ce284..c67f910 100644 --- a/config/config.php +++ b/config/config.php @@ -28,7 +28,14 @@ return [ LogLevel::WARNING, ], ], - - 'site_host'=>'http://store.api.lanzulive.com/' + 'site_host'=> env('SITE_HOST', ''), + 'wxpay' => [ + 'app_id' => env('APP_ID',''), + 'mch_id' => env('MCH_ID',''), + 'key' => env('APP_SECRET',''), + 'cert_path' => env('CERT_PATH',''), + 'key_path' => env('KEY_PATH',''), + 'notify_url' => env('NOTIFY_URL',''), + ] ]; diff --git a/config/routes.php b/config/routes.php index dfdf5ab..2393433 100644 --- a/config/routes.php +++ b/config/routes.php @@ -42,5 +42,6 @@ Router::addGroup('/v1/',function (){ //小程序支付相关 Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); + Router::post('notify/wxmini', 'App\Controller\NotifyController@wxmini'); }); \ No newline at end of file From f6aea0af8cf1bd56abbf8e807b3307b04c52f651 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 19:49:20 +0800 Subject: [PATCH 28/72] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E8=BF=94=E5=9B=9E=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 8 +++++++- app/Controller/NotifyController.php | 8 +++++++- app/Controller/OrderController.php | 5 +++-- app/Controller/PaymentController.php | 2 +- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index f6dde1c..eba612a 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -37,4 +37,10 @@ class ErrorCode extends AbstractConstants /** * @Message("Upload failure!") */ - const UPLOAD_INVALID = 200;} + const UPLOAD_INVALID = 200; + + /** + * @Message("Order failure!") + */ + const ORDER_FAILURE = 300; +} diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 02aa0a3..177a84d 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -6,8 +6,14 @@ use App\Constants\LogLabel; class NotifyController extends BaseController { - public function wxmini() + public function wxminiOnline() { + // 获取参数 + + // 查询订单 + + // 开始处理 + $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, json_encode($this->request->input()) diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index 89a1cad..ff18506 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -2,6 +2,7 @@ namespace App\Controller; +use App\Constants\ErrorCode; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; @@ -20,8 +21,8 @@ class OrderController extends BaseController { $orderMainId = $this->orderService->addOnlineOrder($request->validated()); if (!is_int($orderMainId)) { - return $this->w7result(500, (string)$orderMainId); + return $this->result(ErrorCode::ORDER_FAILURE, '', $orderMainId); } - return $this->w7result(200, (string)$orderMainId); + return $this->success(['order_id' => $orderMainId]); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 29b88e3..50202b7 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -34,7 +34,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100), - 'notify_url' => config('site_host') . '/v1/notify/wxmini', + 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); From 6a485e3a16853ff6c89262a295eefa8ffc7c004b Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 20:09:12 +0800 Subject: [PATCH 29/72] =?UTF-8?q?=E6=94=AF=E4=BB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Constants/ErrorCode.php | 5 +++++ app/Controller/PaymentController.php | 9 +++++++-- app/Request/WxminiPayRequest.php | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/Constants/ErrorCode.php b/app/Constants/ErrorCode.php index eba612a..9ec3ba5 100644 --- a/app/Constants/ErrorCode.php +++ b/app/Constants/ErrorCode.php @@ -43,4 +43,9 @@ class ErrorCode extends AbstractConstants * @Message("Order failure!") */ const ORDER_FAILURE = 300; + + /** + * @Message("Pay failure!") + */ + const PAY_FAILURE = 400; } diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 50202b7..da331a2 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -2,6 +2,7 @@ namespace App\Controller; +use App\Constants\ErrorCode; use App\Model\OrderMain; use App\Model\Users; use App\Request\WxminiPayRequest; @@ -22,12 +23,16 @@ class PaymentController extends BaseController // 待支付的,类型一致的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() - ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'type' => $data['type'], 'id' => $data['order_id']]) + ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { - return $this->result(200, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + if (floatval($orderMain->money) != floatval($data['money'])) { + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单金额有误'); } $result = $app->order->unify([ diff --git a/app/Request/WxminiPayRequest.php b/app/Request/WxminiPayRequest.php index 2307691..633a9f5 100644 --- a/app/Request/WxminiPayRequest.php +++ b/app/Request/WxminiPayRequest.php @@ -15,8 +15,8 @@ class WxminiPayRequest extends BaseFormRequest { return [ 'order_id' => 'required|nonempty|integer', - 'type' => 'required|nonempty|integer', 'openid' => 'required|nonempty', + 'money' => 'required|nonempty', ]; } @@ -31,7 +31,7 @@ class WxminiPayRequest extends BaseFormRequest { return [ 'order_id' => '订单', - 'type' => '订单类型', + 'money' => '订单金额', 'openid' => '用户标识', ]; } From 3e95c80dd031f0ac96bbfa59c1a32bfafda4528c Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 20:27:22 +0800 Subject: [PATCH 30/72] =?UTF-8?q?=E6=94=AF=E4=BB=98=E8=8E=B7=E5=8F=96jsapi?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index da331a2..efde0a2 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -24,17 +24,13 @@ class PaymentController extends BaseController // 待支付的,类型一致的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) - ->where('time', '<=', date('Y-m-d H:i:s', (time()-900))) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); } - if (floatval($orderMain->money) != floatval($data['money'])) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单金额有误'); - } - $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, From 91f96c88214c6b10af4d26e126d794ff4d830c29 Mon Sep 17 00:00:00 2001 From: weigang Date: Wed, 12 Aug 2020 21:16:12 +0800 Subject: [PATCH 31/72] =?UTF-8?q?=E6=8B=86=E5=88=86=E5=A4=96=E5=8D=96?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=92=8C=E5=BD=93=E9=9D=A2=E6=94=AF=E4=BB=98?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 77 +++++++++++++++++++++++++--- app/Controller/PaymentController.php | 35 +++++++++++-- config/routes.php | 6 ++- 3 files changed, 105 insertions(+), 13 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 177a84d..4794fce 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -3,20 +3,81 @@ namespace App\Controller; use App\Constants\LogLabel; +use App\Model\OrderMain; +use EasyWeChat\Factory; +use Hyperf\Guzzle\CoroutineHandler; class NotifyController extends BaseController { public function wxminiOnline() { - // 获取参数 - - // 查询订单 + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; - // 开始处理 + // 通知回调,进行业务处理 + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - json_encode($this->request->input()) - ); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + }); + + $response->send(); + } + + public function wxminiOffline() + { + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 通知回调,进行业务处理 + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_OFFLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + }); + + $response->send(); } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index efde0a2..d4189dd 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -4,7 +4,6 @@ namespace App\Controller; use App\Constants\ErrorCode; use App\Model\OrderMain; -use App\Model\Users; use App\Request\WxminiPayRequest; use EasyWeChat\Factory; @@ -13,7 +12,7 @@ use Hyperf\Guzzle\CoroutineHandler; class PaymentController extends BaseController { - public function wxminiPay(WxminiPayRequest $request){ + public function wxminiPayOnline(WxminiPayRequest $request){ $data = $request->validated(); @@ -21,7 +20,7 @@ class PaymentController extends BaseController $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; - // 待支付的,类型一致的,未超时(15min,900sec)的订单 + // 待支付的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) @@ -43,4 +42,34 @@ class PaymentController extends BaseController return $this->success($result); } + public function wxminiPayOffline(WxminiPayRequest $request){ + + $data = $request->validated(); + + $config = config('wxpay'); + $app = Factory::payment($config); + $app['guzzle_handler'] = CoroutineHandler::class; + + // 待支付的,未超时(15min,900sec)的订单 + $orderMain = OrderMain::query() + ->where(['dm_state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + } + + $result = $app->order->unify([ + 'body' => '懒族生活 - 当面支付', + 'out_trade_no' => $orderMain->global_order_id, + 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', + 'trade_type' => 'JSAPI', + 'openid' => $data['openid'], + ]); + + return $this->success($result); + } + } \ No newline at end of file diff --git a/config/routes.php b/config/routes.php index 2393433..266122f 100644 --- a/config/routes.php +++ b/config/routes.php @@ -41,7 +41,9 @@ Router::addGroup('/v1/',function (){ Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); //小程序支付相关 - Router::post('wxmini/pay', 'App\Controller\PaymentController@wxminiPay'); - Router::post('notify/wxmini', 'App\Controller\NotifyController@wxmini'); + Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); + Router::post('wxminipay/offline', 'App\Controller\PaymentController@wxminiPayOffline'); + Router::post('notify/wxminionline', 'App\Controller\NotifyController@wxminiOnline'); + Router::post('notify/wxminioffline', 'App\Controller\NotifyController@wxminiOffline'); }); \ No newline at end of file From 75f9eed5ceb75acb4d55ad31375ec597a5eb11c0 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 09:22:48 +0800 Subject: [PATCH 32/72] =?UTF-8?q?mark=EF=BC=9Abcmul=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E7=9A=84scale=E4=B8=8D=E8=B5=B7=E4=BD=9C=E7=94=A8=EF=BC=8C?= =?UTF-8?q?=E5=BE=97=E6=89=8B=E5=86=990?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index d4189dd..ff5159e 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -27,13 +27,13 @@ class PaymentController extends BaseController ->first(); if (empty($orderMain)) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, $data,'订单不存在或已失效'); } $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], From c2ae7d892e72dd03071a1bf9d76af99021481446 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 10:01:10 +0800 Subject: [PATCH 33/72] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 ++++ app/Controller/PaymentController.php | 10 ++++++++-- app/Service/OrderService.php | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 4794fce..7845876 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -40,6 +40,10 @@ class NotifyController extends BaseController // return true; } + + // 修改订单、子订单状态 + + // 更新销量、商品库存,新增月销数据 }); $response->send(); diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index ff5159e..e0c850c 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,6 +39,9 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); + $result['sign_type'] = 'MD5'; + $result['timestamp'] = time(); + return $this->success($result); } @@ -57,18 +60,21 @@ class PaymentController extends BaseController ->first(); if (empty($orderMain)) { - return $this->result(ErrorCode::PAY_FAILURE, ['order_id' => $data['order_id']],'订单不存在或已失效'); + return $this->result(ErrorCode::PAY_FAILURE, $data,'订单不存在或已失效'); } $result = $app->order->unify([ 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100), + 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); + $result['sign_type'] = 'MD5'; + $result['timestamp'] = time(); + return $this->success($result); } diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 321c1f7..de1c925 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -83,8 +83,7 @@ class OrderService implements OrderServiceInterface // 统计订单中所有店铺当日订单数,做店铺订单序号 $countsArr = Order::query() - ->selectRaw('COUNT(*) AS count') - ->select('id') + ->selectRaw('id, COUNT(*) AS count') ->whereIn('store_id', explode(',', $dataMain['store_ids'])) ->where(['type' => OrderMain::ORDER_TYPE_ONLINE]) ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]) @@ -93,6 +92,7 @@ class OrderService implements OrderServiceInterface $storeOrderCounts = []; foreach ($countsArr as $key => &$row) { + var_dump('row', $row); $storeOrderCounts[$row['id']] = $row['count']; } From 21a773b481b5801cacd83da6922bc41fc5c86539 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 10:28:47 +0800 Subject: [PATCH 34/72] =?UTF-8?q?=E5=9B=9E=E8=B0=83=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 63 ++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 7845876..289c578 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -5,7 +5,9 @@ namespace App\Controller; use App\Constants\LogLabel; use App\Model\OrderMain; use EasyWeChat\Factory; +use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; +use Exception; class NotifyController extends BaseController { @@ -18,32 +20,55 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); - - // 查询订单 - $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) - ->first(); - - if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + Db::beginTransaction(); + try { $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + $message ); - // return true; - } + // 查询订单 + $orderMain = OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) + ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->first(); + + if (empty($orderMain)) { + // 去查一下微信订单 + $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $wxOrder + ); + + // return true; + } + + // 修改订单、子订单状态 + $currentTime = time(); + $orderMain->state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->time_pay = $currentTime; + $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); + $orderMain->save(); + + // 更新销量、商品库存,新增月销数据 - // 修改订单、子订单状态 + // 喇叭通知,兼容旧音响,MQTT+IOT + + // 公众号模板消息 + + // 打印订单 + + Db::commit(); + return true; + + } catch (Exception $e) { + + Db::rollBack(); + } - // 更新销量、商品库存,新增月销数据 }); $response->send(); From 36cdb8df88cd245d003f55247e8b0cb2bf548968 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 12:34:39 +0800 Subject: [PATCH 35/72] =?UTF-8?q?=E6=94=AF=E4=BB=98=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=EF=BC=8C=E9=87=8D=E6=96=B0=E5=8A=A0=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 38 +++++++++++++++++++++++++--- app/Service/OrderService.php | 1 - config/config.php | 2 +- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index e0c850c..a411185 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,10 +39,42 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); - $result['sign_type'] = 'MD5'; - $result['timestamp'] = time(); + $parameters = [ + 'appId' => $result['appid'], + 'timeStamp' => '' . time() . '', + 'nonceStr' => uniqid(), + 'package' => 'prepay_id=' . $result['prepay_id'], + 'signType' => 'MD5' + ]; + + //签名步骤一:按字典序排序参数 + ksort($parameters); + $string = $this->formatBizQueryParaMap($parameters, false); + //签名步骤二:在string后加入KEY + $string = $string . "&key=" . $config['key']; + //签名步骤三:MD5加密 + $string = md5($string); + //签名步骤四:所有字符转为大写 + $parameters['paySign'] = strtoupper($string); + + return $this->success($parameters); + } - return $this->success($result); + ///作用:格式化参数,签名过程需要使用 + private function formatBizQueryParaMap($paraMap, $urlencode) { + $buff = ""; + ksort($paraMap); + foreach ($paraMap as $k => $v) { + if ($urlencode) { + $v = urlencode($v); + } + $buff .= $k . "=" . $v . "&"; + } + $reqPar = null; + if (strlen($buff) > 0) { + $reqPar = substr($buff, 0, strlen($buff) - 1); + } + return $reqPar; } public function wxminiPayOffline(WxminiPayRequest $request){ diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index de1c925..54468a9 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -92,7 +92,6 @@ class OrderService implements OrderServiceInterface $storeOrderCounts = []; foreach ($countsArr as $key => &$row) { - var_dump('row', $row); $storeOrderCounts[$row['id']] = $row['count']; } diff --git a/config/config.php b/config/config.php index c67f910..7e8d490 100644 --- a/config/config.php +++ b/config/config.php @@ -32,7 +32,7 @@ return [ 'wxpay' => [ 'app_id' => env('APP_ID',''), 'mch_id' => env('MCH_ID',''), - 'key' => env('APP_SECRET',''), + 'key' => env('MCH_KEY',''), 'cert_path' => env('CERT_PATH',''), 'key_path' => env('KEY_PATH',''), 'notify_url' => env('NOTIFY_URL',''), From 8af4a94909af7c9ee8cc5da03e0b683d38055b50 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 13:05:49 +0800 Subject: [PATCH 36/72] =?UTF-8?q?=E4=B8=8B=E5=8D=95=E6=94=AF=E4=BB=98?= =?UTF-8?q?=EF=BC=9A=E7=BA=BF=E4=B8=8A=E3=80=81=E7=BA=BF=E4=B8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 81 ++++++++++++++++++---------- 1 file changed, 52 insertions(+), 29 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index a411185..f8d36fd 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -39,6 +39,7 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); + // 返回支付参数给前端 $parameters = [ 'appId' => $result['appid'], 'timeStamp' => '' . time() . '', @@ -47,36 +48,11 @@ class PaymentController extends BaseController 'signType' => 'MD5' ]; - //签名步骤一:按字典序排序参数 - ksort($parameters); - $string = $this->formatBizQueryParaMap($parameters, false); - //签名步骤二:在string后加入KEY - $string = $string . "&key=" . $config['key']; - //签名步骤三:MD5加密 - $string = md5($string); - //签名步骤四:所有字符转为大写 - $parameters['paySign'] = strtoupper($string); + $parameters['paySign'] = $this->signture($parameters, $config['key']); return $this->success($parameters); } - ///作用:格式化参数,签名过程需要使用 - private function formatBizQueryParaMap($paraMap, $urlencode) { - $buff = ""; - ksort($paraMap); - foreach ($paraMap as $k => $v) { - if ($urlencode) { - $v = urlencode($v); - } - $buff .= $k . "=" . $v . "&"; - } - $reqPar = null; - if (strlen($buff) > 0) { - $reqPar = substr($buff, 0, strlen($buff) - 1); - } - return $reqPar; - } - public function wxminiPayOffline(WxminiPayRequest $request){ $data = $request->validated(); @@ -104,10 +80,57 @@ class PaymentController extends BaseController 'openid' => $data['openid'], ]); - $result['sign_type'] = 'MD5'; - $result['timestamp'] = time(); + // 返回支付参数给前端 + $parameters = [ + 'appId' => $result['appid'], + 'timeStamp' => '' . time() . '', + 'nonceStr' => uniqid(), + 'package' => 'prepay_id=' . $result['prepay_id'], + 'signType' => 'MD5' + ]; + + $parameters['paySign'] = $this->signture($parameters, $config['key']); + + return $this->success($parameters); + } + + /** + * 支付参数加签 + * @param $parameters + * @param $key + * @return string + */ + private function signture($parameters, $key) + { + // 按字典序排序参数 + ksort($parameters); + + // http_query + $queryParams = $this->http_query($parameters); + + // 加入KEY + $queryParams = $queryParams . "&key=" . $key; + + // MD5加密 + $queryParams = md5($queryParams); + + // 字符转为大写 + return strtoupper($queryParams); + } + + /** + * 参数转为http query字串 + * @param $parameters + * @return string + */ + private function http_query($parameters) { + + $http_query = []; + foreach ($parameters as $key => $value) { + $http_query[] = $key.'='.$value; + } - return $this->success($result); + return implode('&', $http_query); } } \ No newline at end of file From 4a11341c8eded80b9983572ffed0913fc2941cda Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 14:32:19 +0800 Subject: [PATCH 37/72] =?UTF-8?q?=E6=94=AF=E4=BB=98=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index f8d36fd..a3ffbd6 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -33,8 +33,9 @@ class PaymentController extends BaseController $result = $app->order->unify([ 'body' => '懒族生活 - 外卖下单', 'out_trade_no' => $orderMain->global_order_id, - 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminiOnline', + // 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), + 'total_fee' => 1, + 'notify_url' => config('site_host') . '/v1/notify/wxminionline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); @@ -75,7 +76,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminiOffline', + 'notify_url' => config('site_host') . '/v1/notify/wxminioffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); From d6d23fdce496f1e1bdf703acf65e9cdf73e3945c Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 21:32:37 +0800 Subject: [PATCH 38/72] =?UTF-8?q?=E7=BA=BF=E4=B8=8A=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Amqp/Consumer/DevicOrderConsumer.php | 4 +- app/Controller/DeviceController.php | 4 +- app/Controller/NotifyController.php | 179 ++++++++-- app/Controller/OrderController.php | 10 + app/Controller/PaymentController.php | 1 - app/Controller/TestController.php | 35 +- app/Libs/FeiePrintClient.php | 307 ++++++++++++++++++ app/Model/OrderMain.php | 1 + app/Model/OrderSalesStatistic.php | 29 ++ app/Model/SystemConfig.php | 10 + app/Request/OrderOfflineRequest.php | 42 +++ app/Service/CouponService.php | 2 +- ...terface.php => CouponServiceInterface.php} | 2 +- app/Service/DeviceServiceImp.php | 45 ++- ...terFace.php => DeviceServiceInterface.php} | 3 +- app/Service/FeiePrintService.php | 226 +++++++++++++ app/Service/FeiePrintServiceInterface.php | 10 + app/Service/MiniprogramService.php | 147 +++++++++ app/Service/MiniprogramServiceInterface.php | 9 + app/Service/MqttServiceInterface.php | 21 ++ app/Service/MqttSpeakerService.php | 48 +++ app/Service/OrderService.php | 107 +++++- app/Service/OrderServiceInterface.php | 2 +- app/TaskWorker/MQTTClientTask.php | 40 ++- config/autoload/dependencies.php | 7 +- config/config.php | 5 +- config/routes.php | 1 + 27 files changed, 1240 insertions(+), 57 deletions(-) create mode 100644 app/Libs/FeiePrintClient.php create mode 100644 app/Model/OrderSalesStatistic.php create mode 100644 app/Model/SystemConfig.php create mode 100644 app/Request/OrderOfflineRequest.php rename app/Service/{CoupnoServiceInterface.php => CouponServiceInterface.php} (93%) rename app/Service/{DeviceServiceInterFace.php => DeviceServiceInterface.php} (68%) create mode 100644 app/Service/FeiePrintService.php create mode 100644 app/Service/FeiePrintServiceInterface.php create mode 100644 app/Service/MiniprogramService.php create mode 100644 app/Service/MiniprogramServiceInterface.php create mode 100644 app/Service/MqttServiceInterface.php create mode 100644 app/Service/MqttSpeakerService.php diff --git a/app/Amqp/Consumer/DevicOrderConsumer.php b/app/Amqp/Consumer/DevicOrderConsumer.php index f6e58bc..08a2d1c 100644 --- a/app/Amqp/Consumer/DevicOrderConsumer.php +++ b/app/Amqp/Consumer/DevicOrderConsumer.php @@ -6,7 +6,7 @@ namespace App\Amqp\Consumer; use App\Model\Order; use App\Model\SpeakerDevic; -use App\Service\DeviceServiceInterFace; +use App\Service\DeviceServiceInterface; use Hyperf\Amqp\Result; use Hyperf\Amqp\Annotation\Consumer; use Hyperf\Amqp\Message\ConsumerMessage; @@ -21,7 +21,7 @@ class DevicOrderConsumer extends ConsumerMessage { /** * @Inject - * @var DeviceServiceInterFace + * @var DeviceServiceInterface */ protected $deviceService; diff --git a/app/Controller/DeviceController.php b/app/Controller/DeviceController.php index ee315b3..d7ec213 100644 --- a/app/Controller/DeviceController.php +++ b/app/Controller/DeviceController.php @@ -4,7 +4,7 @@ namespace App\Controller; use Hyperf\Di\Annotation\Inject; use App\Exception\BusinessException; -use App\Service\DeviceServiceInterFace; +use App\Service\DeviceServiceInterface; use Hyperf\Validation\ValidationException; class DeviceController extends BaseController @@ -12,7 +12,7 @@ class DeviceController extends BaseController /** * @Inject - * @var DeviceServiceInterFace + * @var DeviceServiceInterface */ protected $deviceService; diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 289c578..3ac5cd3 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -3,46 +3,114 @@ namespace App\Controller; use App\Constants\LogLabel; +use App\Model\Goods; +use App\Model\Order; +use App\Model\OrderGoods; use App\Model\OrderMain; +use App\Model\OrderSalesStatistic; +use App\Model\SpecCombination; +use App\Model\Store; +use App\Model\SystemConfig; +use App\Service\DeviceServiceInterface; +use App\Service\FeiePrintServiceInterface; +use App\Service\MiniprogramService; +use App\Service\MqttServiceInterface; use EasyWeChat\Factory; use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; +use Hyperf\Di\Annotation\Inject; class NotifyController extends BaseController { + + /** + * @Inject + * @var MqttServiceInterface + */ + protected $mqttSpeakerService; + + /** + * @Inject + * @var DeviceServiceInterface + */ + protected $deviceService; + + /** + * @Inject + * @var MiniprogramService + */ + protected $miniprogramService; + + /** + * @Inject + * @var FeiePrintServiceInterface + */ + protected $feiePrintService; + public function wxminiOnline() { + $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; - + var_dump('inside'); // 通知回调,进行业务处理 - $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - - Db::beginTransaction(); - try { - - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); + Db::beginTransaction(); + try { + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + var_dump('message', $message); + // 支付失败或者通知失败 + if ( + empty($message) + || $message['return_code'] != 'SUCCESS' + || !isset($message['result_code']) + || $message['result_code'] != 'SUCCESS' + ) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + $fail('Unknown error but FAIL'); + } // 查询订单 $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_ONLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) + ->where([ + 'global_order_id' => $message['out_trade_no'], + 'type' => OrderMain::ORDER_TYPE_ONLINE, + 'state' => OrderMain::ORDER_STATE_UNPAY + ]) + ->where('time', '>=', date('Y-m-d H:i:s', (time() - 900))) ->first(); - + var_dump('$orderMain', $orderMain); + // 订单不存在 if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + $orderMain ); + // 去查一下微信订单,只处理未支付的情况 TODO 其他情况处理 + $wxOrder = $app->order->queryByOutTradeNumber($message['out_trade_no']); + // 查询成功 + if ($wxOrder['return_code'] == 'SUCCESS') { + if ($wxOrder['result_code'] == 'SUCCESS') { + // 看订单支付状态,处理未支付的情况,把订单处理成未支付 + if ($wxOrder['trade_state'] != 'NOTPAY') { + OrderMain::query() + ->where(['global_order_id' => $message['out_trade_no']]) + ->update(['state' => OrderMain::ORDER_STATE_UNPAY]); + + $fail('Order not paid'); + } + } + } + + + // return true; } @@ -53,25 +121,86 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); - // 更新销量、商品库存,新增月销数据 + $upOrder = Order::query() + ->where(['order_main_id' => $orderMain->id]) + ->update(['state' => OrderMain::ORDER_STATE_UNTAKE, 'pay_time' => $orderMain->pay_time]); + + // 更新商户销量 + $upStoreScore = Store::query() + ->whereIn('id', $orderMain->order_ids) + ->update(['score' => Db::raw('score+1')]); + + // 更新商品库存和销量 + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'createtime']) + ->where(['order_main_id' => $orderMain->id]) + ->get() + ->toArray(); + $orderGoods = OrderGoods::query()->select(['good_id AS id', 'number', 'combination_id']) + ->whereIn('order_id', array_values(array_column($orders, 'id'))) + ->get() + ->toArray(); + foreach ($orderGoods as $key => &$goodsItem) { + + $goods = Goods::find($goodsItem['id']); + + // 库存处理,有规格 + if ($goodsItem->combination_id) { + $combination = SpecCombination::find($goodsItem['combination_id']); + $combination->number = $combination->number - $goodsItem['number']; + $combination->save(); + } else { + $goods->inventory = $goods->inventory - $goodsItem['number']; + } + + $goods->sales = $goods->sales - $goodsItem['number']; + $goods->save(); + + } + + // 月销流水 + $statistics = []; + foreach ($orders as $key => & $order) { + $statistics[] = [ + 'money' => $order->money, + 'user_id' => $order->user_id, + 'store_id' => $order->store_id, + 'market_id' => $orderMain->market_id, + 'order_id' => $order->id, + 'createtime' => strtotime($order->pay_time), + ]; + } + + if (is_array($statistics) && !empty($statistics)) { + $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics); + } // 喇叭通知,兼容旧音响,MQTT+IOT + $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + var_dump($res); + $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + var_dump($res); // 公众号模板消息 + $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + var_dump($res); - // 打印订单 + // 打印订单,自动打印 TODO 后续优化调用逻辑 + $res = $this->feiePrintService->feiePrint($orderMain->order_num); + var_dump($res); - Db::commit(); - return true; + }); - } catch (Exception $e) { + var_dump('$response', $response); + Db::rollBack(); + $response->send(); - Db::rollBack(); - } + } catch (\EasyWeChat\Kernel\Exceptions\Exception $e) { - }); + var_dump($e->getMessage()); + Db::rollBack(); + + } - $response->send(); } public function wxminiOffline() diff --git a/app/Controller/OrderController.php b/app/Controller/OrderController.php index ff18506..f26045d 100644 --- a/app/Controller/OrderController.php +++ b/app/Controller/OrderController.php @@ -3,6 +3,7 @@ namespace App\Controller; use App\Constants\ErrorCode; +use App\Request\OrderOfflineRequest; use App\Request\OrderOnlineRequest; use Hyperf\Di\Annotation\Inject; use App\Service\OrderServiceInterface; @@ -25,4 +26,13 @@ class OrderController extends BaseController } return $this->success(['order_id' => $orderMainId]); } + + public function addOfflineOrder(OrderOfflineRequest $request) + { + $orderMainId = $this->orderService->addOfflineOrder($request->validated()); + if (!is_int($orderMainId)) { + return $this->result(ErrorCode::ORDER_FAILURE, '', $orderMainId); + } + return $this->success(['order_id' => $orderMainId]); + } } \ No newline at end of file diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index a3ffbd6..5047f27 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -65,7 +65,6 @@ class PaymentController extends BaseController // 待支付的,未超时(15min,900sec)的订单 $orderMain = OrderMain::query() ->where(['dm_state' => OrderMain::ORDER_STATE_UNPAY, 'id' => $data['order_id']]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) ->first(); if (empty($orderMain)) { diff --git a/app/Controller/TestController.php b/app/Controller/TestController.php index f69cea8..10fe872 100644 --- a/app/Controller/TestController.php +++ b/app/Controller/TestController.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Controller; +use App\Libs\FeiePrintClient; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Annotation\AutoController; use Hyperf\Utils\Coroutine; @@ -22,6 +23,7 @@ class TestController extends AbstractController { private $name = 'default action'; + protected $client = null; public function index1(RequestInterface $request) { @@ -37,14 +39,33 @@ class TestController extends AbstractController // $result = $client->handle("set"); - //$log = ApplicationContext::getContainer()->get(Log::class); - $log = $this->log; - - $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); - $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + // //$log = ApplicationContext::getContainer()->get(Log::class); + // $log = $this->log; + // + // $log->push(['test'=>1,'user_id'=>290,'msg'=>'order']); + // $log->event('t1',['test'=>1,'user_id'=>290,'msg'=>'order']); + // + // //$this->name = 'index1 action '. $result; + // return $this->name; - //$this->name = 'index1 action '. $result; - return $this->name; + $time = time(); + $msgInfo = array( + 'user' => '13161443713@163.com', + 'stime' => $time, + 'sig' => sha1('13161443713@163.com' . 'XsaHzgePdyWTfcMX' . $time), + 'apiname' => 'Open_printMsg', + 'sn' => '920527381', + 'content' => '1111', + 'times' => 1//打印次数 + ); + $this->client = new FeiePrintClient('api.feieyun.cn', 80); + if (!$this->client->post('/Api/Open/', $msgInfo)) { + return '12'; + } else { + //服务器返回的JSON字符串,建议要当做日志记录起来 + $result = $this->client->getContent(); + return $result; + } } public function index2(RequestInterface $request) diff --git a/app/Libs/FeiePrintClient.php b/app/Libs/FeiePrintClient.php new file mode 100644 index 0000000..a1b4789 --- /dev/null +++ b/app/Libs/FeiePrintClient.php @@ -0,0 +1,307 @@ +host = $host; + $this->port = $port; + } + function get($path, $data = false) { + $this->path = $path; + $this->method = 'GET'; + if ($data) { + $this->path .= '?'.$this->buildQueryString($data); + } + return $this->doRequest(); + } + function post($path, $data) { + $this->path = $path; + $this->method = 'POST'; + $this->postdata = $this->buildQueryString($data); + return $this->doRequest(); + } + function buildQueryString($data) { + $querystring = ''; + if (is_array($data)) { + foreach ($data as $key => $val) { + if (is_array($val)) { + foreach ($val as $val2) { + $querystring .= urlencode($key).'='.urlencode($val2).'&'; + } + } else { + $querystring .= urlencode($key).'='.urlencode($val).'&'; + } + } + $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & + } else { + $querystring = $data; + } + return $querystring; + } + function doRequest() { + if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { + switch($errno) { + case -3: + $this->errormsg = 'Socket creation failed (-3)'; + case -4: + $this->errormsg = 'DNS lookup failure (-4)'; + case -5: + $this->errormsg = 'Connection refused or timed out (-5)'; + default: + $this->errormsg = 'Connection failed ('.$errno.')'; + $this->errormsg .= ' '.$errstr; + $this->debug($this->errormsg); + } + return false; + } + socket_set_timeout($fp, $this->timeout); + $request = $this->buildRequest(); + $this->debug('Request', $request); + fwrite($fp, $request); + $this->headers = array(); + $this->content = ''; + $this->errormsg = ''; + $inHeaders = true; + $atStart = true; + while (!feof($fp)) { + $line = fgets($fp, 4096); + if ($atStart) { + $atStart = false; + if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { + $this->errormsg = "Status code line invalid: ".htmlentities($line); + $this->debug($this->errormsg); + return false; + } + $http_version = $m[1]; + $this->status = $m[2]; + $status_string = $m[3]; + $this->debug(trim($line)); + continue; + } + if ($inHeaders) { + if (trim($line) == '') { + $inHeaders = false; + $this->debug('Received Headers', $this->headers); + if ($this->headers_only) { + break; + } + continue; + } + if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { + continue; + } + $key = strtolower(trim($m[1])); + $val = trim($m[2]); + if (isset($this->headers[$key])) { + if (is_array($this->headers[$key])) { + $this->headers[$key][] = $val; + } else { + $this->headers[$key] = array($this->headers[$key], $val); + } + } else { + $this->headers[$key] = $val; + } + continue; + } + $this->content .= $line; + } + fclose($fp); + if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { + $this->debug('Content is gzip encoded, unzipping it'); + $this->content = substr($this->content, 10); + $this->content = gzinflate($this->content); + } + if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { + $cookies = $this->headers['set-cookie']; + if (!is_array($cookies)) { + $cookies = array($cookies); + } + foreach ($cookies as $cookie) { + if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { + $this->cookies[$m[1]] = $m[2]; + } + } + $this->cookie_host = $this->host; + } + if ($this->persist_referers) { + $this->debug('Persisting referer: '.$this->getRequestURL()); + $this->referer = $this->getRequestURL(); + } + if ($this->handle_redirects) { + if (++$this->redirect_count >= $this->max_redirects) { + $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; + $this->debug($this->errormsg); + $this->redirect_count = 0; + return false; + } + $location = isset($this->headers['location']) ? $this->headers['location'] : ''; + $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; + if ($location || $uri) { + $url = parse_url($location.$uri); + return $this->get($url['path']); + } + } + return true; + } + function buildRequest() { + $headers = array(); + $headers[] = "{$this->method} {$this->path} HTTP/1.0"; + $headers[] = "Host: {$this->host}"; + $headers[] = "User-Agent: {$this->user_agent}"; + $headers[] = "Accept: {$this->accept}"; + if ($this->use_gzip) { + $headers[] = "Accept-encoding: {$this->accept_encoding}"; + } + $headers[] = "Accept-language: {$this->accept_language}"; + if ($this->referer) { + $headers[] = "Referer: {$this->referer}"; + } + if ($this->cookies) { + $cookie = 'Cookie: '; + foreach ($this->cookies as $key => $value) { + $cookie .= "$key=$value; "; + } + $headers[] = $cookie; + } + if ($this->username && $this->password) { + $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); + } + if ($this->postdata) { + $headers[] = 'Content-Type: application/x-www-form-urlencoded'; + $headers[] = 'Content-Length: '.strlen($this->postdata); + } + $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; + return $request; + } + function getStatus() { + return $this->status; + } + function getContent() { + return $this->content; + } + function getHeaders() { + return $this->headers; + } + function getHeader($header) { + $header = strtolower($header); + if (isset($this->headers[$header])) { + return $this->headers[$header]; + } else { + return false; + } + } + function getError() { + return $this->errormsg; + } + function getCookies() { + return $this->cookies; + } + function getRequestURL() { + $url = 'https://'.$this->host; + if ($this->port != 80) { + $url .= ':'.$this->port; + } + $url .= $this->path; + return $url; + } + function setUserAgent($string) { + $this->user_agent = $string; + } + function setAuthorization($username, $password) { + $this->username = $username; + $this->password = $password; + } + function setCookies($array) { + $this->cookies = $array; + } + function useGzip($boolean) { + $this->use_gzip = $boolean; + } + function setPersistCookies($boolean) { + $this->persist_cookies = $boolean; + } + function setPersistReferers($boolean) { + $this->persist_referers = $boolean; + } + function setHandleRedirects($boolean) { + $this->handle_redirects = $boolean; + } + function setMaxRedirects($num) { + $this->max_redirects = $num; + } + function setHeadersOnly($boolean) { + $this->headers_only = $boolean; + } + function setDebug($boolean) { + $this->debug = $boolean; + } + function quickGet($url) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + if (isset($bits['query'])) { + $path .= '?'.$bits['query']; + } + $client = new HttpClient($host, $port); + if (!$client->get($path)) { + return false; + } else { + return $client->getContent(); + } + } + function quickPost($url, $data) { + $bits = parse_url($url); + $host = $bits['host']; + $port = isset($bits['port']) ? $bits['port'] : 80; + $path = isset($bits['path']) ? $bits['path'] : '/'; + $client = new HttpClient($host, $port); + if (!$client->post($path, $data)) { + return false; + } else { + return $client->getContent(); + } + } + function debug($msg, $object = false) { + if ($this->debug) { + print '
HttpClient Debug: '.$msg; + if ($object) { + ob_start(); + print_r($object); + $content = htmlentities(ob_get_contents()); + ob_end_clean(); + print '
'.$content.'
'; + } + print '
'; + } + } +} \ No newline at end of file diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index ee3840c..4972484 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -75,6 +75,7 @@ class OrderMain extends Model 'coupon_id2', 'uniacid', 'state', + 'dm_state', 'time', 'time_add', 'pay_time', diff --git a/app/Model/OrderSalesStatistic.php b/app/Model/OrderSalesStatistic.php new file mode 100644 index 0000000..a20edf8 --- /dev/null +++ b/app/Model/OrderSalesStatistic.php @@ -0,0 +1,29 @@ + 'required|nonempty|integer', + 'user_id' => 'required|nonempty|integer', + 'money' => 'required|nonempty', + ]; + } + + public function messages(): array + { + return [ + '*.*' => ':attribute 参数异常' + ]; + } + + public function attributes(): array + { + return [ + + ]; + } +} diff --git a/app/Service/CouponService.php b/app/Service/CouponService.php index f4f8af9..227d79b 100644 --- a/app/Service/CouponService.php +++ b/app/Service/CouponService.php @@ -6,7 +6,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Redis\Redis; use Hyperf\Utils\ApplicationContext; -class CouponService implements CoupnoServiceInterface +class CouponService implements CouponServiceInterface { /** diff --git a/app/Service/CoupnoServiceInterface.php b/app/Service/CouponServiceInterface.php similarity index 93% rename from app/Service/CoupnoServiceInterface.php rename to app/Service/CouponServiceInterface.php index 4e3d9a4..943eb38 100644 --- a/app/Service/CoupnoServiceInterface.php +++ b/app/Service/CouponServiceInterface.php @@ -4,7 +4,7 @@ namespace App\Service; -interface CoupnoServiceInterface +interface CouponServiceInterface { /** * 当前订单可用优惠券列表 diff --git a/app/Service/DeviceServiceImp.php b/app/Service/DeviceServiceImp.php index 2b4962c..16c9110 100644 --- a/app/Service/DeviceServiceImp.php +++ b/app/Service/DeviceServiceImp.php @@ -4,13 +4,14 @@ namespace App\Service; use App\Commons\Log; use App\Constants\LogLabel; +use App\Model\Order; use App\Model\SpeakerDevic; use App\Model\Store; use Hyperf\Di\Annotation\Inject; use Hyperf\Utils\ApplicationContext; use App\TaskWorker\AliIotTask; -class DeviceServiceImp implements DeviceServiceInterFace +class DeviceServiceImp implements DeviceServiceInterface { /** * @Inject @@ -54,13 +55,6 @@ class DeviceServiceImp implements DeviceServiceInterFace // 获取市场ID $market_id = Store::query()->where(['id' => $store_id])->value('market_id'); - // $sd = new SpeakerDevic; - // $sd->store_id = $store_id; - // $sd->device_name = $dev_name; - // $sd->market_id = $market_id; - // $sd->bind_time = time(); - // $sd->saveOrFail(); - $sd = SpeakerDevic::query()->updateOrCreate( ['store_id' => $store_id, 'device_name' => $dev_name], ['market_id' => $market_id, 'bind_time' => time(), 'is_bind' => SpeakerDevic::IS_BIND_YES] @@ -84,8 +78,9 @@ class DeviceServiceImp implements DeviceServiceInterFace /** * 发布语音消息 - * @param $store_id + * @param $dev_names * @param $msg + * @return bool */ public function pubMsgToStoreByDevName($dev_names, $msg) { @@ -96,6 +91,38 @@ class DeviceServiceImp implements DeviceServiceInterFace return true; } + public function pubMsgToStoreByOrderMainId($order_id, $is_main = true) + { + + // 获取订单 + $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); + if ($is_main) { + $orders = $orders->where(['order_main_id' => $order_id])->get()->toArray(); + } else { + $orders = $orders->where(['id' => $order_id])->get()->toArray(); + } + + if(empty($orders)) return; + + // 循环发送 + foreach ($orders as $k => &$order) { + + $device_names = SpeakerDevic::query() + ->select(['device_name']) + ->where(['store_id' => $order['store_id'], 'is_bind' => SpeakerDevic::IS_BIND_YES]) + ->get() + ->toArray(); + + $msg = "{\"msg\":\"到账".$order['money']."元\"}"; + foreach ($device_names as $key => $dev_name) { + $this->IOTService->pub($dev_name['device_name'], $msg); + } + } + + return true; + + } + /** * 当前设备是否已经被绑定 * @param $dev_name diff --git a/app/Service/DeviceServiceInterFace.php b/app/Service/DeviceServiceInterface.php similarity index 68% rename from app/Service/DeviceServiceInterFace.php rename to app/Service/DeviceServiceInterface.php index 15aa23b..68cd47c 100644 --- a/app/Service/DeviceServiceInterFace.php +++ b/app/Service/DeviceServiceInterface.php @@ -2,10 +2,11 @@ namespace App\Service; -interface DeviceServiceInterFace +interface DeviceServiceInterface { public function getListByStoreId($store_id); public function bindByStoreId($dev_name,$store_id); public function unbindById($bind_id); public function pubMsgToStoreByDevName($dev_names,$msg); + public function pubMsgToStoreByOrderMainId($order_id, $is_main = true); } \ No newline at end of file diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php new file mode 100644 index 0000000..b822175 --- /dev/null +++ b/app/Service/FeiePrintService.php @@ -0,0 +1,226 @@ +join('ims_cjdc_order as o','o.order_main_id', '=', 'm.id','inner') + ->join('ims_cjdc_order_goods as g','o.id','=', 'g.order_id','inner') + ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') + ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') + ->where('m.order_num', $order_num) + ->select("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") + ->order('s.id') + ->get(); + + $content = $this->printFormat($data, 14, 6, 3, 6); + $res = $this->printMsg($data[0]['sn'], $content, 1); + return ($res); + } + + /** + * [打印订单接口 Open_printMsg] + * @param [string] $sn [打印机编号sn] + * @param [string] $content [打印内容] + * @param [string] $times [打印联数] + * @return [string] [接口返回值] + */ + protected function printMsg($sn, $content, $times = 1) + { + $time = time(); //请求时间 + $msgInfo = array( + 'user' => self::USER, + 'stime' => $time, + 'sig' => sha1(self::USER . self::UKEY . $time), + 'apiname' => 'Open_printMsg', + 'sn' => $sn, + 'content' => $content, + 'times' => $times//打印次数 + ); + + $client = new FeiePrintClient(self::IP, self::PORT); + if (!$client->post(self::PATH, $msgInfo)) { + echo 'error'; + } else { + // 服务器返回的JSON字符串,建议要当做日志记录起来 + $result = $client->getContent(); + return $result; + } + } + + protected function printFormat($arr, $A, $B, $C, $D) + { + $orderInfo = '懒族生活
'; + $orderInfo .= '名称 单价 数量 金额
'; + $orderInfo .= '--------------------------------
'; + $shopname = ""; + $shopnum = 0; + foreach ($arr as $k5 => $v5) { + if ($shopname != $v5['shopname']) { + if ($shopname != "") { + $orderInfo .= '
'; + } + $shopnum++; + $orderInfo .= "(" . $shopnum . ")" .$v5['shopname'] . '
'; + $shopname = $v5['shopname']; + } + $name = $v5['name']; + if(!empty($v5['spec'])) { + $name .= "(规格:". $v5['spec'].")"; + }elseif (!empty($v5['good_unit'])){ + $name .= "(规格:". $v5['good_unit'].")"; + } + $price = $v5['money']; + $num = $v5['number']; + $prices = sprintf("%.2f",$v5['money']*$v5['number']); + $kw3 = ''; + $kw1 = ''; + $kw2 = ''; + $kw4 = ''; + $str = $name; + $blankNum = $A;//名称控制为14个字节 + $lan = mb_strlen($str,'utf-8'); + $m = 0; + $j=1; + $blankNum++; + $result = array(); + if(strlen($price) < $B){ + $k1 = $B - strlen($price); + for($q=0;$q<$k1;$q++){ + $kw1 .= ' '; + } + $price = $kw1.$price; + } + if(strlen($num) < $C){ + $k2 = $C - strlen($num); + for($q=0;$q<$k2;$q++){ + $kw2 .= ' '; + } + $num = $kw2.$num; + } + if(strlen($prices) < $D){ + $k3 = $D - strlen($prices); + for($q=0;$q<$k3;$q++){ + $kw4 .= ' '; + } + $prices = $kw4.$prices; + } + for ($i=0;$i<$lan;$i++){ + $new = mb_substr($str,$m,$j,'utf-8'); + $j++; + if(mb_strwidth($new,'utf-8')<$blankNum) { + if($m+$j>$lan) { + $m = $m+$j; + $tail = $new; + $lenght = iconv("UTF-8", "GBK//IGNORE", $new); + $k = $A - strlen($lenght); + for($q=0;$q<$k;$q++){ + $kw3 .= ' '; + } + if($m==$j){ + $tail .= $kw3.' '.$price.' '.$num.' '.$prices; + }else{ + $tail .= $kw3.'
'; + } + break; + }else{ + $next_new = mb_substr($str,$m,$j,'utf-8'); + if(mb_strwidth($next_new,'utf-8')<$blankNum) continue; + else{ + $m = $i+1; + $result[] = $new; + $j=1; + } + } + } + } + $head = ''; + foreach ($result as $key=>$value) { + if($key < 1){ + $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); + $v_lenght = strlen($v_lenght); + if($v_lenght == 13) $value = $value." "; + $head .= $value.' '.$price.' '.$num.' '.$prices; + }else{ + $head .= $value.'
'; + } + } + $orderInfo .= $head.$tail; + if(!empty($v5['o_note'])){ + $orderInfo .= '备注:'.$v5['o_note'].'
'; + } + } + // $time = date('Y-m-d H:i:s', time()); + $orderInfo .= '--------------------------------
'; + if ($arr[0]['box_money'] > 0) { + $kw5 = ''; + $len = 24 - strlen($arr[0]['box_money']); + for ($q = 0; $q < $len; $q++) { + $kw5 .= ' '; + } + $orderInfo .= '包装费:' . $kw5 . $arr[0]['box_money'] . '
'; + } + if($arr[0]['dada_fee'] > 0){ + $kw5 = ''; + $len = 24 - strlen($arr[0]['dada_fee']); + for ($q = 0; $q < $len; $q++) { + $kw5 .= ' '; + } + $orderInfo .= '配送费:'.$kw5.$arr[0]['dada_fee'].'
'; + } + if($arr[0]['yhq_money2'] > 0){ + $yhq_money2 = sprintf("%.2f",$arr[0]['yhq_money2']); + $kw6 = ''; + $len = 25 - strlen($yhq_money2); + for ($q = 0; $q < $len; $q++) { + $kw6 .= ' '; + } + $orderInfo .= '红包:'.$kw6.'-'.$yhq_money2.'
'; + } + $total = '合计:'.$arr[0]['m_money']; + $user_name = $arr[0]['user_name']; + if(strlen($user_name)>18){ + $user_name=substr($user_name,0,18).'...'; + } + $str = $user_name . $total; + $kw5 = ''; + $lenght = iconv("UTF-8", "GBK//IGNORE", $str); + $total_len = 32 - strlen($lenght); + for ($q = 0; $q < $total_len; $q++) { + $kw5 .= ' '; + } + $total_str = $user_name.$kw5.$total; + $orderInfo .= $total_str.'
'; + $orderInfo .= '送货地点:' . $arr[0]['address'] . '
'; + $tel = substr_replace( $arr[0]['tel'], '****', 3, 4); + $orderInfo .= '联系电话:' . $tel . '
'; + $orderInfo .= '配送时间:' . $arr[0]['ps_time'] . '
'; + if(!empty($arr[0]['note'])){ + $orderInfo .= '备注:'.$arr[0]['note'].'

'; + } + //$orderInfo .= 'http://www.feieyun.com';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码 + return $orderInfo; + } +} \ No newline at end of file diff --git a/app/Service/FeiePrintServiceInterface.php b/app/Service/FeiePrintServiceInterface.php new file mode 100644 index 0000000..5e67cdc --- /dev/null +++ b/app/Service/FeiePrintServiceInterface.php @@ -0,0 +1,10 @@ + '微信支付', '2' => '余额支付', '3' => '积分支付', '4' => '货到付款']; + $address_store = $order['address'] . ';' .$order['name']. ';'. substr_replace($order['tel'],'****',3,4); + $address = $order['address'] . ';' .$order['name']. ';'. $order['tel']; + + // 查询子订单,用于发消息给商户 + $order_children = Order::query()->select(['id', 'order_num', 'store_id', 'money', 'time']) + ->where(['order_main_id' => $order_main_id]) + ->get() + ->toArray(); + + $goods_temp_all = []; + foreach ($order_children as $key => &$item) { + + $item = (array)$item; + + // 订单商品 + $order_goods = OrderGoods::query()->select(['name', 'number', 'spec', 'good_unit']) + ->where(['order_id' => $item['id']]) + ->get() + ->toArray(); + + $goods_temp = []; + foreach ($order_goods as $k => &$goods) { + array_push($goods_temp, $goods['name']."*".$goods['number']."/".($goods['spec']?:$goods['good_unit'])); + array_push($goods_temp_all, $goods['name']."*".$goods['number']."/".($goods['spec']?:$goods['good_unit'])); + } + + // 商户/门店的openid + $store = Store::query()->select(['id', 'name']) + ->where(['id' => $item['store_id']]) + ->first()->toArray(); + $store['openid'] = Users::query() + ->where(['id' => $store['user_id']]) + ->value('openid'); + + // 模板数据 + $data_store = [ + 'first' => ['您有新的外卖订单!订单编号:'.$item['order_num'], '#ff0000'], + 'keyword' => [ + ["您的外卖订单详情:\r\n".implode(";\r\n",$goods_temp), '#ff0000'], + $item['money'], + $payTypes[$order['pay_type']], + $item['time']?:'', + $address_store, + ], + 'remark' => [$order['note'], '#4e6ef2'] + ]; + + $ret_store = $this->sendTempMsg($store['openid'], '-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c',$data_store); + } + + // 模板数据发送消息给用户 + $data_user = [ + 'first' => '您好,下单成功!订单编号:'.$order['order_num'], + 'keyword' => [ + implode(";\r\n", $goods_temp_all), + $order['money'], + $payTypes[$order['pay_type']], + date('Y-m-d H:i:s', $order['time_add']), + $address, + ], + 'remark' => '感谢您的光临,欢迎下次再来!' + ]; + + // 获取用户openid,发送给用户 + $user_openid = Users::query()->where(['id' => $order['user_id']])->value('openid'); + $ret_user = $this->sendTempMsg($user_openid,'-M7DG_ACwJxqdAvyvJuAnPpx4xaLf3VkkN0fckno71c', $data_user); + + } + + public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']) + { + // 先拼个基础的 + $template = [ + 'touser' => $openid, + 'mp_template_msg' => [ + 'appid' => env('OFFICIAL_APP_ID'), + 'template_id' => $template_id, + 'url' => $redirect_url, + ] + ]; + + // 看看有没有小程序跳转的要求 + if ( is_array($applet_config)&&!empty($applet_config)&&!empty($applet_config['appid']) ) { + $template['mp_template_msg']['miniprogram'] = $applet_config; + } + + // 重点来了,拼接关键数据data + if (!is_array($data)) { # 数组都不是,请回去 + return false; + } + + if (is_array($data['first'])) { + $template['mp_template_msg']['data']['first']['value'] = $data['first'][0] ?? ''; + $template['mp_template_msg']['data']['first']['color'] = $data['first'][1] ?? ''; + } else { + $template['mp_template_msg']['data']['first']['value'] = $data['first']; + } + + if (isset($data['keyword'])&&is_array($data['keyword'])) { + foreach ($data['keyword'] as $key => &$keyword) { + $index = $key+1; + + if (is_array($keyword)) { + $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword[0] ?? ''; + $template['mp_template_msg']['data']['keyword'.$index]['color'] = $keyword[1] ?? ''; + } else { + $template['mp_template_msg']['data']['keyword'.$index]['value'] = $keyword; + } + + } + } + + if (is_array($data['remark'])) { + $template['mp_template_msg']['data']['remark']['value'] = $data['remark'][0] ?? ''; + $template['mp_template_msg']['data']['remark']['color'] = $data['remark'][1] ?? ''; + } else { + $template['mp_template_msg']['data']['remark']['value'] = $data['remark']; + } + + $app = Factory::miniProgram(config('wxtempmsg')); + $app->uniform_message->send($template); + } + +} \ No newline at end of file diff --git a/app/Service/MiniprogramServiceInterface.php b/app/Service/MiniprogramServiceInterface.php new file mode 100644 index 0000000..b1ebe72 --- /dev/null +++ b/app/Service/MiniprogramServiceInterface.php @@ -0,0 +1,9 @@ + '', 'pagepath' => '']); +} \ No newline at end of file diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php new file mode 100644 index 0000000..203b908 --- /dev/null +++ b/app/Service/MqttServiceInterface.php @@ -0,0 +1,21 @@ +select(['id','order_num','money', 'pay_type', 'store_id', 'type']); + if ($isMain) { + $orders = $orders->where(['order_main_id' => $orderId])->get()->toArray(); + } else { + $orders = $orders->where(['id' => $orderId])->get()->toArray(); + } + + if(empty($orders)) return; + + // 循环发送 + foreach ($orders as $k => &$order) { + $order['template'] = "懒族生活支付到账".floatval($order['money'])."元"; + // 获取终端ID + $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); + // 发布订阅消息 + $this->pubToMqtt($order['template'], self::TOPIC, $order['to_client_id']); + } + } + + /** + * @inheritDoc + */ + public function pubToMqtt($message, $topic, $toClientId) + { + $task = ApplicationContext::getContainer()->get(MQTTClientTask::class); + $task->publish($message, $topic, $toClientId); + } +} \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 54468a9..2efb470 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -22,7 +22,7 @@ class OrderService implements OrderServiceInterface /** * @Inject - * @var CoupnoServiceInterface + * @var CouponServiceInterface */ protected $couponService; @@ -349,9 +349,110 @@ class OrderService implements OrderServiceInterface /** * @inheritDoc */ - public function addOfflineOrder() + public function addOfflineOrder($data) { - // TODO: Implement addOfflineOrder() method. + Db::beginTransaction(); + try { + // 主订单数据 + $dataMain = []; + + // 获取分布式全局ID + $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class); + $globalRrderId = $generator->generate(); + + // 主订单插入数据 + $currentTime = time(); + $dataMain = [ + 'delivery_no' => '', + 'dada_fee' => 0, + 'market_id' => 0, + 'box_money' => 0, + 'ps_money' => 0, + 'mj_money' => 0, + 'xyh_money' => 0, + 'yhq_money' => 0, + 'yhq_money2' => 0, + 'zk_money' => 0, + 'tel' => '', + 'name' => '', + 'address' => '', + 'area' => '', + 'lat' => '', + 'lng' => '', + 'note' => '', + 'form_id' => '', + 'form_id2' => '', + 'delivery_time' => '', + 'order_type' => 0, + 'coupon_id' => 0, + 'coupon_id2' => 0, + 'store_list' => '', + 'receive_coupon_ids' => '', + 'type' => OrderMain::ORDER_TYPE_OFFLINE, + 'time' => date('Y-m-d H:i:s', $currentTime), + 'time_add' => $currentTime, + 'pay_time' => '', + 'pay_type' => OrderMain::ORDER_PAY_WX, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'dm_state' => OrderMain::ORDER_STATE_UNPAY, + 'code' => $globalRrderId, + 'jj_note' => '', + 'uniacid' => 2, + 'order_num' => 'dm'.date('YmdHis', time()) . rand(1111, 9999), + 'money' => $data['money'], + 'user_id' => $data['user_id'], + 'store_ids' => $data['store_id'], + 'global_order_id' => $globalRrderId, + ]; + + // 主订单模型保存 + $orderMain = OrderMain::create($dataMain); + $orderMainId = $orderMain->id; + + // 子订单模型保存 + $dataChild = [ + 'uniacid' => 1, + 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999), + 'user_id' => $orderMain->user_id, + 'store_id' => $data['store_id'], + 'order_main_id' => $orderMainId, + 'state' => OrderMain::ORDER_STATE_UNPAY, + 'tel' => $orderMain->tel, + 'name' => $orderMain->name, + 'address' => $orderMain->address, + 'area' => $orderMain->area, + 'time' => date("Y-m-d H:i:s"), + 'note' => '', + 'delivery_time' => $orderMain->delivery_time, + 'type' => $orderMain->type, + 'lat' => $orderMain->lat, + 'lng' => $orderMain->lng, + 'pay_type' => $orderMain->pay_type, + 'order_type' => $orderMain->order_type, + 'money' => 0, + 'box_money' => 0, + 'mj_money' => 0, + 'yhq_money' => 0, + 'yhq_money2' => 0, + 'zk_money' => 0, + 'coupon_id' => 0, + 'coupon_id2' => 0, + 'xyh_money' => 0, + 'time_add' => date("Y-m-d H:i:s"), + 'jj_note' => '', + 'form_id' => '', + 'form_id2' => '', + 'code' => '', + ]; + + $orderChildId = Order::query()->insertGetId($dataChild); + + Db::commit(); + return $orderMainId; + } catch (Exception $e) { + Db::rollBack(); + return '购买失败'; + } } diff --git a/app/Service/OrderServiceInterface.php b/app/Service/OrderServiceInterface.php index 08ee815..0d5e0a2 100644 --- a/app/Service/OrderServiceInterface.php +++ b/app/Service/OrderServiceInterface.php @@ -17,7 +17,7 @@ interface OrderServiceInterface * 扫码支付 * @return mixed */ - public function addOfflineOrder(); + public function addOfflineOrder($data); /** * 订单是否已经存在 diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php index 6119690..f751cdc 100644 --- a/app/TaskWorker/MQTTClientTask.php +++ b/app/TaskWorker/MQTTClientTask.php @@ -12,8 +12,46 @@ class MQTTClientTask /** * @Task + * @param string|number $message 消息内容 + * @param string $topic 发布消息到主题,主题名 + * @param string $type 消息类型,cash或tts + * @param string $payId 支付方式,如“支付宝”、“微信”等 + * @param string $toClientId 终端id,如IMEI码 + * @param string $curClientId 当前客户端id */ - public function getClient() + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ) { + $this->getClient(); + + $msgArr = []; + if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { + $msgArr['cash'] = $message; + $payId AND $msgArr['payid'] = $payId; + } else { + $msgArr['message'] = $message; + } + + if (!empty($toClientId)) { + $topic .= '/'.$toClientId; + } + + $curClientId OR $curClientId = rand(1,999999999); + $success = $this->mqttClient->sendConnect($curClientId); + + if ($success) { + $this->mqttClient->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); + $this->mqttClient->sendDisconnect(); + } + $this->mqttClient->close(); + } + + protected function getClient() { $this->mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 411bb9f..1557ca3 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -9,13 +9,16 @@ declare(strict_types=1); * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ + return [ \App\Service\ServiceEvaluateServiceInterface::class => \App\Service\ServiceEvaluateService::class, \App\Service\AttachmentServiceInterface::class => \App\Service\AttachmentService::class, \App\Service\ParamsTokenServiceInterface::class => \App\Service\ParamsTokenSsdbService::class, - \App\Service\DeviceServiceInterFace::class =>\App\Service\DeviceServiceImp::class, + \App\Service\DeviceServiceInterface::class =>\App\Service\DeviceServiceImp::class, \App\Commons\Log::class => \App\Commons\Log::class, \App\Service\IOTServiceInterface::class => \App\Service\IOTAliService::class, \App\Service\OrderServiceInterface::class => \App\Service\OrderService::class, - \App\Service\CoupnoServiceInterface::class => \App\Service\CouponService::class, + \App\Service\CouponServiceInterface::class => \App\Service\CouponService::class, + \App\Service\MqttServiceInterface::class => \App\Service\MqttSpeakerService::class, + \App\Service\FeiePrintServiceInterface::class => \App\Service\FeiePrintService::class, ]; diff --git a/config/config.php b/config/config.php index 7e8d490..ba75ad6 100644 --- a/config/config.php +++ b/config/config.php @@ -36,6 +36,9 @@ return [ 'cert_path' => env('CERT_PATH',''), 'key_path' => env('KEY_PATH',''), 'notify_url' => env('NOTIFY_URL',''), + ], + 'wxtempmsg' => [ + 'app_id' => env('APP_ID',''), + 'secret' => env('APP_SECRET',''), ] - ]; diff --git a/config/routes.php b/config/routes.php index 266122f..7902ff0 100644 --- a/config/routes.php +++ b/config/routes.php @@ -39,6 +39,7 @@ Router::addGroup('/v1/',function (){ //订单相关 Router::post('Order/addOnline', 'App\Controller\OrderController@addOnlineOrder'); + Router::post('Order/addOffline', 'App\Controller\OrderController@addOfflineOrder'); //小程序支付相关 Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); From 4e675fd7580b27288cde34f34ac6cde89e9c1e74 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 21:50:22 +0800 Subject: [PATCH 39/72] =?UTF-8?q?=E4=BF=AE=E6=94=B9API=20AUTH=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/PaymentController.php | 4 ++-- config/autoload/middlewares.php | 4 ++-- config/routes.php | 5 ++++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/Controller/PaymentController.php b/app/Controller/PaymentController.php index 5047f27..9fc92ae 100644 --- a/app/Controller/PaymentController.php +++ b/app/Controller/PaymentController.php @@ -35,7 +35,7 @@ class PaymentController extends BaseController 'out_trade_no' => $orderMain->global_order_id, // 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), 'total_fee' => 1, - 'notify_url' => config('site_host') . '/v1/notify/wxminionline', + 'notify_url' => config('site_host') . '/wechat/notify/wxminionline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); @@ -75,7 +75,7 @@ class PaymentController extends BaseController 'body' => '懒族生活 - 当面支付', 'out_trade_no' => $orderMain->global_order_id, 'total_fee' => bcmul(floatval($orderMain->money), 100, 0), - 'notify_url' => config('site_host') . '/v1/notify/wxminioffline', + 'notify_url' => config('site_host') . '/wechat/notify/wxminioffline', 'trade_type' => 'JSAPI', 'openid' => $data['openid'], ]); diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 5eb19a5..fa4a0fc 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,8 +11,8 @@ declare(strict_types=1); */ return [ 'http' => [ - \App\Middleware\Auth\ApiMiddleware::class, - \Hyperf\Validation\Middleware\ValidationMiddleware::class, + // \App\Middleware\Auth\ApiMiddleware::class, \App\Middleware\CorsMiddleware::class, + \Hyperf\Validation\Middleware\ValidationMiddleware::class, ], ]; diff --git a/config/routes.php b/config/routes.php index 7902ff0..ab8a2ed 100644 --- a/config/routes.php +++ b/config/routes.php @@ -44,7 +44,10 @@ Router::addGroup('/v1/',function (){ //小程序支付相关 Router::post('wxminipay/online', 'App\Controller\PaymentController@wxminiPayOnline'); Router::post('wxminipay/offline', 'App\Controller\PaymentController@wxminiPayOffline'); + +},['middleware' => [\App\Middleware\Auth\ApiMiddleware::class]]); + +Router::addGroup('/wechat/',function () { Router::post('notify/wxminionline', 'App\Controller\NotifyController@wxminiOnline'); Router::post('notify/wxminioffline', 'App\Controller\NotifyController@wxminiOffline'); - }); \ No newline at end of file From f6dab71db5cdda9c5b5a3181a7a6ee1b03393f5e Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 22:26:13 +0800 Subject: [PATCH 40/72] =?UTF-8?q?easywechat=E7=BB=91=E5=AE=9A=E6=96=B0requ?= =?UTF-8?q?est?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 17 ++++++++++++++--- app/Model/Goods.php | 2 ++ app/Model/Order.php | 1 + app/Model/OrderGoods.php | 1 + app/Model/OrderSalesStatistic.php | 2 ++ app/Model/SpecCombination.php | 1 + app/Model/SystemConfig.php | 1 + app/Model/Users.php | 1 + 8 files changed, 23 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 3ac5cd3..80f8b0f 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -20,6 +20,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; use Hyperf\Di\Annotation\Inject; +use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController { @@ -54,6 +55,16 @@ class NotifyController extends BaseController $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; + + $get = $this->request->getQueryParams(); + $post = $this->request->getParsedBody(); + $cookie = $this->request->getCookieParams(); + $files = $this->request->getUploadedFiles(); + $server = $this->request->getServerParams(); + $xml = $this->request->getBody()->getContents(); + + $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); + var_dump('inside'); // 通知回调,进行业务处理 Db::beginTransaction(); @@ -109,9 +120,7 @@ class NotifyController extends BaseController } } - - - // return true; + return true; } // 修改订单、子订单状态 @@ -188,6 +197,8 @@ class NotifyController extends BaseController $res = $this->feiePrintService->feiePrint($orderMain->order_num); var_dump($res); + return true; + }); var_dump('$response', $response); diff --git a/app/Model/Goods.php b/app/Model/Goods.php index 83f2304..8009bda 100644 --- a/app/Model/Goods.php +++ b/app/Model/Goods.php @@ -9,4 +9,6 @@ class Goods extends Model const INVENTORY_NOLIMIT = 1; protected $table = 'ims_cjdc_goods'; + public $timestamps = false; + } \ No newline at end of file diff --git a/app/Model/Order.php b/app/Model/Order.php index 535bbc7..7053f71 100644 --- a/app/Model/Order.php +++ b/app/Model/Order.php @@ -7,5 +7,6 @@ namespace App\Model; class Order extends Model { protected $table = 'ims_cjdc_order'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/OrderGoods.php b/app/Model/OrderGoods.php index 12b1702..c82b527 100644 --- a/app/Model/OrderGoods.php +++ b/app/Model/OrderGoods.php @@ -5,4 +5,5 @@ namespace App\Model; class OrderGoods extends Model { protected $table = 'ims_cjdc_order_goods'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/OrderSalesStatistic.php b/app/Model/OrderSalesStatistic.php index a20edf8..5b58f92 100644 --- a/app/Model/OrderSalesStatistic.php +++ b/app/Model/OrderSalesStatistic.php @@ -26,4 +26,6 @@ class OrderSalesStatistic extends Model * @var array */ protected $casts = []; + + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/SpecCombination.php b/app/Model/SpecCombination.php index adf23a3..9d112d0 100644 --- a/app/Model/SpecCombination.php +++ b/app/Model/SpecCombination.php @@ -8,6 +8,7 @@ class SpecCombination extends Model { protected $table = 'ims_cjdc_spec_combination'; + public $timestamps = false; public function goods() { diff --git a/app/Model/SystemConfig.php b/app/Model/SystemConfig.php index 5f81111..74e8bb8 100644 --- a/app/Model/SystemConfig.php +++ b/app/Model/SystemConfig.php @@ -7,4 +7,5 @@ namespace App\Model; class SystemConfig extends Model { protected $table = 'ims_cjdc_system_config'; + public $timestamps = false; } \ No newline at end of file diff --git a/app/Model/Users.php b/app/Model/Users.php index 2a8d910..32cff4d 100644 --- a/app/Model/Users.php +++ b/app/Model/Users.php @@ -5,4 +5,5 @@ namespace App\Model; class Users extends Model { protected $table = 'ims_cjdc_user'; + public $timestamps = false; } \ No newline at end of file From 488f4666b0e4eb196264ad9748e2726d281b3e6b Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:00:43 +0800 Subject: [PATCH 41/72] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 18 +++++++++--------- app/Model/OrderMain.php | 1 + app/Service/OrderService.php | 7 ++++--- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 80f8b0f..f54b3fc 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -136,11 +136,11 @@ class NotifyController extends BaseController // 更新商户销量 $upStoreScore = Store::query() - ->whereIn('id', $orderMain->order_ids) + ->whereIn('id', explode(',', $orderMain->store_ids)) ->update(['score' => Db::raw('score+1')]); // 更新商品库存和销量 - $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'createtime']) + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); @@ -153,7 +153,7 @@ class NotifyController extends BaseController $goods = Goods::find($goodsItem['id']); // 库存处理,有规格 - if ($goodsItem->combination_id) { + if ($goodsItem['combination_id']) { $combination = SpecCombination::find($goodsItem['combination_id']); $combination->number = $combination->number - $goodsItem['number']; $combination->save(); @@ -168,14 +168,14 @@ class NotifyController extends BaseController // 月销流水 $statistics = []; - foreach ($orders as $key => & $order) { + foreach ($orders as $key => &$order) { $statistics[] = [ - 'money' => $order->money, - 'user_id' => $order->user_id, - 'store_id' => $order->store_id, + 'money' => $order['money'], + 'user_id' => $order['user_id'], + 'store_id' => $order['store_id'], 'market_id' => $orderMain->market_id, - 'order_id' => $order->id, - 'createtime' => strtotime($order->pay_time), + 'order_id' => $order['id'], + 'createtime' => strtotime($order['pay_time']), ]; } diff --git a/app/Model/OrderMain.php b/app/Model/OrderMain.php index 4972484..92213ad 100644 --- a/app/Model/OrderMain.php +++ b/app/Model/OrderMain.php @@ -81,6 +81,7 @@ class OrderMain extends Model 'pay_time', 'jj_note', 'global_order_id', + 'store_ids', ]; } \ No newline at end of file diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 2efb470..decf5ab 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -36,10 +36,11 @@ class OrderService implements OrderServiceInterface // 订单判重 $dataMain = $data; + var_dump($dataMain); if ($orderMainId = $this->existsByOrderNum($data['order_num'])) { return $orderMainId; } - + var_dump($orderMainId); Db::beginTransaction(); try { @@ -62,12 +63,12 @@ class OrderService implements OrderServiceInterface Db::rollBack(); return '订单中商品不存在或已失效'; } - +var_dump('storelist', $storeList); // 获取商户IDs foreach ($storeList as &$item) { $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; } - + var_dump('$dataMain[\'store_ids\']', $dataMain['store_ids']); // 主订单插入数据 $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); From cc3b2eb74927b53e09268edf2e3635789a8ea99a Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:05:26 +0800 Subject: [PATCH 42/72] Fix --- app/Controller/NotifyController.php | 2 +- app/Service/MqttSpeakerService.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index f54b3fc..074cf53 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -140,7 +140,7 @@ class NotifyController extends BaseController ->update(['score' => Db::raw('score+1')]); // 更新商品库存和销量 - $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id']) + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 9724497..5a8b802 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -5,6 +5,7 @@ namespace App\Service; use App\Model\Order; use App\Model\Store; use App\TaskWorker\MQTTClientTask; +use Hyperf\Utils\ApplicationContext; class MqttSpeakerService implements MqttServiceInterface { From d46f86f6a41b303f3e664741ad3f8511fba98c1b Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:07:53 +0800 Subject: [PATCH 43/72] Fix --- app/Service/MiniprogramService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index e977403..ab74ec4 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -48,7 +48,7 @@ class MiniprogramService implements MiniprogramServiceInterface } // 商户/门店的openid - $store = Store::query()->select(['id', 'name']) + $store = Store::query()->select(['id', 'name', 'user_id']) ->where(['id' => $item['store_id']]) ->first()->toArray(); $store['openid'] = Users::query() From 9b76889dcbc35c954e9e1974a07e491aed346eb9 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:16:14 +0800 Subject: [PATCH 44/72] Fix --- app/Controller/NotifyController.php | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 074cf53..5eeb3bc 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -67,10 +67,9 @@ class NotifyController extends BaseController var_dump('inside'); // 通知回调,进行业务处理 - Db::beginTransaction(); - try { - $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - + $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + Db::beginTransaction(); + try { var_dump('message', $message); // 支付失败或者通知失败 if ( @@ -197,20 +196,19 @@ class NotifyController extends BaseController $res = $this->feiePrintService->feiePrint($orderMain->order_num); var_dump($res); + Db::commit(); return true; - }); - - var_dump('$response', $response); - Db::rollBack(); - $response->send(); + } catch (Exception $e) { - } catch (\EasyWeChat\Kernel\Exceptions\Exception $e) { + var_dump($e->getMessage()); + Db::rollBack(); + $fail('Exception'); + } - var_dump($e->getMessage()); - Db::rollBack(); + }); - } + $response->send(); } From 1eef42fab02754ddee5eec0e1d55f0d752c1dcc4 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:24:29 +0800 Subject: [PATCH 45/72] FIX --- app/Service/MiniprogramService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index ab74ec4..93bc586 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -10,6 +10,7 @@ use App\Model\OrderMain; use App\Model\Store; use App\Model\Users; use EasyWeChat\Factory; +use Hyperf\Guzzle\CoroutineHandler; class MiniprogramService implements MiniprogramServiceInterface { @@ -141,6 +142,7 @@ class MiniprogramService implements MiniprogramServiceInterface } $app = Factory::miniProgram(config('wxtempmsg')); + $app['guzzle_handler'] = CoroutineHandler::class; $app->uniform_message->send($template); } From 5587e759aa3123bfe851205d0af08db1c923352d Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:40:21 +0800 Subject: [PATCH 46/72] f --- app/Controller/NotifyController.php | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 5eeb3bc..d22e6da 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -82,6 +82,7 @@ class NotifyController extends BaseController LogLabel::PAY_NOTIFY_WXMINI, $message ); + Db::rollBack(); $fail('Unknown error but FAIL'); } @@ -89,36 +90,17 @@ class NotifyController extends BaseController $orderMain = OrderMain::query() ->where([ 'global_order_id' => $message['out_trade_no'], - 'type' => OrderMain::ORDER_TYPE_ONLINE, - 'state' => OrderMain::ORDER_STATE_UNPAY + 'type' => OrderMain::ORDER_TYPE_ONLINE ]) - ->where('time', '>=', date('Y-m-d H:i:s', (time() - 900))) ->first(); var_dump('$orderMain', $orderMain); // 订单不存在 if (empty($orderMain)) { - $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $orderMain + ['global_order_id_fail' => $message['out_trade_no']] ); - - // 去查一下微信订单,只处理未支付的情况 TODO 其他情况处理 - $wxOrder = $app->order->queryByOutTradeNumber($message['out_trade_no']); - // 查询成功 - if ($wxOrder['return_code'] == 'SUCCESS') { - if ($wxOrder['result_code'] == 'SUCCESS') { - // 看订单支付状态,处理未支付的情况,把订单处理成未支付 - if ($wxOrder['trade_state'] != 'NOTPAY') { - OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no']]) - ->update(['state' => OrderMain::ORDER_STATE_UNPAY]); - - $fail('Order not paid'); - } - } - } - + Db::rollBack(); return true; } From c208d602986d8a791896af2b8fcf42f704dbd206 Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:43:13 +0800 Subject: [PATCH 47/72] Fix --- app/Controller/NotifyController.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index d22e6da..ba9a1e8 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -166,17 +166,17 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump($res); + var_dump('speakToStore',$res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump($res); + var_dump('pubMsgToStoreByOrderMainId',$res); // 公众号模板消息 - $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); - var_dump($res); + // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->order_num); - var_dump($res); + var_dump('feiePrint',$res); Db::commit(); return true; From d19d49995beda68cb3d539486bcaac54839e080c Mon Sep 17 00:00:00 2001 From: weigang Date: Thu, 13 Aug 2020 23:46:36 +0800 Subject: [PATCH 48/72] Fix --- app/Service/FeiePrintService.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index b822175..7bfb6f1 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -31,9 +31,10 @@ class FeiePrintService implements FeiePrintServiceInterface ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') ->where('m.order_num', $order_num) - ->select("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") - ->order('s.id') - ->get(); + ->selectRaw("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") + ->orderBy('s.id') + ->get() + ->toArray(); $content = $this->printFormat($data, 14, 6, 3, 6); $res = $this->printMsg($data[0]['sn'], $content, 1); From bbeebb64a90fe57956c94c43e6703d3b61265953 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:05:47 +0800 Subject: [PATCH 49/72] F --- app/Service/FeiePrintService.php | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 7bfb6f1..0b1f1aa 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -3,6 +3,7 @@ namespace App\Service; use App\Libs\FeiePrintClient; +use App\Model\OrderMain; use Hyperf\DbConnection\Db; use Hyperf\Utils\ApplicationContext; @@ -25,16 +26,20 @@ class FeiePrintService implements FeiePrintServiceInterface public function feiePrint($order_num) { + // TODO 对象数组=》二维数组 $data = Db::table('ims_cjdc_order_main as m') ->join('ims_cjdc_order as o','o.order_main_id', '=', 'm.id','inner') ->join('ims_cjdc_order_goods as g','o.id','=', 'g.order_id','inner') ->join('ims_cjdc_feprint as f','m.market_id','=', 'f.market_id','inner') ->join('ims_cjdc_store as s','s.id','=', 'o.store_id','inner') - ->where('m.order_num', $order_num) + ->where('m.global_order_id', $order_num) ->selectRaw("o.note as o_note,g.name,g.number,g.money,g.good_unit,m.delivery_time as ps_time,m.address,m.note,m.name as user_name,m.dada_fee,m.money as m_money,m.yhq_money2,m.box_money,f.sn,m.tel,m.order_num,g.id,g.spec,s.name as shopname") ->orderBy('s.id') ->get() ->toArray(); + foreach ($data as $key => &$item) { + $item = (array)$item; + } $content = $this->printFormat($data, 14, 6, 3, 6); $res = $this->printMsg($data[0]['sn'], $content, 1); @@ -135,8 +140,8 @@ class FeiePrintService implements FeiePrintServiceInterface if($m+$j>$lan) { $m = $m+$j; $tail = $new; - $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - strlen($lenght); + // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); + $k = $A - mb_strlen($new); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -160,8 +165,8 @@ class FeiePrintService implements FeiePrintServiceInterface $head = ''; foreach ($result as $key=>$value) { if($key < 1){ - $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = strlen($v_lenght); + // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); + $v_lenght = mb_strlen($value); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -207,8 +212,8 @@ class FeiePrintService implements FeiePrintServiceInterface } $str = $user_name . $total; $kw5 = ''; - $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - strlen($lenght); + // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); + $total_len = 32 - mb_strlen($str); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } From ec8740fe1b709d8327eb5afb0a23cce739da6155 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:13:17 +0800 Subject: [PATCH 50/72] Fix --- app/Controller/NotifyController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index ba9a1e8..9d7fa85 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -175,7 +175,7 @@ class NotifyController extends BaseController // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 - $res = $this->feiePrintService->feiePrint($orderMain->order_num); + $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); var_dump('feiePrint',$res); Db::commit(); From 49383d9ab56f293dde9ea7199e79a4227da5c69c Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:29:15 +0800 Subject: [PATCH 51/72] F --- app/Controller/NotifyController.php | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 9d7fa85..6f9a494 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -20,6 +20,7 @@ use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; use Exception; use Hyperf\Di\Annotation\Inject; +use Hyperf\HttpMessage\Stream\SwooleStream; use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController @@ -65,12 +66,10 @@ class NotifyController extends BaseController $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); - var_dump('inside'); // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { Db::beginTransaction(); try { - var_dump('message', $message); // 支付失败或者通知失败 if ( empty($message) @@ -93,7 +92,7 @@ class NotifyController extends BaseController 'type' => OrderMain::ORDER_TYPE_ONLINE ]) ->first(); - var_dump('$orderMain', $orderMain); + // 订单不存在 if (empty($orderMain)) { $this->log->event( @@ -166,31 +165,34 @@ class NotifyController extends BaseController // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump('speakToStore',$res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump('pubMsgToStoreByOrderMainId',$res); // 公众号模板消息 // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); - // var_dump('sendTemMsgForOnlineOrder',$res); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); - var_dump('feiePrint',$res); Db::commit(); return true; } catch (Exception $e) { - var_dump($e->getMessage()); + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['exception_fail' => $e->getMessage()] + ); Db::rollBack(); $fail('Exception'); } }); - $response->send(); + var_dump('reponse',$response->getContent()); + return $this->response + ->withHeader('Content-Type', 'application/xml') + ->withStatus(200) + ->withBody(new SwooleStream($response->getContent())); } From 4417db873950e5ac2c9f368155d19fb3344dd0f5 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:34:12 +0800 Subject: [PATCH 52/72] f --- app/Controller/NotifyController.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 6f9a494..90ced49 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -68,6 +68,8 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + + var_dump('message',$message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -190,7 +192,7 @@ class NotifyController extends BaseController var_dump('reponse',$response->getContent()); return $this->response - ->withHeader('Content-Type', 'application/xml') + ->withHeader('Content-Type', 'text/xml') ->withStatus(200) ->withBody(new SwooleStream($response->getContent())); From 2d8ed3c41b2855212f64ebf661a1fee2f3dafc33 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 00:54:16 +0800 Subject: [PATCH 53/72] Fx --- app/Controller/NotifyController.php | 4 +--- app/Service/MiniprogramService.php | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 90ced49..633ff04 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -69,7 +69,6 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - var_dump('message',$message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -170,7 +169,7 @@ class NotifyController extends BaseController $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); // 公众号模板消息 - // $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); + $res = $this->miniprogramService->sendTemMsgForOnlineOrder($orderMain->id); // 打印订单,自动打印 TODO 后续优化调用逻辑 $res = $this->feiePrintService->feiePrint($orderMain->global_order_id); @@ -190,7 +189,6 @@ class NotifyController extends BaseController }); - var_dump('reponse',$response->getContent()); return $this->response ->withHeader('Content-Type', 'text/xml') ->withStatus(200) diff --git a/app/Service/MiniprogramService.php b/app/Service/MiniprogramService.php index 93bc586..33a9b4d 100644 --- a/app/Service/MiniprogramService.php +++ b/app/Service/MiniprogramService.php @@ -104,9 +104,7 @@ class MiniprogramService implements MiniprogramServiceInterface ]; // 看看有没有小程序跳转的要求 - if ( is_array($applet_config)&&!empty($applet_config)&&!empty($applet_config['appid']) ) { - $template['mp_template_msg']['miniprogram'] = $applet_config; - } + $template['mp_template_msg']['miniprogram'] = $applet_config; // 重点来了,拼接关键数据data if (!is_array($data)) { # 数组都不是,请回去 From 9820a42affb5e7d07cffd505949d7528bfaa5c21 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 09:30:10 +0800 Subject: [PATCH 54/72] =?UTF-8?q?=E5=96=87=E5=8F=AD=E6=92=AD=E6=8A=A5?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Libs/MQTTClient.php | 2 +- app/Service/FeiePrintService.php | 6 +++--- app/TaskWorker/MQTTClientTask.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index d2a9490..56584c0 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -322,7 +322,7 @@ class MQTTClient { } // Set socket timeout - ini_set('default_socket_timeout', 10); + ini_set('default_socket_timeout', '10'); stream_set_timeout($this->socket, 0, $this->socketTimeout * 1000); // Set stream to non-blocking mode, ie do not wait to read if stream is empty stream_set_blocking($this->socket, true); diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 0b1f1aa..0a7365d 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -141,7 +141,7 @@ class FeiePrintService implements FeiePrintServiceInterface $m = $m+$j; $tail = $new; // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - mb_strlen($new); + $k = $A - mb_strlen($new,'utf-8'); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -166,7 +166,7 @@ class FeiePrintService implements FeiePrintServiceInterface foreach ($result as $key=>$value) { if($key < 1){ // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = mb_strlen($value); + $v_lenght = mb_strlen($value,'utf-8'); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -213,7 +213,7 @@ class FeiePrintService implements FeiePrintServiceInterface $str = $user_name . $total; $kw5 = ''; // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - mb_strlen($str); + $total_len = 32 - mb_strlen($str,'utf-8'); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php index f751cdc..e49f562 100644 --- a/app/TaskWorker/MQTTClientTask.php +++ b/app/TaskWorker/MQTTClientTask.php @@ -41,7 +41,7 @@ class MQTTClientTask $topic .= '/'.$toClientId; } - $curClientId OR $curClientId = rand(1,999999999); + $curClientId OR $curClientId = (string)rand(1,999999999); $success = $this->mqttClient->sendConnect($curClientId); if ($success) { From 28861f0494a558ca26a45aac64803e9c74e49bf9 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 09:57:34 +0800 Subject: [PATCH 55/72] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E4=B8=8B=E5=8D=95?= =?UTF-8?q?=E8=B0=83=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index decf5ab..75bca49 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -36,11 +36,11 @@ class OrderService implements OrderServiceInterface // 订单判重 $dataMain = $data; - var_dump($dataMain); + if ($orderMainId = $this->existsByOrderNum($data['order_num'])) { return $orderMainId; } - var_dump($orderMainId); + Db::beginTransaction(); try { @@ -63,12 +63,12 @@ class OrderService implements OrderServiceInterface Db::rollBack(); return '订单中商品不存在或已失效'; } -var_dump('storelist', $storeList); + // 获取商户IDs foreach ($storeList as &$item) { $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id']; } - var_dump('$dataMain[\'store_ids\']', $dataMain['store_ids']); + // 主订单插入数据 $currentTime = time(); $dataMain['time'] = date('Y-m-d H:i:s', $currentTime); From 6abb9f90813a0743483f007244529cb9eee95a1e Mon Sep 17 00:00:00 2001 From: Lemon <15040771@qq.com> Date: Fri, 14 Aug 2020 10:41:04 +0800 Subject: [PATCH 56/72] =?UTF-8?q?=E5=90=88=E8=AE=A1=E9=87=91=E9=A2=9D?= =?UTF-8?q?=E6=8D=A2=E8=A1=8C=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/FeiePrintService.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Service/FeiePrintService.php b/app/Service/FeiePrintService.php index 0a7365d..9f8f31d 100644 --- a/app/Service/FeiePrintService.php +++ b/app/Service/FeiePrintService.php @@ -141,7 +141,7 @@ class FeiePrintService implements FeiePrintServiceInterface $m = $m+$j; $tail = $new; // $lenght = iconv("UTF-8", "GBK//IGNORE", $new); - $k = $A - mb_strlen($new,'utf-8'); + $k = $A - mb_strwidth($new,'utf-8'); for($q=0;$q<$k;$q++){ $kw3 .= ' '; } @@ -166,7 +166,7 @@ class FeiePrintService implements FeiePrintServiceInterface foreach ($result as $key=>$value) { if($key < 1){ // $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value); - $v_lenght = mb_strlen($value,'utf-8'); + $v_lenght = mb_strwidth($value,'utf-8'); if($v_lenght == 13) $value = $value." "; $head .= $value.' '.$price.' '.$num.' '.$prices; }else{ @@ -213,7 +213,7 @@ class FeiePrintService implements FeiePrintServiceInterface $str = $user_name . $total; $kw5 = ''; // $lenght = iconv("UTF-8", "GBK//IGNORE", $str); - $total_len = 32 - mb_strlen($str,'utf-8'); + $total_len = 32 - mb_strwidth($str,'utf-8'); for ($q = 0; $q < $total_len; $q++) { $kw5 .= ' '; } From e952ee31ead1d2a9e139b2b0c38e51b98ded57e9 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 11:52:30 +0800 Subject: [PATCH 57/72] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 167 ++++++++++++++++++-- app/Model/StoreAccount.php | 9 ++ app/Service/MiniprogramService.php | 66 +++++++- app/Service/MiniprogramServiceInterface.php | 32 ++++ app/Service/UserService.php | 76 +++++++++ app/Service/UserServiceInterface.php | 28 ++++ 6 files changed, 360 insertions(+), 18 deletions(-) create mode 100644 app/Model/StoreAccount.php create mode 100644 app/Service/UserService.php create mode 100644 app/Service/UserServiceInterface.php diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 633ff04..7d88a32 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -10,11 +10,14 @@ use App\Model\OrderMain; use App\Model\OrderSalesStatistic; use App\Model\SpecCombination; use App\Model\Store; +use App\Model\StoreAccount; use App\Model\SystemConfig; +use App\Model\Users; use App\Service\DeviceServiceInterface; use App\Service\FeiePrintServiceInterface; use App\Service\MiniprogramService; use App\Service\MqttServiceInterface; +use App\Service\UserServiceInterface; use EasyWeChat\Factory; use Hyperf\DbConnection\Db; use Hyperf\Guzzle\CoroutineHandler; @@ -50,6 +53,12 @@ class NotifyController extends BaseController */ protected $feiePrintService; + /** + * @Inject + * @var UserServiceInterface + */ + protected $userService; + public function wxminiOnline() { @@ -202,33 +211,159 @@ class NotifyController extends BaseController $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; + $get = $this->request->getQueryParams(); + $post = $this->request->getParsedBody(); + $cookie = $this->request->getCookieParams(); + $files = $this->request->getUploadedFiles(); + $server = $this->request->getServerParams(); + $xml = $this->request->getBody()->getContents(); + + $app['request'] = new Request($get,$post,[],$cookie,$files,$server,$xml); + // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - $this->log->event( - LogLabel::PAY_NOTIFY_WXMINI, - $message - ); + Db::beginTransaction(); + try { + // 支付失败或者通知失败 + if ( + empty($message) + || $message['return_code'] != 'SUCCESS' + || !isset($message['result_code']) + || $message['result_code'] != 'SUCCESS' + ) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + $message + ); + Db::rollBack(); + $fail('Unknown error but FAIL'); + } - // 查询订单 - $orderMain = OrderMain::query() - ->where(['global_order_id' => $message['out_trade_no'], 'type' => OrderMain::ORDER_TYPE_OFFLINE, 'state' => OrderMain::ORDER_STATE_UNPAY]) - ->where('time', '>=', date('Y-m-d H:i:s', (time()-900))) - ->first(); + // 查询订单 + $orderMain = OrderMain::query() + ->where([ + 'global_order_id' => $message['out_trade_no'], + 'type' => OrderMain::ORDER_TYPE_OFFLINE + ]) + ->first(); - if (empty($orderMain)) { - // 去查一下微信订单 - $wxOrder = $app->order->queryByOutTradeNumber($orderMain->global_order_id); + // 订单不存在 + if (empty($orderMain)) { + $this->log->event( + LogLabel::PAY_NOTIFY_WXMINI, + ['global_order_id_fail' => $message['out_trade_no']] + ); + Db::rollBack(); + return true; + } + + // 修改订单、子订单状态 + $currentTime = time(); + $orderMain->state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->dm_state = OrderMain::ORDER_STATE_UNTAKE; + $orderMain->time_pay = $currentTime; + $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); + $orderMain->save(); + + // 查询子订单,当面付目前实际上只有一个子订单 + $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) + ->where(['order_main_id' => $orderMain->id]) + ->get() + ->toArray(); + + // 商户钱包、流水资金、奖励、发布模板消息处理 + foreach ($orders as $key => $orderItem) { + + $recordBase = [ + 'user_id' => $orderItem['user_id'], + 'order_id' => $orderItem['id'], + 'store_id' => $orderItem['store_id'], + 'type' => 1, + 'time' => date('Y-m-d H:i:s', $currentTime), + 'add_time' => $currentTime, + ]; + + // 钱包 + $store = Store::find($orderItem['store_id']); + $store->store_wallet = bcadd($store->store_wallet, $orderItem['money'], 2); + $store->save(); + + // 流水 + $record = [ + 'money' => $orderItem['money'], + 'note' => '当面付订单收入', + 'category' => 2, + ]; + StoreAccount::query()->insert(array($recordBase, $record)); + + // 平台新用户奖励给商户 + $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); + $needAward = false; + $awardAmount = 0; + if ($isStageNewUser) { + $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_new_user'])->value('value'); + // 流水 + $record = [ + 'money' => $awardAmount, + 'note' => '新用户下单成功,平台奖励', + 'category' => 3, + ]; + $needAward = true; + } else { + $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); + if ($isStoreFirstOrderToday) { + $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); + // 流水 + $record = [ + 'money' => $awardAmount, + 'note' => '用户下单成功,平台奖励', + 'category' => 4, + ]; + $needAward = true; + } + } + + if ($needAward && $awardAmount) { + // 奖励钱包 + $store->refresh(); + $store->award_money = bcadd($store->award_money, $awardAmount, 2); + $store->save(); + + // 流水 + StoreAccount::query()->insert(array($recordBase, $record)); + + // 发布公众号消息 + $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); + $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); + } + } + + // 喇叭通知,兼容旧音响,MQTT+IOT + $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + + // 公众号模板消息 + $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); + + Db::commit(); + return true; + + } catch (Exception $e) { $this->log->event( LogLabel::PAY_NOTIFY_WXMINI, - $wxOrder + ['exception_fail' => $e->getMessage()] ); - - // return true; + Db::rollBack(); + $fail('Exception'); } + }); - $response->send(); + return $this->response + ->withHeader('Content-Type', 'text/xml') + ->withStatus(200) + ->withBody(new SwooleStream($response->getContent())); } } \ No newline at end of file diff --git a/app/Model/StoreAccount.php b/app/Model/StoreAccount.php new file mode 100644 index 0000000..d83f11f --- /dev/null +++ b/app/Model/StoreAccount.php @@ -0,0 +1,9 @@ + &$item) { - $item = (array)$item; - // 订单商品 $order_goods = OrderGoods::query()->select(['name', 'number', 'spec', 'good_unit']) ->where(['order_id' => $item['id']]) @@ -91,6 +92,67 @@ class MiniprogramService implements MiniprogramServiceInterface } + /** + * @inheritDoc + */ + public function sendTemMsgForOfflineOrder($order_main_id) + { + + // 查询子订单,用于发消息给商户 + $order_children = Order::query()->select(['id', 'order_num', 'store_id', 'money', 'time']) + ->where(['order_main_id' => $order_main_id]) + ->get() + ->toArray(); + + foreach ($order_children as $key => &$item) { + // 商户/门店的openid + $store = Store::query()->select(['id', 'name', 'user_id']) + ->where(['id' => $item['store_id']]) + ->first()->toArray(); + $store['openid'] = Users::query() + ->where(['id' => $store['user_id']]) + ->value('openid'); + + // 模板数据 + $data_store = [ + 'first' => '您有新订单收入!订单编号:'.$item['order_num'], + 'keyword' => [ + $store['name']?:'', + $item['time']?:'', + '暂无', + $item['money'] + ], + 'remark' => '感谢您的使用!' + ]; + + $ret_store = $this->sendTempMsg($store['openid'], 'lxVbC6PVpKbiO44bYqLmacl-BaME70D47Q0jn2Link0',$data_store); + } + + } + + /** + * @inheritDoc + */ + public function sendTemMsgForAward($money, $note, $openid, $time) + { + // 模板数据发送消息给用户 + $data_user = [ + 'first' => '恭喜!您有一笔新的奖励收入!', + 'keyword' => [ + $money, + $note, + $time + ], + 'remark' => '感谢您的使用!' + ]; + + // 获取用户openid,发送给用户 + $ret_user = $this->sendTempMsg($openid,'ypZ7xdHUjWrRG8P-MD42dhpp6kUlh4Unoh7eTSrLZEg', $data_user); + } + + /** + * @inheritDoc + */ public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']) { // 先拼个基础的 diff --git a/app/Service/MiniprogramServiceInterface.php b/app/Service/MiniprogramServiceInterface.php index b1ebe72..1be9d80 100644 --- a/app/Service/MiniprogramServiceInterface.php +++ b/app/Service/MiniprogramServiceInterface.php @@ -4,6 +4,38 @@ namespace App\Service; interface MiniprogramServiceInterface { + /** + * 外卖线上订单模板消息 + * @param $order_main_id + * @return mixed + */ public function sendTemMsgForOnlineOrder($order_main_id); + + /** + * 当面线下订单模板消息 + * @param $order_main_id + * @return mixed + */ + public function sendTemMsgForOfflineOrder($order_main_id); + + /** + * 奖励模板消息 + * @param $money + * @param $note + * @param $openid + * @param $time + * @return mixed + */ + public function sendTemMsgForAward($money, $note, $openid, $time); + + /** + * 发送模板消息 + * @param $openid + * @param $template_id + * @param $data + * @param string $redirect_url + * @param string[] $applet_config + * @return mixed + */ public function sendTempMsg($openid, $template_id, $data, $redirect_url = '', $applet_config = ['appid' => '', 'pagepath' => '']); } \ No newline at end of file diff --git a/app/Service/UserService.php b/app/Service/UserService.php new file mode 100644 index 0000000..6881a6f --- /dev/null +++ b/app/Service/UserService.php @@ -0,0 +1,76 @@ +where(['user_id' => $user_id]) + ->where(function ($query){ + $query->where('state', 'in', [4,5,10]) + ->orWhere('dm_state', 'in', [2,3]); + }) + ->exists(); + + return !$exist; + } + + /** + * 根据用户的openid更新unionid信息 + * 如果没有找到用户,则不做任何处理 + * @param $openid + * @param $unionid + * @return array + */ + public function saveUserUnionid($openid,$unionid) + { + $result = [ + 'status' => false, + 'msg' => '用户不存在或者已存在相同unionid' + ]; + + // 查询用户是否存在 + $userinfo = Users::select('id','unionid')->where('openid',$openid)->first(); + if($userinfo && $userinfo->unionid != $unionid){ + $userinfo->unionid = $unionid; + if($res = $userinfo->save()){ + $result['status'] = true; + $result['msg'] = '更改用户unionid信息成功'; + $result['res'] = $res; + }else{ + $result['msg'] = '更改用户unionid信息失败'; + } + } + + return $result; + } + + /** + * @inheritDoc + */ + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) + { + return !Order::query() + ->where(['user_id' => $user_id, 'store_id' => $store_id, 'dm_state' => 2]) + ->where('time_add', '>=', date('Y-m-d 00:00:00')) + ->where('time_add', '<=', date('Y-m-d 23:59:59')) + ->where('money', '>=', $limit_amount) + ->where('id', '!=', $current_order_id) + ->exists(); + } +} \ No newline at end of file diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php new file mode 100644 index 0000000..5f7bbd3 --- /dev/null +++ b/app/Service/UserServiceInterface.php @@ -0,0 +1,28 @@ + Date: Fri, 14 Aug 2020 13:25:35 +0800 Subject: [PATCH 58/72] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 23 ++++++++++++++++++++--- app/Service/OrderService.php | 1 + 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 7d88a32..231a0ae 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -207,6 +207,7 @@ class NotifyController extends BaseController public function wxminiOffline() { + var_dump('Inside'); $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; @@ -223,6 +224,7 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { + var_dump('$message', $message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -266,12 +268,23 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); + var_dump('$orderMain', $orderMain->toArray()); + + $upOrder = Order::query() + ->where(['order_main_id' => $orderMain->id]) + ->update([ + 'state' => OrderMain::ORDER_STATE_UNTAKE, + 'dm_state' => OrderMain::ORDER_STATE_UNTAKE, + 'pay_time' => date('Y-m-d H:i:s', $currentTime) + ]); + + var_dump('$upOrder', $upOrder); // 查询子订单,当面付目前实际上只有一个子订单 $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); - + var_dump('$orders', $orders); // 商户钱包、流水资金、奖励、发布模板消息处理 foreach ($orders as $key => $orderItem) { @@ -295,7 +308,7 @@ class NotifyController extends BaseController 'note' => '当面付订单收入', 'category' => 2, ]; - StoreAccount::query()->insert(array($recordBase, $record)); + StoreAccount::query()->insert(array_merge($recordBase, $record)); // 平台新用户奖励给商户 $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); @@ -331,20 +344,24 @@ class NotifyController extends BaseController $store->save(); // 流水 - StoreAccount::query()->insert(array($recordBase, $record)); + StoreAccount::query()->insert(array_merge($recordBase, $record)); // 发布公众号消息 $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); + var_dump('$res-award', $res); } } // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); + var_dump('$res-mqttSpeakerService', $res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); + var_dump('$res-deviceService', $res); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); + var_dump('$res-miniprogramService', $res); Db::commit(); return true; diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 75bca49..2ea3245 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -418,6 +418,7 @@ class OrderService implements OrderServiceInterface 'store_id' => $data['store_id'], 'order_main_id' => $orderMainId, 'state' => OrderMain::ORDER_STATE_UNPAY, + 'dm_state' => OrderMain::ORDER_STATE_UNPAY, 'tel' => $orderMain->tel, 'name' => $orderMain->name, 'address' => $orderMain->address, From 0dd1daed41f7a5327dc4b5d6fe367a4412e3b9db Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 13:33:41 +0800 Subject: [PATCH 59/72] =?UTF-8?q?=E5=BD=93=E9=9D=A2=E4=BB=98=E4=B8=8B?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 2ea3245..9e9604a 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -431,7 +431,7 @@ class OrderService implements OrderServiceInterface 'lng' => $orderMain->lng, 'pay_type' => $orderMain->pay_type, 'order_type' => $orderMain->order_type, - 'money' => 0, + 'money' => $data['money'], 'box_money' => 0, 'mj_money' => 0, 'yhq_money' => 0, From e686bb6db34b361b5c06ef67bbad1024f4c109f4 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:17:20 +0800 Subject: [PATCH 60/72] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 231a0ae..a94b07f 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -207,7 +207,7 @@ class NotifyController extends BaseController public function wxminiOffline() { - var_dump('Inside'); + $config = config('wxpay'); $app = Factory::payment($config); $app['guzzle_handler'] = CoroutineHandler::class; @@ -224,7 +224,6 @@ class NotifyController extends BaseController // 通知回调,进行业务处理 $response = $app->handlePaidNotify(function ($message, $fail) use ($app) { - var_dump('$message', $message); Db::beginTransaction(); try { // 支付失败或者通知失败 @@ -268,8 +267,6 @@ class NotifyController extends BaseController $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime); $orderMain->save(); - var_dump('$orderMain', $orderMain->toArray()); - $upOrder = Order::query() ->where(['order_main_id' => $orderMain->id]) ->update([ @@ -278,13 +275,12 @@ class NotifyController extends BaseController 'pay_time' => date('Y-m-d H:i:s', $currentTime) ]); - var_dump('$upOrder', $upOrder); // 查询子订单,当面付目前实际上只有一个子订单 $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time']) ->where(['order_main_id' => $orderMain->id]) ->get() ->toArray(); - var_dump('$orders', $orders); + // 商户钱包、流水资金、奖励、发布模板消息处理 foreach ($orders as $key => $orderItem) { @@ -349,19 +345,15 @@ class NotifyController extends BaseController // 发布公众号消息 $openid = Users::query()->where(['id' => $store['user_id']])->value('openid'); $res = $this->miniprogramService->sendTemMsgForAward($record['money'], $record['note'], $openid, $recordBase['time']); - var_dump('$res-award', $res); } } // 喇叭通知,兼容旧音响,MQTT+IOT $res = $this->mqttSpeakerService->speakToStore($orderMain->id); - var_dump('$res-mqttSpeakerService', $res); $res = $this->deviceService->pubMsgToStoreByOrderMainId($orderMain->id); - var_dump('$res-deviceService', $res); // 公众号模板消息 $res = $this->miniprogramService->sendTemMsgForOfflineOrder($orderMain->id); - var_dump('$res-miniprogramService', $res); Db::commit(); return true; From 058afbe306f2a287aec062e1082c2c0ae8d98904 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:36:07 +0800 Subject: [PATCH 61/72] =?UTF-8?q?=E5=B0=86MQTTClient=E7=A7=BB=E5=87=BAtask?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/MqttServiceInterface.php | 17 ++++++++ app/Service/MqttSpeakerService.php | 46 ++++++++++++++++++-- app/TaskWorker/MQTTClientTask.php | 65 ---------------------------- 3 files changed, 60 insertions(+), 68 deletions(-) delete mode 100644 app/TaskWorker/MQTTClientTask.php diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php index 203b908..127b3cc 100644 --- a/app/Service/MqttServiceInterface.php +++ b/app/Service/MqttServiceInterface.php @@ -18,4 +18,21 @@ interface MqttServiceInterface * @return mixed */ public function pubToMqtt($message, $topic, $toClientId); + + /** + * @param string|number $message 消息内容 + * @param string $topic 发布消息到主题,主题名 + * @param string $type 消息类型,cash或tts + * @param string $payId 支付方式,如“支付宝”、“微信”等 + * @param string $toClientId 终端id,如IMEI码 + * @param string $curClientId 当前客户端id + */ + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ); } \ No newline at end of file diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 5a8b802..4eaf580 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -2,9 +2,9 @@ namespace App\Service; +use App\Libs\MQTTClient; use App\Model\Order; use App\Model\Store; -use App\TaskWorker\MQTTClientTask; use Hyperf\Utils\ApplicationContext; class MqttSpeakerService implements MqttServiceInterface @@ -43,7 +43,47 @@ class MqttSpeakerService implements MqttServiceInterface */ public function pubToMqtt($message, $topic, $toClientId) { - $task = ApplicationContext::getContainer()->get(MQTTClientTask::class); - $task->publish($message, $topic, $toClientId); + $this->publish($message, $topic, $toClientId); + } + + /** + * @inheritDoc + */ + public function publish( + $message, + $topic, + $toClientId = '', + $type = '', + $payId = '', + $curClientId = '' + ) { + + $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); + $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + + if (env('MQTT_CERT')) { + $client->setEncryption(env('MQTT_CERT')); + } + + $msgArr = []; + if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { + $msgArr['cash'] = $message; + $payId AND $msgArr['payid'] = $payId; + } else { + $msgArr['message'] = $message; + } + + if (!empty($toClientId)) { + $topic .= '/'.$toClientId; + } + + $curClientId OR $curClientId = (string)rand(1,999999999); + $success = $client->sendConnect($curClientId); + + if ($success) { + $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); + $client->sendDisconnect(); + } + $client->close(); } } \ No newline at end of file diff --git a/app/TaskWorker/MQTTClientTask.php b/app/TaskWorker/MQTTClientTask.php deleted file mode 100644 index e49f562..0000000 --- a/app/TaskWorker/MQTTClientTask.php +++ /dev/null @@ -1,65 +0,0 @@ -getClient(); - - $msgArr = []; - if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { - $msgArr['cash'] = $message; - $payId AND $msgArr['payid'] = $payId; - } else { - $msgArr['message'] = $message; - } - - if (!empty($toClientId)) { - $topic .= '/'.$toClientId; - } - - $curClientId OR $curClientId = (string)rand(1,999999999); - $success = $this->mqttClient->sendConnect($curClientId); - - if ($success) { - $this->mqttClient->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); - $this->mqttClient->sendDisconnect(); - } - $this->mqttClient->close(); - } - - protected function getClient() - { - $this->mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); - $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); - - if (env('MQTT_CERT')) { - $this->mqttClient->setEncryption(env('MQTT_CERT')); - } - - return $this->mqttClient; - } -} \ No newline at end of file From 8133c86dc5ce0a60e9f61fe219c38fc16ca91494 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:48:14 +0800 Subject: [PATCH 62/72] debug mqttclient --- app/Service/MqttServiceInterface.php | 9 --------- app/Service/MqttSpeakerService.php | 19 ++++++++----------- 2 files changed, 8 insertions(+), 20 deletions(-) diff --git a/app/Service/MqttServiceInterface.php b/app/Service/MqttServiceInterface.php index 127b3cc..3148be2 100644 --- a/app/Service/MqttServiceInterface.php +++ b/app/Service/MqttServiceInterface.php @@ -10,15 +10,6 @@ interface MqttServiceInterface */ public function speakToStore($orderId, $isMain = true); - /** - * MQTT发布消息 - * @param $message - * @param $topic - * @param $toClientId - * @return mixed - */ - public function pubToMqtt($message, $topic, $toClientId); - /** * @param string|number $message 消息内容 * @param string $topic 发布消息到主题,主题名 diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 4eaf580..080e0c1 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -17,7 +17,7 @@ class MqttSpeakerService implements MqttServiceInterface */ public function speakToStore($orderId, $isMain = true) { - + var_dump('speaker-orderid', $orderId); // 获取订单 $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); if ($isMain) { @@ -26,26 +26,22 @@ class MqttSpeakerService implements MqttServiceInterface $orders = $orders->where(['id' => $orderId])->get()->toArray(); } + var_dump('speaker-orders', $orders); + if(empty($orders)) return; // 循环发送 foreach ($orders as $k => &$order) { - $order['template'] = "懒族生活支付到账".floatval($order['money'])."元"; + $order['template'] = "懒族支付到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); + var_dump('speaker-$order', $order); // 发布订阅消息 - $this->pubToMqtt($order['template'], self::TOPIC, $order['to_client_id']); + $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']); + var_dump('speaker-$res', $res); } } - /** - * @inheritDoc - */ - public function pubToMqtt($message, $topic, $toClientId) - { - $this->publish($message, $topic, $toClientId); - } - /** * @inheritDoc */ @@ -60,6 +56,7 @@ class MqttSpeakerService implements MqttServiceInterface $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT')); $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS')); + $client->setDebug(true); if (env('MQTT_CERT')) { $client->setEncryption(env('MQTT_CERT')); From 24df57265e413b28aee13bf0a475eb4f5dc4c6ae Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 14:54:44 +0800 Subject: [PATCH 63/72] Debug (cherry picked from commit b789d72128d10d4f0d33dc208c055d83685975db) --- app/Libs/MQTTClient.php | 6 +++++- app/Service/MqttSpeakerService.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index 56584c0..7c02ad7 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -218,6 +218,8 @@ class MQTTClient { * @return boolean Returns false if connection failed */ public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { + + var_dump('serverAddress', $this->serverAddress); if (!$this->serverAddress) return false; // Basic validation of clientid @@ -390,8 +392,9 @@ class MQTTClient { * @return boolean */ public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { + var_dump('connect:', $this->isConnected()); if(!$this->isConnected()) return false; - +var_dump('sendpublish', [$topic, $message, $qos]); if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; $packetId = $this->getNextPacketId(); @@ -405,6 +408,7 @@ class MQTTClient { $dupFlag = 0; $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); $this->debugMessage('Sending PUBLISH'); + var_dump('sendpublish-$payload', $header.$payload); $this->send($header . $payload); if($qos == self::MQTT_QOS1) { diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 080e0c1..617eb3a 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -76,7 +76,7 @@ class MqttSpeakerService implements MqttServiceInterface $curClientId OR $curClientId = (string)rand(1,999999999); $success = $client->sendConnect($curClientId); - + var_dump('$success', $success); if ($success) { $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); $client->sendDisconnect(); From 8145b74169ef66c9e12663f2d4ca5b60d1f70dd0 Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 15:04:00 +0800 Subject: [PATCH 64/72] =?UTF-8?q?=E5=8E=BB=E6=8E=89Debug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Libs/MQTTClient.php | 4 ---- app/Service/MqttSpeakerService.php | 7 +------ 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/app/Libs/MQTTClient.php b/app/Libs/MQTTClient.php index 7c02ad7..0d08a87 100644 --- a/app/Libs/MQTTClient.php +++ b/app/Libs/MQTTClient.php @@ -219,7 +219,6 @@ class MQTTClient { */ public function sendConnect($clientId, $cleanSession=false, $keepAlive=10, $timeout=5000) { - var_dump('serverAddress', $this->serverAddress); if (!$this->serverAddress) return false; // Basic validation of clientid @@ -392,9 +391,7 @@ class MQTTClient { * @return boolean */ public function sendPublish($topic, $message, $qos = self::MQTT_QOS1, $retain = 0) { - var_dump('connect:', $this->isConnected()); if(!$this->isConnected()) return false; -var_dump('sendpublish', [$topic, $message, $qos]); if($qos!=self::MQTT_QOS0 && $qos!=self::MQTT_QOS1 && $qos!=self::MQTT_QOS2) return false; $packetId = $this->getNextPacketId(); @@ -408,7 +405,6 @@ var_dump('sendpublish', [$topic, $message, $qos]); $dupFlag = 0; $header = $this->createHeader(self::MQTT_PUBLISH + ($dupFlag<<3) + ($qos<<1) + $retain, $payload); $this->debugMessage('Sending PUBLISH'); - var_dump('sendpublish-$payload', $header.$payload); $this->send($header . $payload); if($qos == self::MQTT_QOS1) { diff --git a/app/Service/MqttSpeakerService.php b/app/Service/MqttSpeakerService.php index 617eb3a..d058ae7 100644 --- a/app/Service/MqttSpeakerService.php +++ b/app/Service/MqttSpeakerService.php @@ -17,7 +17,7 @@ class MqttSpeakerService implements MqttServiceInterface */ public function speakToStore($orderId, $isMain = true) { - var_dump('speaker-orderid', $orderId); + // 获取订单 $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']); if ($isMain) { @@ -26,8 +26,6 @@ class MqttSpeakerService implements MqttServiceInterface $orders = $orders->where(['id' => $orderId])->get()->toArray(); } - var_dump('speaker-orders', $orders); - if(empty($orders)) return; // 循环发送 @@ -35,10 +33,8 @@ class MqttSpeakerService implements MqttServiceInterface $order['template'] = "懒族支付到账".floatval($order['money'])."元"; // 获取终端ID $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei'); - var_dump('speaker-$order', $order); // 发布订阅消息 $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']); - var_dump('speaker-$res', $res); } } @@ -76,7 +72,6 @@ class MqttSpeakerService implements MqttServiceInterface $curClientId OR $curClientId = (string)rand(1,999999999); $success = $client->sendConnect($curClientId); - var_dump('$success', $success); if ($success) { $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); $client->sendDisconnect(); From 4daa303f538a31c9f2c936b2c06c9e33578b42ac Mon Sep 17 00:00:00 2001 From: weigang Date: Fri, 14 Aug 2020 18:09:43 +0800 Subject: [PATCH 65/72] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E4=BD=BF?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 9e9604a..9efaf6b 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -46,6 +46,7 @@ class OrderService implements OrderServiceInterface // 计算当前订单可用红包优惠金额 $couponMoney = 0; + $receiveCouponIds = []; if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) { $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids'])); $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']); @@ -290,6 +291,11 @@ class OrderService implements OrderServiceInterface if (is_array($canUseConpons)&&!empty($canUseConpons)) { # 使用记录、更新当前优惠券 foreach ($canUseConpons as $key => &$coupon) { + + if (!in_array($coupon->id, $receiveCouponIds)) { + continue; + } + $couponUse = [ 'user_id' => $coupon->user_id, 'user_receive_id' => $coupon->id, From 38d7035b883eba51409cf1d0e75643a2ca52ba29 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 10:36:33 +0800 Subject: [PATCH 66/72] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B7=A8=E5=BA=97?= =?UTF-8?q?=E4=B8=8B=E5=8D=95=E5=95=86=E5=93=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index 9efaf6b..d8d0bdd 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -99,6 +99,7 @@ class OrderService implements OrderServiceInterface // 循环处理订单总额、子订单总额、商品、商户订单等信息 $orderAmountTotal = 0; # 总订单金额 + $orderGoods = []; foreach ($storeList as $key => &$item) { // 子订单数据处理 @@ -142,7 +143,7 @@ class OrderService implements OrderServiceInterface // 子订单内商品处理 $goodsAmountTotal = 0; - $orderGoods = []; + if (!is_array($item['good_list'])||empty($item['good_list'])) { Db::rollBack(); return '订单商品异常'; @@ -273,28 +274,12 @@ class OrderService implements OrderServiceInterface } // 处理红包的使用 - $canUseConpons = $this->couponService->getOrderCanUseCoupons( - $data['money'], - $data['market_id'], - $data['user_id'], - [ - 'receive.id', - 'receive.user_id', - 'receive.number', - 'receive.number_remain', - 'receive.system_coupon_user_id', - 'coupon.discounts', - 'coupon.discount_type', - ] - ); - - if (is_array($canUseConpons)&&!empty($canUseConpons)) { + $canUseCoupons = CouponUserRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id']) + ->whereIn('id', $receiveCouponIds) + ->get(); + if (is_array($canUseCoupons)&&!empty($canUseCoupons)) { # 使用记录、更新当前优惠券 - foreach ($canUseConpons as $key => &$coupon) { - - if (!in_array($coupon->id, $receiveCouponIds)) { - continue; - } + foreach ($canUseCoupons as $key => &$coupon) { $couponUse = [ 'user_id' => $coupon->user_id, From 7d831289ac52796392e437649994f2e34c2addbe Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 11:10:16 +0800 Subject: [PATCH 67/72] =?UTF-8?q?=E4=BC=98=E6=83=A0=E5=88=B8=E4=BD=BF?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/OrderService.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/app/Service/OrderService.php b/app/Service/OrderService.php index d8d0bdd..b637ac3 100644 --- a/app/Service/OrderService.php +++ b/app/Service/OrderService.php @@ -276,15 +276,15 @@ class OrderService implements OrderServiceInterface // 处理红包的使用 $canUseCoupons = CouponUserRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id']) ->whereIn('id', $receiveCouponIds) - ->get(); + ->get()->toArray(); if (is_array($canUseCoupons)&&!empty($canUseCoupons)) { # 使用记录、更新当前优惠券 foreach ($canUseCoupons as $key => &$coupon) { $couponUse = [ - 'user_id' => $coupon->user_id, - 'user_receive_id' => $coupon->id, - 'system_coupon_id' => $coupon->system_coupon_user_id, + 'user_id' => $coupon['user_id'], + 'user_receive_id' => $coupon['id'], + 'system_coupon_id' => $coupon['system_coupon_user_id'], 'order_main_id' => $orderMainId, 'use_time' => $currentTime, 'return_time' => 0, @@ -292,20 +292,21 @@ class OrderService implements OrderServiceInterface 'status' => 1, 'update_time' => 0, ]; + var_dump('$couponUse',$couponUse); $insertRes = CouponUserUse::query()->insert($couponUse); if ($insertRes) { - $numberRemain = $coupon->number_remain - 1; + $numberRemain = $coupon['number_remain'] - 1; if ($numberRemain == 0) { $status = 2; - } elseif ($numberRemain > 0 && $numberRemain < $coupon->number) { + } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) { $status = 1; - } elseif ($numberRemain == $coupon->number) { + } elseif ($numberRemain == $coupon['number']) { $status = 0; } - $upRes = CouponUserRec::query()->where(['id' => $coupon->id])->update(['number_remain' => $numberRemain, 'status' => $status]); + $upRes = CouponUserRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]); if (!$upRes) { Db::rollBack(); @@ -313,7 +314,7 @@ class OrderService implements OrderServiceInterface } // 缓存使用记录 - $usedRes = $this->couponService->cacheTodayCouponUsed($coupon->user_id, $coupon->system_coupon_user_id, $coupon->id); + $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']); if (!$usedRes) { Db::rollBack(); return '优惠券使用失败'; From f9b0fce54f0b50e2f11bbdce6a8e411906730e41 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 12:06:25 +0800 Subject: [PATCH 68/72] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 ++-- config/autoload/dependencies.php | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index a94b07f..1d2c1be 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -15,7 +15,7 @@ use App\Model\SystemConfig; use App\Model\Users; use App\Service\DeviceServiceInterface; use App\Service\FeiePrintServiceInterface; -use App\Service\MiniprogramService; +use App\Service\MiniprogramServiceInterface; use App\Service\MqttServiceInterface; use App\Service\UserServiceInterface; use EasyWeChat\Factory; @@ -43,7 +43,7 @@ class NotifyController extends BaseController /** * @Inject - * @var MiniprogramService + * @var MiniprogramServiceInterface */ protected $miniprogramService; diff --git a/config/autoload/dependencies.php b/config/autoload/dependencies.php index 1557ca3..7c683c7 100644 --- a/config/autoload/dependencies.php +++ b/config/autoload/dependencies.php @@ -21,4 +21,6 @@ return [ \App\Service\CouponServiceInterface::class => \App\Service\CouponService::class, \App\Service\MqttServiceInterface::class => \App\Service\MqttSpeakerService::class, \App\Service\FeiePrintServiceInterface::class => \App\Service\FeiePrintService::class, + \App\Service\MiniprogramServiceInterface::class => \App\Service\MiniprogramService::class, + \App\Service\UserServiceInterface::class => \App\Service\UserService::class, ]; From 69316fac903b99428cec2cf157573e5a0a41f678 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:10:47 +0800 Subject: [PATCH 69/72] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 4 +++- app/Service/UserService.php | 10 +++++----- app/Service/UserServiceInterface.php | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index 1d2c1be..fb4de38 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -29,6 +29,8 @@ use Symfony\Component\HttpFoundation\Request; class NotifyController extends BaseController { + const AWARD_LIMIT_AMOUNT = 3; + /** * @Inject * @var MqttServiceInterface @@ -321,7 +323,7 @@ class NotifyController extends BaseController $needAward = true; } else { $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); - if ($isStoreFirstOrderToday) { + if ($isStoreFirstOrderToday && $orderItem['money'] >= self::AWARD_LIMIT_AMOUNT) { $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); // 流水 $record = [ diff --git a/app/Service/UserService.php b/app/Service/UserService.php index 6881a6f..c045850 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -22,8 +22,8 @@ class UserService implements UserServiceInterface $exist = OrderMain::query() ->where(['user_id' => $user_id]) ->where(function ($query){ - $query->where('state', 'in', [4,5,10]) - ->orWhere('dm_state', 'in', [2,3]); + $query->where('state', 'in', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) + ->orWhere('dm_state', 'in', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); }) ->exists(); @@ -63,13 +63,13 @@ class UserService implements UserServiceInterface /** * @inheritDoc */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id) { return !Order::query() - ->where(['user_id' => $user_id, 'store_id' => $store_id, 'dm_state' => 2]) + ->where(['user_id' => $user_id, 'store_id' => $store_id]) + ->whereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]) ->where('time_add', '>=', date('Y-m-d 00:00:00')) ->where('time_add', '<=', date('Y-m-d 23:59:59')) - ->where('money', '>=', $limit_amount) ->where('id', '!=', $current_order_id) ->exists(); } diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 5f7bbd3..2e41493 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -23,6 +23,6 @@ interface UserServiceInterface * @param int $limit_amount * @return mixed */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3); + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id); } \ No newline at end of file From 378a14b048dce814df024700c3681e735008a7cf Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:27:48 +0800 Subject: [PATCH 70/72] =?UTF-8?q?=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Service/UserService.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Service/UserService.php b/app/Service/UserService.php index c045850..a665734 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -22,8 +22,8 @@ class UserService implements UserServiceInterface $exist = OrderMain::query() ->where(['user_id' => $user_id]) ->where(function ($query){ - $query->where('state', 'in', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) - ->orWhere('dm_state', 'in', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); + $query->whereIn('state', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) + ->orWhereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); }) ->exists(); From 0785999db0f909ffc057359ecfbae5cf02cffe62 Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 18:55:15 +0800 Subject: [PATCH 71/72] =?UTF-8?q?=E5=95=86=E6=88=B7=E5=A5=96=E5=8A=B1?= =?UTF-8?q?=EF=BC=88=E5=B9=B3=E5=8F=B0=E6=96=B0=E7=94=A8=E6=88=B7BUG?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 2 +- app/Service/UserService.php | 4 +++- app/Service/UserServiceInterface.php | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index fb4de38..c762745 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -309,7 +309,7 @@ class NotifyController extends BaseController StoreAccount::query()->insert(array_merge($recordBase, $record)); // 平台新用户奖励给商户 - $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id']); + $isStageNewUser = $this->userService->isStageNewUser($orderItem['user_id'], $orderMain->id); $needAward = false; $awardAmount = 0; if ($isStageNewUser) { diff --git a/app/Service/UserService.php b/app/Service/UserService.php index a665734..8f43371 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -15,12 +15,14 @@ class UserService implements UserServiceInterface * 判定条件: * 没有在平台下过单(包括线上和线下) * @param $user_id + * @param $order_main_id * @return mixed|void */ - public function isStageNewUser($user_id): bool + public function isStageNewUser($user_id, $order_main_id): bool { $exist = OrderMain::query() ->where(['user_id' => $user_id]) + ->where('id', '!=', $order_main_id) ->where(function ($query){ $query->whereIn('state', [OrderMain::ORDER_STATE_COMPLETE,OrderMain::ORDER_STATE_EVALUATED,OrderMain::ORDER_STATE_UNREFUND]) ->orWhereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]); diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 2e41493..8742ce9 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -9,9 +9,10 @@ interface UserServiceInterface /** * 是否平台新用户 * @param $user_id + * @param $order_main_id * @return mixed */ - public function isStageNewUser($user_id): bool; + public function isStageNewUser($user_id, $order_main_id): bool; public function saveUserUnionid($openid,$unionid); From f5ad8df2d881f0279602e673b2a7346c8f36f55c Mon Sep 17 00:00:00 2001 From: weigang Date: Mon, 17 Aug 2020 19:13:42 +0800 Subject: [PATCH 72/72] =?UTF-8?q?=E5=A5=96=E5=8A=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controller/NotifyController.php | 2 +- app/Service/UserService.php | 3 ++- app/Service/UserServiceInterface.php | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Controller/NotifyController.php b/app/Controller/NotifyController.php index c762745..9f47c82 100644 --- a/app/Controller/NotifyController.php +++ b/app/Controller/NotifyController.php @@ -322,7 +322,7 @@ class NotifyController extends BaseController ]; $needAward = true; } else { - $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id']); + $isStoreFirstOrderToday = $this->userService->isStoreFirstOrderToday($orderItem['user_id'],$orderItem['store_id'],$orderItem['id'], self::AWARD_LIMIT_AMOUNT); if ($isStoreFirstOrderToday && $orderItem['money'] >= self::AWARD_LIMIT_AMOUNT) { $awardAmount = SystemConfig::query()->where(['type' => 1, 'menu_name' => 'award_each_order'])->value('value'); // 流水 diff --git a/app/Service/UserService.php b/app/Service/UserService.php index 8f43371..b5cc5fb 100644 --- a/app/Service/UserService.php +++ b/app/Service/UserService.php @@ -65,13 +65,14 @@ class UserService implements UserServiceInterface /** * @inheritDoc */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id) + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3) { return !Order::query() ->where(['user_id' => $user_id, 'store_id' => $store_id]) ->whereIn('dm_state', [OrderMain::ORDER_STATE_UNTAKE,OrderMain::ORDER_STATE_DELIVERY]) ->where('time_add', '>=', date('Y-m-d 00:00:00')) ->where('time_add', '<=', date('Y-m-d 23:59:59')) + ->where('money', '>=', $limit_amount) ->where('id', '!=', $current_order_id) ->exists(); } diff --git a/app/Service/UserServiceInterface.php b/app/Service/UserServiceInterface.php index 8742ce9..2920d53 100644 --- a/app/Service/UserServiceInterface.php +++ b/app/Service/UserServiceInterface.php @@ -24,6 +24,6 @@ interface UserServiceInterface * @param int $limit_amount * @return mixed */ - public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id); + public function isStoreFirstOrderToday($user_id, $store_id, $current_order_id, $limit_amount = 3); } \ No newline at end of file