PHP开发钉钉机器人
2023-06-28 本文已影响0人
henryspace
步骤
- 登录钉钉开发者后台。 选择应用开发 >企业内部开发 >机器人,单击创建应用。
1.png
-
填写基本信息,参考以下信息配置机器人应用,然后单击 确定创建:
-
应用类型:选择 机器人。
-
应用名称:输入机器人名称。
本教程设置为:钉小蜜。
-
应用描述:输入机器人的描述。
本教程设置为:测试机器人。
-
应用图标:使用默认图标。
2.png
-
-
填写完成后,单击 创建,即可成功创建机器人,如下图所示。
3.png
代码
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use \Exception;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
class DingController extends Controller
{
# 获取位置:钉钉开放平台 > 应用开发 > 基础信息 > 应用信息 > 复制 AppKey
private $appKey = 'xxxxxxxxxxxxxxxxxxx';
# 获取位置:钉钉开放平台 > 应用开发 > 基础信息 > 应用信息 > 复制 AppSecret
private $appSecret = 'xxxxxxxxxxxxxxxxxxx';
# 获取位置:钉钉开放平台 > 应用开发 > 应用功能 > 机器人与消息推送 > 复制 RobotCode
private $robotCode = 'xxxxxxxxxxxxxxxxxxx';
# 钉钉授权token
public $accessToken = '';
/**
* DingController constructor.
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function __construct()
{
$this->getAccessToken();
}
/**
* 获取accessToken
* @return mixed|string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function getAccessToken()
{
$this->accessToken = Cache::get('accessToken');
if ($this->accessToken) {
return $this->accessToken;
}
$webhook = "https://api.dingtalk.com/v1.0/oauth2/accessToken";
$data = [
'appKey' => $this->appKey,
'appSecret' => $this->appSecret
];
$client = new Client();
$response = $client->post($webhook, [
'json' => $data
]);
$responseData = json_decode($response->getBody(), true);
$this->accessToken = $responseData['accessToken'] ?? '';
if (!$this->accessToken) {
throw new \Exception("获取accessToken失败");
}
Cache::put('accessToken', $this->accessToken, 7200);
return $this->accessToken;
}
/**
* 钉钉单聊
* @param $userId
* @param $content
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function sendPrivateMessage($userId, $content)
{
$client = new Client();
return $client->post(
'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend',
[
'json' => [
'robotCode' => $this->robotCode,
'userIds' => [$userId],
'msgKey' => 'sampleText',
'msgParam' => json_encode(['content' => $content]),
],
'headers' => [
'x-acs-dingtalk-access-token' => $this->accessToken,
],
]
);
}
/**
* 钉钉群聊
* @param $conversationId
* @param $content
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function sendGroupMessage($conversationId, $content)
{
$client = new Client();
return $client->post(
'https://api.dingtalk.com/v1.0/robot/groupMessages/send',
[
'json' => [
'robotCode' => $this->robotCode,
'openConversationId' => $conversationId,
'msgKey' => 'sampleText',
'msgParam' => json_encode(['content' => $content]),
],
'headers' => [
'x-acs-dingtalk-access-token' => $this->accessToken,
],
]
);
}
/**
* 钉钉回调接口
* @param Request $request
* @return \Illuminate\Http\JsonResponse
* @throws Exception
*/
public function parse(Request $request)
{
$params = $request->all();
Log::channel('ding')->error('Params: '. json_encode($params, JSON_UNESCAPED_UNICODE));
$content = $params['text']['content']??"钉钉,让进步发生";
try {
// 根据 conversationType 判断是群聊还是单聊
if ($params['conversationType'] === '1') {
// 单聊
$res = $this->sendPrivateMessage($params['senderStaffId'], $content);
} else {
// 群聊
$res = $this->sendGroupMessage($params['conversationId'], $content);
}
Log::channel('ding')->error('Response: '. json_encode($res, JSON_UNESCAPED_UNICODE));
}
catch (GuzzleException $e) {
Log::channel('ding')->debug("Msg:{$e->getMessage()}");
throw new \Exception($e->getMessage());
}
catch (Exception $err) {
Log::channel('ding')->debug("Msg:{$err->getMessage()}");
}
return $this->success('success', ['ok' => 1]);
}
}