1. Go to this page and download the library: Download hyperf-apex/wecom 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/ */
use Hyperf\Apex\WeCom\Manager\WeComManager;
final class UserSyncService
{
public function __construct(private readonly WeComManager $wecom)
{
}
public function departmentUsers(int $departmentId, ?string $alias = null): array
{
// 成功返回响应体;失败抛 BusinessException(503),errcode 在 $e->getData()['errcode'] 里
return $this->wecom->api($alias)->get('cgi-bin/user/list', [
'department_id' => $departmentId,
]);
}
public function sendText(string $userId, string $content, ?string $alias = null): array
{
return $this->wecom->api($alias)->post('cgi-bin/message/send', [
'touser' => $userId,
'msgtype' => 'text',
'agentid' => (int) $this->wecom->account($alias)->agentId,
'text' => ['content' => $content],
]);
}
}
use Hyperf\Apex\WeCom\DTO\WeComAuthorizeRequestDTO;
use Hyperf\Apex\WeCom\DTO\WeComLoginRequestDTO;
use Hyperf\Apex\WeCom\Login\WeComLoginService;
final class AuthService
{
public function __construct(private readonly WeComLoginService $login)
{
}
/** 第一步:把三个入口与 state 交给前端 */
public function authorizeUrl(): \Hyperf\Apex\WeCom\DTO\WeComAuthorizeUrlDTO
{
return $this->login->buildAuthorizeUrl(new WeComAuthorizeRequestDTO()); // 可传 alias / redirectUri
}
/** 第二步:回调带回的 code + state 换成员 userid */
public function resolveUserId(string $code, string $state): string
{
return $this->login->resolveMember(new WeComLoginRequestDTO(code: $code, state: $state))->userId;
}
}