1. Go to this page and download the library: Download kydev/work-wx-user library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kydev / work-wx-user example snippets
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use KY\WorkWxUser\Request\AuthorizeRequest;
use KY\WorkWxUser\UserService;
use KY\WorkWxUser\WeChat\WeChat;
class OAuthController extends Controller
{
#[Inject]
protected WeChat $wx;
#[Inject]
protected UserService $service;
public function authorize(AuthorizeRequest $request)
{
$url = (string) $request->input('redirect_uri');
$state = (string) $request->input('state');
$redirectUrl = $this->wx->authorize($url, $state);
return $this->response->redirect($redirectUrl);
}
public function login()
{
$code = $this->request->input('code');
$result = $this->service->login($code);
return $this->response->success([
'token' => $result->getToken(),
'user' => $result->getUser()->toArray(),
]);
}
}
declare(strict_types=1);
namespace App\Exception\Handler;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Kernel\Http\Response;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Exception\CircularDependencyException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Exception\HttpException;
use KY\WorkWxUser\Exception\TokenInvalidException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Throwable;
class BusinessExceptionHandler extends ExceptionHandler
{
protected Response $response;
protected LoggerInterface $logger;
public function __construct(protected ContainerInterface $container)
{
$this->response = $container->get(Response::class);
$this->logger = $container->get(StdoutLoggerInterface::class);
}
public function handle(Throwable $throwable, ResponseInterface $response)
{
switch (true) {
case $throwable instanceof HttpException:
return $this->response->handleException($throwable);
case $throwable instanceof TokenInvalidException:
return $this->response->fail(ErrorCode::TOKEN_INVALID, 'Token Invalid.');
case $throwable instanceof BusinessException:
$this->logger->warning(format_throwable($throwable));
return $this->response->fail($throwable->getCode(), $throwable->getMessage());
case $throwable instanceof CircularDependencyException:
$this->logger->error($throwable->getMessage());
return $this->response->fail(ErrorCode::SERVER_ERROR, $throwable->getMessage());
}
$this->logger->error(format_throwable($throwable));
return $this->response->fail(ErrorCode::SERVER_ERROR, 'Server Error');
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}