Files
cycle_api/app/Service/ImService.php
2023-12-21 22:01:33 +08:00

81 lines
2.0 KiB
PHP

<?php
namespace App\Service;
use App\Const\Im;
use App\Exceptions\AppException;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Http;
class ImService{
const user_register_data = [
'secret' => '',
'users' => [
'userID' => '',
'nickname' => '',
'faceURL' => '',
],
];
/**
* @throws AppException
*/
function userUserRegister($userId, $nickname = '', $faceUrl=''): bool
{
$path = '/user/user_register';
$aData['users'] = [
'userID' => $this->genImUid($userId),
'nickname' => $nickname,
'faceURL' => $faceUrl,
];
$jRes = $this->sendReq($path,$aData);
if(isset($jRes['errCode']) && $jRes['errCode'] === 0) return true;
return false;
}
/**
* @throws AppException
*/
function authUserToken($userId,int $platform): false|array
{
$path = '/auth/user_token';
$aData['users'] = [
'platformID' => $platform,
'userID' => $this->genImUid($userId),
];
$jRes = $this->sendReq($path,$aData);
if(isset($jRes['errCode']) && $jRes['errCode'] === 0){
return [
'token' => $jRes['token'],
'expireTimeSeconds' => $jRes['expireTimeSeconds'],
];
}
return false;
}
function getSecret()
{
return Env::get('IM_SECRET');
}
function getUrl(): string
{
return rtrim(Env::get('IM_URL'),'/');
}
/**
* @throws AppException
*/
function sendReq(string $path,array $aData = [])
{
if (!isset($aData['secret'])) $aData['secret'] = $this->getSecret();
$resp = Http::post($this->getUrl().$path,$aData);
if(!$resp->ok()) throw new AppException('im request error');
return $resp->json();
}
function genImUid($userId): string
{
return Im::USER_PREFIX.$userId;
}
}