-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathChatBot.php
77 lines (71 loc) · 2.1 KB
/
ChatBot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace DingTalkRobot;
use DingTalkRobot\Messages\BaseMessage;
/**
* Class ChatBot
* @package DingTalkRobot
*/
class ChatBot
{
/**
* @param BaseMessage $message
* @param GroupChat $group
* @return bool|false|string
*/
public function send($message, $group)
{
$data = $message->packageData();
$url = str_replace('ACCESS_TOKEN', $group->getToken(), Constants::URL);
return $this->postJson($url, $data);
}
/**
* @param string $url
* @param array $params
* @return bool|false|string
*/
private function postJson($url, $params)
{
try {
$ret = $this->curlJson($url, $params);
} catch (\Exception $exception) {
$ret = json_encode(array('errcode' => $exception->getCode(), 'errmsg' => $exception->getMessage()));
}
return $ret;
}
/**
* @param $url
* @param array $postFields
* @return bool|string
* @throws \Exception
*/
private function curlJson($url, $postFields = array())
{
$postFields = json_encode($postFields);
$header = array(
"Content-Type: application/json; charset=utf-8",
"Content-Length:" . strlen($postFields)
);
$ch = curl_init();
if ($ch === false) {
return false;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$postFields && curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new \Exception(curl_error($ch), 0);
} else {
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode) {
throw new \Exception($response, $httpStatusCode);
}
}
curl_close($ch);
return $response;
}
}