php对接飞书机器人,根据手机号给指定人推送消息
工具类:
<?php
namespace common\components;
class Feishu
{
public static function getToken($config) {
$url = $config['serverUrl'] . 'auth/v3/app_access_token/internal';
$data = [
"app_id" => $config['appId'],
"app_secret" => $config['appSecret']
];
$res = self::commonCurl($url,$data);
if($res['code'] != 0) {
return false;
}
return $res['app_access_token'];
}
public static function sendMessage($mobiles, $message) {
$config = self::_getConfig();
$token = self::getToken($config);
if(!$token) return null;
$userList = self::_getUserListByMobile($mobiles, $config, $token);
if(!$userList) return null;
$headers = [
'Authorization: ' . 'Bearer ' . $token,
];
$data = [
"msg_type" => "text",
"content" => json_encode([
'text' => $message
])
];
$res = null;
foreach ($userList as $userInfo) {
$data['receive_id'] = $userInfo[0]['open_id'];
$res = self::commonCurl($config['serverUrl'] . 'im/v1/messages?receive_id_type=open_id', $data, $headers);
}
if(isset($res['code']) && ($res['code'] == 0)) return true;
return false;
}
//获取用户信息
private static function _getUserListByMobile($mobiles, $config, $token) {
$params = implode('&mobiles=', $mobiles);
$headers = [
'Authorization: ' . 'Bearer ' . $token,
];
$res = self::commonGetCurl($config['serverUrl'] . 'user/v1/batch_get_id?mobiles=' . $params, $headers);
if($res['code'] != 0) {
return false;
}
return $res['data']['mobile_users'];
}
private static function _getConfig() {
return [
'serverUrl' => 'https://open.feishu.cn/open-apis/',
'appId' => '111', //替换成自己的 appId
'appSecret' => '111', //替换成自己的 appSecret
];
}
public static function commonCurl($serverUrl, $args, $headers = [], $isJson = true) {
$data_string = $isJson ? json_encode($args) : $args;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $serverUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($headers, array(
'Content-Type: application/json;charset=UTF-8',
'Content-Length: ' . strlen($data_string)))
);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$data = json_decode($result, true);
return $data ?: $result;
}
}
调用工具类发送消息:
Feishu::sendMessage(['18618161234'], '测试消息');
浙公网安备 33010602011771号