Browse Source

ErrorCode使用整理(通过异常)、service的基础统一规范(make、check、remove)、用户手机号绑定

master
weigang 5 years ago
parent
commit
e2ec76680c
  1. 4
      app/Constants/v3/ActivityType.php
  2. 47
      app/Constants/v3/ErrorCode.php
  3. 5
      app/Constants/v3/OrderState.php
  4. 5
      app/Constants/v3/OrderType.php
  5. 5
      app/Constants/v3/Payment.php
  6. 17
      app/Constants/v3/SmsTemplateCode.php
  7. 17
      app/Constants/v3/SsdbKeys.php
  8. 9
      app/Constants/v3/Tabs.php
  9. 7
      app/Controller/BaseController.php
  10. 41
      app/Controller/v3/SmsController.php
  11. 44
      app/Controller/v3/UserController.php
  12. 29
      app/Exception/ErrorCodeException.php
  13. 48
      app/Exception/Handler/ErrorCodeExceptionHandler.php
  14. 27
      app/Middleware/Auth/UserMiddleware.php
  15. 10
      app/Model/v3/User.php
  16. 2
      app/Request/UserRequest.php
  17. 44
      app/Request/v3/UserBindTelRequest.php
  18. 41
      app/Request/v3/VerifyCodeRequest.php
  19. 20
      app/Service/v3/Implementations/HelperService.php
  20. 78
      app/Service/v3/Implementations/SmsAliService.php
  21. 38
      app/Service/v3/Implementations/UserBindService.php
  22. 89
      app/Service/v3/Implementations/VerifyCodeService.php
  23. 8
      app/Service/v3/Interfaces/HelperServiceInterface.php
  24. 11
      app/Service/v3/Interfaces/SmsServiceInterface.php
  25. 10
      app/Service/v3/Interfaces/UserBindServiceInterface.php
  26. 10
      app/Service/v3/Interfaces/VerifyCodeServiceInterface.php
  27. 5
      config/autoload/dependencies.php
  28. 5
      config/autoload/exceptions.php
  29. 1
      config/config.php
  30. 3
      config/routes.php

4
app/Constants/v3/ActivityType.php

@ -3,7 +3,11 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class ActivityType extends AbstractConstants
{
/**

47
app/Constants/v3/ErrorCode.php

@ -3,32 +3,73 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class ErrorCode extends AbstractConstants
{
/************************************/
/* 应用或系统相关,参考HTTP STATUS */
/************************************/
/**
* 服务器内部错误
* @Message("服务器内部错误")
*/
const SERVER_ERROR=500;
const SERVER_ERROR = 500;
/************************************/
/* 订单相关 601-650 */
/************************************/
/************************************/
/* 支付相关 651-700 */
/************************************/
/************************************/
/* 用户相关 701-750 */
/************************************/
/**
* 验证码错误或已失效
* @Message("验证码错误或已失效")
*/
const INVALID_VERIFY_CODE = 701;
/**
* 电话号码绑定失败
* @Message("电话号码绑定失败")
*/
const BIND_TEL_ERROR = 702;
/**
* 电话号码解绑失败
* @Message("电话号码解绑失败")
*/
const UNBIND_TEL_ERROR = 703;
/************************************/
/* 定位相关 751-800 */
/************************************/
/************************************/
/* 公共相关 1001-1100 */
/************************************/
/**
* 获取验证码失败
* @Message("获取验证码失败")
*/
const VERIFY_CODE_ERROR = 1001;
/**
* 验证码已发送,请勿重复请求
* @Message("验证码已发送,请勿重复请求")
*/
const VERIFY_CODE_SENDED = 1002;
/**
* 短信发送失败
* @Message("短信发送失败")
*/
const SMS_SEND_FAILURE = 1003;
}

5
app/Constants/v3/OrderState.php

@ -3,11 +3,10 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* 订单状态
* Class OrderState
* @package App\Constants\v3
* @Constants
*/
class OrderState extends AbstractConstants
{

5
app/Constants/v3/OrderType.php

@ -3,11 +3,10 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* 订单类型
* Class OrderType
* @package App\Constants\v3
* @Constants
*/
class OrderType extends AbstractConstants
{

5
app/Constants/v3/Payment.php

@ -3,11 +3,10 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* 支付相关
* Class Payment
* @package App\Constants\v3
* @Constants
*/
class Payment extends AbstractConstants
{

17
app/Constants/v3/SmsTemplateCode.php

@ -0,0 +1,17 @@
<?php
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class SmsTemplateCode extends AbstractConstants
{
/**
* @Message("短信验证码")
*/
const ALI_VERIFY_CODE = 'SMS_200690862';
}

17
app/Constants/v3/SsdbKeys.php

@ -0,0 +1,17 @@
<?php
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class SsdbKeys extends AbstractConstants
{
/**
* @Message("短信验证码")
*/
const VERIFY_CODE = 'verify_code_';
}

9
app/Constants/v3/Tabs.php

@ -2,12 +2,13 @@
namespace App\Constants\v3;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* 选项卡标识
* Class Tabs
* @package App\Constants\v3
* @Constants
*/
class Tabs
class Tabs extends AbstractConstants
{
/**
* @Message("小程序首页推荐")

7
app/Controller/BaseController.php

@ -11,12 +11,19 @@ declare(strict_types=1);
*/
namespace App\Controller;
use App\Service\v3\Interfaces\HelperServiceInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Di\Annotation\Inject;
class BaseController extends AbstractController
{
/**
* @Inject
* @var HelperServiceInterface
*/
protected $helperService;
public function w7result($statusCode,$data = ''){
return $this->response

41
app/Controller/v3/SmsController.php

@ -0,0 +1,41 @@
<?php
namespace App\Controller\v3;
use App\Controller\BaseController;
use App\Request\v3\VerifyCodeRequest;
use App\Service\v3\Interfaces\VerifyCodeServiceInterface;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
/**
* 短信相关
* Class SmsController
* @package App\Controller\v3
*/
class SmsController extends BaseController
{
/**
* @Inject
* @var VerifyCodeServiceInterface
*/
protected $verifyCodeService;
/**
* 获取手机验证码,发送验证码短信
* 1、获取手机号并验证
* 2、发送短信
* 3、存储验证码,保留用于校验,有失效时间
* @param VerifyCodeRequest $request
* @return ResponseInterface
*/
public function getVerifyCode(VerifyCodeRequest $request)
{
// 获取参数
$params = $request->validated();
// 获取并发送验证码
$this->verifyCodeService->make($params['user_id'], $params['tel']);
return $this->success([]);
}
}

44
app/Controller/v3/UserController.php

@ -0,0 +1,44 @@
<?php
namespace App\Controller\v3;
use App\Constants\v3\ErrorCode;
use App\Controller\BaseController;
use App\Request\v3\UserBindTelRequest;
use App\Service\v3\Interfaces\UserBindServiceInterface;
use App\Service\v3\Interfaces\VerifyCodeServiceInterface;
use Hyperf\Di\Annotation\Inject;
/**
* 用户相关
* Class UserController
* @package App\Controller\v3
*/
class UserController extends BaseController
{
/**
* @Inject
* @var VerifyCodeServiceInterface
*/
protected $verifyCodeService;
/**
* @Inject
* @var UserBindServiceInterface
*/
protected $userBindService;
public function bindTel(UserBindTelRequest $request)
{
// 获取参数
$params = $request->validated();
// 校验验证码
$this->verifyCodeService->check($params['user_id'], $params['tel'], $params['verify_code']);
// 绑定
$this->userBindService->makeTel($params['user_id'], $params['tel']);
return $this->success([]);
}
}

29
app/Exception/ErrorCodeException.php

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Exception;
use App\Constants\v3\ErrorCode;
use Hyperf\Server\Exception\ServerException;
use Throwable;
class ErrorCodeException extends ServerException
{
public function __construct(int $code = 0, string $message = null, Throwable $previous = null)
{
if (is_null($message)) {
$message = ErrorCode::getMessage($code);
}
parent::__construct($message, $code, $previous);
}
}

48
app/Exception/Handler/ErrorCodeExceptionHandler.php

@ -0,0 +1,48 @@
<?php
namespace App\Exception\Handler;
use App\Exception\ErrorCodeException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class ErrorCodeExceptionHandler extends ExceptionHandler
{
/**
* @var StdoutLoggerInterface
*/
protected $logger;
public function __construct(StdoutLoggerInterface $logger)
{
$this->logger = $logger;
}
public function handle(Throwable $throwable, ResponseInterface $response)
{
$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
$this->logger->error($throwable->getTraceAsString());
$this->stopPropagation();
$content = json_encode([
"status" => 'error',
"code" => $throwable->getCode(),
"result" => [],
"message" => $throwable->getMessage()
]);
return $response->withHeader('Content-Type', 'application/json')
->withStatus(200)
->withBody(new SwooleStream($content));
}
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof ErrorCodeException;
}
}

27
app/Middleware/Auth/UserMiddleware.php

@ -2,14 +2,39 @@
namespace App\Middleware\Auth;
use Hyperf\HttpServer\Contract\RequestInterface as HttpRequest;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class UserMiddleware implements MiddlewareInterface
class UserMiddleware implements MiddlewareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var HttpResponse
*/
protected $response;
/**
* @var HttpRequest
*/
protected $request;
public function __construct(ContainerInterface $container, HttpResponse $response, HttpRequest $request)
{
$this->container = $container;
$this->response = $response;
$this->request = $request;
}
/**
* @inheritDoc
*/

10
app/Model/v3/User.php

@ -0,0 +1,10 @@
<?php
namespace App\Model\v3;
use App\Model\Model;
class User extends Model
{
protected $table = 'lanzu_user';
}

2
app/Request/UserRequest.php

@ -22,7 +22,7 @@ class UserRequest extends FormRequest
public function rules(): array
{
return [
'user_id' => 'required|nonempty|integer|exists:ims_cjdc_user,id',
'user_id' => 'required|nonempty|integer|exists:lanzu_user,id',
];
}

44
app/Request/v3/UserBindTelRequest.php

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Request\v3;
use App\Request\BaseFormRequest;
class UserBindTelRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'user_id' => 'required|nonempty|exists_enable:ims_cjdc_user,id',
'tel' => 'required|nonempty|tel',
'verify_code' => 'required|nonempty|numeric|strlen:6,6',
];
}
/**
* @return array
*/
public function messages(): array
{
return [
'user_id.*' => ':attribute未登录或无效',
'tel.*' => ':attribute无效',
'verify_code.*' => ':attribute格式有误',
];
}
public function attributes(): array
{
return [
'user_id' => '用户',
'tel' => '手机号码',
'verify_code' => '验证码',
];
}
}

41
app/Request/v3/VerifyCodeRequest.php

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Request\v3;
use App\Request\BaseFormRequest;
class VerifyCodeRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'user_id' => 'required|nonempty|exists_enable:ims_cjdc_user,id',
'tel' => 'required|nonempty|tel',
];
}
/**
* @return array
*/
public function messages(): array
{
return [
'user_id.*' => ':attribute未登录或无效',
'tel.*' => ':attribute无效',
];
}
public function attributes(): array
{
return [
'user_id' => '用户',
'tel' => '手机号码',
];
}
}

20
app/Service/v3/Implementations/HelperService.php

@ -0,0 +1,20 @@
<?php
namespace App\Service\v3\Implementations;
use App\Service\v3\Interfaces\HelperServiceInterface;
class HelperService implements HelperServiceInterface
{
public function makeNumCode($length)
{
// 获取验证码
$codeArr = array_map(function ($item) {
return mt_rand(0,9);
}, array_pad([], $length, 0));
// 返回验证码
return implode('', $codeArr);
}
}

78
app/Service/v3/Implementations/SmsAliService.php

@ -0,0 +1,78 @@
<?php
namespace App\Service\v3\Implementations;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Constants\v3\ErrorCode;
use App\Exception\ErrorCodeException;
use Exception;
use App\Commons\Log;
use App\Constants\v3\SmsTemplateCode;
use Hyperf\Di\Annotation\Inject;
use App\Service\v3\Interfaces\SmsServiceInterface;
class SmsAliService implements SmsServiceInterface
{
/**
* @Inject
* @var Log
*/
protected $log;
public function send($tel, $template, $templateParams)
{
try {
$aliSms = config('alisms');
AlibabaCloud::accessKeyClient($aliSms['app_key'], $aliSms['app_secret'])
->regionId($aliSms['regionid'])
->asDefaultClient();
$result = AlibabaCloud::rpc()
->product($aliSms['product'])
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host($aliSms['host'])
->options([
'query' => [
'RegionId' => $aliSms['regionid'],
'PhoneNumbers' => $tel,
'SignName' => $aliSms['sign_name'],
'TemplateCode' => $template,
'TemplateParam' => $templateParams,
],
])
->request();
return $result->toArray();
} catch (ClientException $e) {
$this->log->event('alisms', ['alisms_error_ClientException' => $e->getErrorMessage()]);
throw new ErrorCodeException(ErrorCode::SMS_SEND_FAILURE);
} catch (ServerException $e) {
$this->log->event('alisms', ['alisms_error_ServerException' => $e->getErrorMessage()]);
throw new ErrorCodeException(ErrorCode::SMS_SEND_FAILURE);
} catch (Exception $e) {
$this->log->event('alisms', ['alisms_error_Exception' => $e->getErrorMessage()]);
throw new ErrorCodeException(ErrorCode::SMS_SEND_FAILURE);
}
}
public function makeVerifyCode($tel, $code)
{
$params = ['user_name' => '疯狂的水叔叔', 'market_name' => '验证码', 'money' => $code];
return $this->send($tel, SmsTemplateCode::ALI_VERIFY_CODE, json_encode($params));
}
public function checkVerifyCode($tel, $code)
{
// TODO: Implement checkVerifyCode() method.
}
public function removeVerifyCode($tel, $code)
{
// TODO: Implement removeVerifyCode() method.
}
}

38
app/Service/v3/Implementations/UserBindService.php

@ -0,0 +1,38 @@
<?php
namespace App\Service\v3\Implementations;
use App\Constants\v3\ErrorCode;
use App\Exception\ErrorCodeException;
use App\Model\v3\User;
use App\Service\v3\Interfaces\UserBindServiceInterface;
class UserBindService implements UserBindServiceInterface
{
public function makeTel($userId, $tel)
{
$user = User::find($userId);
$user->tel = $tel;
if (!$user->save()) {
throw new ErrorCodeException(ErrorCode::BIND_TEL_ERROR);
}
return true;
}
public function checkTel($userId)
{
$user = User::find($userId);
return $user->tel ? true : false;
}
public function removeTel($userId)
{
$user = User::find($userId);
$user->tel = '';
if (!$user->save()) {
throw new ErrorCodeException(ErrorCode::UNBIND_TEL_ERROR);
}
return true;
}
}

89
app/Service/v3/Implementations/VerifyCodeService.php

@ -0,0 +1,89 @@
<?php
namespace App\Service\v3\Implementations;
use App\Constants\v3\ErrorCode;
use App\Constants\v3\SsdbKeys;
use App\Exception\BusinessException;
use App\Exception\ErrorCodeException;
use App\Service\v3\Interfaces\HelperServiceInterface;
use App\Service\v3\Interfaces\SmsServiceInterface;
use App\Service\v3\Interfaces\VerifyCodeServiceInterface;
use App\TaskWorker\SSDBTask;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
class VerifyCodeService implements VerifyCodeServiceInterface
{
/**
* @Inject
* @var SmsServiceInterface
*/
protected $smsService;
/**
* @Inject
* @var HelperServiceInterface
*/
protected $helperService;
public function make($userId, $tel)
{
// 获取验证码
$verifyCode = $this->helperService->makeNumCode(6);
// 存到SSDB
$ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
$setRes = $ssdbClient->exec(
"setnx",
SsdbKeys::VERIFY_CODE.$userId.'_'.$tel,
$verifyCode
);
if (!$setRes) {
throw new ErrorCodeException(ErrorCode::VERIFY_CODE_SENDED);
}
$expireRes = $ssdbClient->exec(
'expire',
SsdbKeys::VERIFY_CODE.$userId.'_'.$tel,
900
);
if (!$expireRes) {
throw new ErrorCodeException(ErrorCode::VERIFY_CODE_ERROR);
}
// 发送短信
$smsRes = $this->smsService->makeVerifyCode($tel, $verifyCode);
if (!$smsRes) {
throw new ErrorCodeException(ErrorCode::VERIFY_CODE_ERROR);
}
return true;
}
public function check($userId, $tel, $verifyCode)
{
// 获取验证码并验证
$ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
$code = $ssdbClient->exec(
"get",
SsdbKeys::VERIFY_CODE.$userId.'_'.$tel
);
if (empty($code) || $verifyCode!=$code) {
throw new ErrorCodeException(ErrorCode::INVALID_VERIFY_CODE);
}
$this->remove($userId, $tel);
return true;
}
public function remove($userId, $tel)
{
$ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
return $ssdbClient->exec(
'del',
SsdbKeys::VERIFY_CODE.$userId.'_'.$tel
);
}
}

8
app/Service/v3/Interfaces/HelperServiceInterface.php

@ -0,0 +1,8 @@
<?php
namespace App\Service\v3\Interfaces;
interface HelperServiceInterface
{
public function makeNumCode($length);
}

11
app/Service/v3/Interfaces/SmsServiceInterface.php

@ -0,0 +1,11 @@
<?php
namespace App\Service\v3\Interfaces;
interface SmsServiceInterface
{
public function send($tel, $template, $templateParams);
public function makeVerifyCode($tel, $code);
public function checkVerifyCode($tel, $code);
public function removeVerifyCode($tel, $code);
}

10
app/Service/v3/Interfaces/UserBindServiceInterface.php

@ -0,0 +1,10 @@
<?php
namespace App\Service\v3\Interfaces;
interface UserBindServiceInterface
{
public function makeTel($userId, $tel);
public function checkTel($userId);
public function removeTel($userId);
}

10
app/Service/v3/Interfaces/VerifyCodeServiceInterface.php

@ -0,0 +1,10 @@
<?php
namespace App\Service\v3\Interfaces;
interface VerifyCodeServiceInterface
{
public function make($userId, $tel);
public function check($userId, $tel, $verifyCode);
public function remove($userId, $tel);
}

5
config/autoload/dependencies.php

@ -36,4 +36,9 @@ return [
\App\Service\SmsServiceInterface::class => \App\Service\SmsAliService::class,
\App\Service\OrderListServiceInterface::class => \App\Service\OrderListService::class,
\App\Service\v3\Interfaces\GoodsServiceInterface::class => \App\Service\v3\Implementations\GoodsService::class,
\App\Service\v3\Interfaces\SmsServiceInterface::class => \App\Service\v3\Implementations\SmsAliService::class,
\App\Service\v3\Interfaces\HelperServiceInterface::class => \App\Service\v3\Implementations\HelperService::class,
\App\Service\v3\Interfaces\VerifyCodeServiceInterface::class => \App\Service\v3\Implementations\VerifyCodeService::class,
\App\Service\v3\Interfaces\UserBindServiceInterface::class => \App\Service\v3\Implementations\UserBindService::class,
];

5
config/autoload/exceptions.php

@ -13,10 +13,11 @@ return [
'handler' => [
'http' => [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
App\Exception\Handler\ValidationExceptionHandler::class,
App\Exception\Handler\ErrorCodeExceptionHandler::class,
App\Exception\Handler\SsdbExceptionHandler::class,
\App\Exception\Handler\FilesystemExceptionHandler::class,
App\Exception\Handler\FilesystemExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
],
],
];

1
config/config.php

@ -47,6 +47,7 @@ return [
'regionid' => env('ALI_SMS_REGION_ID', ''),
'product' => env('ALI_SMS_PRODUCT', ''),
'host' => env('ALI_SMS_HOST', ''),
'sign_name' => env('ALI_SMS_SIGN_NAME', ''),
],
'alioss' => [
'img_host' => env('OSS_IMG_HOST', ''),

3
config/routes.php

@ -85,5 +85,6 @@ Router::addGroup('/v3/', function () {
// 需要登录的路由
Router::addGroup('/v3/', function () {
Router::post('sms/getVerifyCode', 'App\Controller\v3\SmsController@getVerifyCode');
Router::post('user/bindTel', 'App\Controller\v3\UserController@bindTel');
},['middleware' => [\App\Middleware\Auth\ApiMiddleware::class, \App\Middleware\Auth\UserMiddleware::class]]);
Loading…
Cancel
Save