Files
xk-api-yii/common/services/ImService.php
2024-09-19 11:32:39 +08:00

88 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace common\services;
use GuzzleHttp\Client;
use yii\base\Exception;
class ImService{
private static $instance = null;
public $config;
private function __construct()
{
$config = \Yii::$app->params['im'];
if(!$config['url'] || !$config['token']){
throw new Exception('缺少im相关配置');
}
$this->config = $config;
}
private function __clone()
{
}
public static function getInstance()
{
if(empty(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
/**
* Get a fresh instance of the Guzzle HTTP client.
*
* @return \GuzzleHttp\Client
*/
protected function getHttpClient()
{
return new Client(['http_errors' => false]);
}
//消息发送 接收人接收角色会话id,消息内容
public function sendToUid($to_id,$to_role,$message)
{
//会话id组合到message
$data = [
'FromId' => 0,
'ToId' => $to_id,
'ToType' => $to_role,
'Msg' => $message,
'Broadcast' => $to_id ? false : true,
];
$params = [
'headers' => ['token' => $this->config['token']],
'json' => $data,
];
$response = $this->getHttpClient()->post($this->config['url'].'/sendMsg', $params);
$result = json_decode($response->getBody()->getContents(), true);
\Yii::error($data);
\Yii::error($result);
//根据是否发送成功进行模板消息的发送
}
public function updateImStatus($userId,$imStatus,$userType)
{
//
$data = [
'userId' => intval($userId),
'imStatus' => intval($imStatus),
'userType' => $userType,
];
$params = [
'headers' => ['token' => $this->config['token']],
'json' => $data,
];
$response = $this->getHttpClient()->post($this->config['url'].'/updateImStatus', $params);
$result = json_decode($response->getBody()->getContents(), true);
}
}