Prechádzať zdrojové kódy

在 Laravel 电商项目中基于 Micro API 调用用户微服务接口

chenlong 4 rokov pred
rodič
commit
917de74bdc

+ 17 - 32
app/Http/Controllers/Auth/RegisterController.php

@@ -2,70 +2,55 @@
 
 namespace App\Http\Controllers\Auth;
 
-use App\Shop\Customers\Customer;
+use App\MicroApi\Exceptions\RpcException;
+use App\MicroApi\Items\UserItem;
+use App\MicroApi\Services\UserService;
 use App\Http\Controllers\Controller;
-use App\Shop\Customers\Repositories\Interfaces\CustomerRepositoryInterface;
-use App\Shop\Customers\Requests\CreateCustomerRequest;
 use App\Shop\Customers\Requests\RegisterCustomerRequest;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Facades\Validator;
 use Illuminate\Foundation\Auth\RegistersUsers;
 
 class RegisterController extends Controller
 {
-    /*
-    |--------------------------------------------------------------------------
-    | Register Controller
-    |--------------------------------------------------------------------------
-    |
-    | This controller handles the registration of new users as well as their
-    | validation and creation. By default this controller uses a trait to
-    | provide this functionality without requiring any additional code.
-    |
-    */
-
     use RegistersUsers;
 
-    /**
-     * Where to redirect users after registration.
-     *
-     * @var string
-     */
     protected $redirectTo = '/accounts';
 
-    private $customerRepo;
+    private $userService;
 
     /**
      * Create a new controller instance.
-     * @param CustomerRepositoryInterface $customerRepository
+     * @param UserService $userService
      */
-    public function __construct(CustomerRepositoryInterface $customerRepository)
+    public function __construct(UserService $userService)
     {
         $this->middleware('guest');
-        $this->customerRepo = $customerRepository;
+        $this->userService = $userService;
     }
 
     /**
      * Create a new user instance after a valid registration.
      *
      * @param  array  $data
-     * @return Customer
+     * @return UserItem
+     * @throws RpcException
      */
     protected function create(array $data)
     {
-        return $this->customerRepo->createCustomer($data);
+        return $this->userService->create($data);
     }
 
     /**
      * @param RegisterCustomerRequest $request
      * @return \Illuminate\Http\RedirectResponse
+     * @throws RpcException
      */
     public function register(RegisterCustomerRequest $request)
     {
-        $customer = $this->create($request->except('_method', '_token'));
-        Auth::login($customer);
+        $data = $request->except('_method', '_token');
+        $user = $this->create($data);
+        $token = $this->userService->auth($data);  // 获取 Token
+        session([md5($token) => $user]);  // 存储用户信息
 
-        return redirect()->route('accounts');
+        return redirect()->route('user.profile')->cookie('jwt-token', $token);
     }
-}
+}

+ 22 - 1
app/Http/Controllers/Front/AccountsController.php

@@ -9,6 +9,9 @@ use App\Http\Controllers\Controller;
 use App\Shop\Orders\Order;
 use App\Shop\Orders\Transformers\OrderTransformable;
 
+use App\MicroApi\Services\UserService;
+use Illuminate\Http\Request;
+
 class AccountsController extends Controller
 {
     use OrderTransformable;
@@ -23,18 +26,26 @@ class AccountsController extends Controller
      */
     private $courierRepo;
 
+    /**
+     * @var UserService
+     */
+    private $userService;
+
     /**
      * AccountsController constructor.
      *
      * @param CourierRepositoryInterface $courierRepository
      * @param CustomerRepositoryInterface $customerRepository
+     * @param UserService $userService
      */
     public function __construct(
         CourierRepositoryInterface $courierRepository,
-        CustomerRepositoryInterface $customerRepository
+        CustomerRepositoryInterface $customerRepository,
+        UserService $userService
     ) {
         $this->customerRepo = $customerRepository;
         $this->courierRepo = $courierRepository;
+        $this->userService = $userService;
     }
 
     public function index()
@@ -58,4 +69,14 @@ class AccountsController extends Controller
             'addresses' => $addresses
         ]);
     }
+
+    public function profile(Request $request)
+    {
+        $token = $request->cookie('jwt-token');
+        if (empty($token) || !$this->userService->isAuth($token)) {
+            return '尚未登录';
+        }
+        $user = session(md5($token));
+        dd($user);
+    }
 }

+ 27 - 0
app/MicroApi/Facades/HttpClient.php

@@ -0,0 +1,27 @@
+<?php
+namespace App\MicroApi\Facades;
+
+use Illuminate\Support\Facades\Facade;
+use Psr\Http\Message\RequestInterface;
+use Psr\Http\Message\ResponseInterface;
+
+/**
+ * @method static ResponseInterface get(string $uri, array $options = [])
+ * @method static ResponseInterface post(string $uri, array $options = [])
+ * @method static ResponseInterface send(RequestInterface $request, array $options = [])
+ * @method static ResponseInterface request(string $method, string $uri, array $options = [])
+ *
+ * @see \GuzzleHttp\Client
+ */
+class HttpClient extends Facade
+{
+    /**
+     * Get the registered name of the component.
+     *
+     * @return string
+     */
+    protected static function getFacadeAccessor()
+    {
+        return 'HttpClient';
+    }
+}

+ 9 - 0
app/MicroApi/Items/TokenItem.php

@@ -0,0 +1,9 @@
+<?php
+# app/MicroApi/Items/TokenItem.php
+namespace App\MicroApi\Items;
+
+class TokenItem
+{
+    public $token;
+    public $valid;
+}

+ 12 - 0
app/MicroApi/Items/UserItem.php

@@ -0,0 +1,12 @@
+<?php
+# app/MicroApi/Services/ResponseHandler.php
+namespace App\MicroApi\Items;
+
+class UserItem
+{
+    public $id;
+    public $name;
+    public $email;
+    public $password;
+    public $status;
+}

+ 8 - 0
app/MicroApi/RpcException.php

@@ -0,0 +1,8 @@
+<?php
+# app/MicroApi/Exceptions/RpcException.php
+namespace App\MicroApi\Exceptions;
+
+class RpcException extends \Exception
+{
+
+}

+ 16 - 0
app/MicroApi/Services/DataHandler.php

@@ -0,0 +1,16 @@
+<?php
+# app/MicroApi/Services/DataHandler.php
+namespace App\MicroApi\Services;
+
+trait DataHandler
+{
+    public function encode($data)
+    {
+        return json_encode($data);
+    }
+
+    public function decode($content)
+    {
+        return json_decode($content);
+    }
+}

+ 110 - 0
app/MicroApi/Services/UserService.php

@@ -0,0 +1,110 @@
+<?php
+namespace App\MicroApi\Services;
+
+use App\MicroApi\Exceptions\RpcException;
+use App\MicroApi\Facades\HttpClient;
+use App\MicroApi\Items\TokenItem;
+use App\MicroApi\Items\UserItem;
+use Illuminate\Support\Facades\Log;
+
+class UserService
+{
+    use DataHandler;
+
+    protected $servicePrefix = '/user/userService';
+
+    /**
+     * @param $data
+     * @return UserItem
+     * @throws RpcException
+     */
+    public function create($data)
+    {
+        $path = $this->servicePrefix . '/create';
+        $user = new UserItem();
+        if (!empty($data['name'])) {
+            $user->name = $data['name'];
+        }
+        if (!empty($data['email'])) {
+            $user->email = $data['email'];
+        }
+        if (!empty($data['password'])) {
+            $user->password = $data['password'];
+        }
+        $options = ['json' => $user];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.UserService.create Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return $result->user;
+    }
+
+    public function getAll()
+    {
+        $path = $this->servicePrefix . '/getAll';
+        try {
+            $response = HttpClient::get($path);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.UserService.getAll Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return $result->users;
+    }
+
+    public function getById($id)
+    {
+        $path = $this->servicePrefix . '/get';
+        $user = new UserItem();
+        $user->id = $id;
+        $options = ['json' => $user];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.UserService.getByCondition Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return $result->user;
+    }
+
+    public function auth($credentials)
+    {
+        $path = $this->servicePrefix . '/auth';
+        $user = new UserItem();
+        if (!empty($credentials['email'])) {
+            $user->email = $credentials['email'];
+        }
+        if (!empty($credentials['password'])) {
+            $user->password = $credentials['password'];
+        }
+        $options = ['json' => $user];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.UserService.auth Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return $result->token;
+    }
+
+    public function isAuth($token)
+    {
+        $path = $this->servicePrefix . '/validateToken';
+        $item = new TokenItem();
+        $item->token = $token;
+        $options = ['json' => $item];
+        try {
+            $response = HttpClient::post($path, $options);
+        } catch (\Exception $exception) {
+            Log::error("MicroApi.UserService.auth Call Failed: " . $exception->getMessage());
+            throw new RpcException("调用远程服务失败");
+        }
+        $result = $this->decode($response->getBody()->getContents());
+        return  $result->valid;
+    }
+}

+ 11 - 1
app/Providers/AppServiceProvider.php

@@ -4,6 +4,7 @@ namespace App\Providers;
 
 use Illuminate\Support\ServiceProvider;
 use Laravel\Cashier\Cashier;
+use GuzzleHttp\Client as HttpClient;
 
 class AppServiceProvider extends ServiceProvider
 {
@@ -24,6 +25,15 @@ class AppServiceProvider extends ServiceProvider
      */
     public function register()
     {
-        //
+        // 以单例模式绑定 HttpClient 实例到 App 容器
+        $this->app->singleton('HttpClient', function ($app) {
+            return new HttpClient([
+                'base_uri' => config('services.micro.api_gateway'),
+                'timeout'  => config('services.micro.timeout'),
+                'headers'  => [
+                    'Content-Type' => 'application/json'
+                ]
+            ]);
+        });
     }
 }

+ 5 - 0
config/services.php

@@ -35,4 +35,9 @@ return [
         'secret' => env('STRIPE_SECRET'),
     ],
 
+    'micro' => [
+        'api_gateway' => env('MICRO_API_GATEWAY', 'http://localhost:8080'),
+        'timeout' => env('MICRO_TIMEOUT', 3.0)   //网关超时时间
+    ]
+
 ];

+ 1 - 0
routes/web.php

@@ -76,6 +76,7 @@ Route::namespace('Auth')->group(function () {
 
 Route::namespace('Front')->group(function () {
     Route::get('/', 'HomeController@index')->name('home');
+    Route::get('/profile', 'AccountsController@profile')->name('user.profile');
     Route::group(['middleware' => ['auth', 'web']], function () {
 
         Route::namespace('Payments')->group(function () {