Issues (6)

src/HttpClient.php (1 issue)

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: wangju
5
 * Date: 2019-05-17
6
 * Time: 20:38
7
 */
8
9
namespace DingNotice;
10
11
12
use GuzzleHttp\Client;
13
14
class HttpClient implements SendClient
15
{
16
    protected $client;
17
    protected $config;
18
    /**
19
     * @var string
20
     */
21
    protected $hookUrl = "https://oapi.dingtalk.com/robot/send";
22
23
    /**
24
     * @var string
25
     */
26
    protected $accessToken = "";
27
28
    public function __construct($config)
29
    {
30
        $this->config = $config;
31
        $this->setAccessToken();
32
        $this->client = $this->createClient();
33
    }
34
35
    /**
36
     *
37
     */
38
    public function setAccessToken(){
39
        $this->accessToken = $this->config['token'];
40
    }
41
42
    /**
43
     * create a guzzle client
44
     * @return Client
45
     * @author wangju 2019-05-17 20:25
46
     */
47
    protected function createClient()
48
    {
49
        $client = new Client([
50
            'timeout' => $this->config['timeout'] ?? 2.0,
51
        ]);
52
        return $client;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getRobotUrl()
59
    {
60
        $query['access_token'] = $this->accessToken;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query = array(); before regardless.
Loading history...
61
        if (isset($this->config['secret']) && $secret = $this->config['secret']) {
62
            $timestamp = time() . sprintf('%03d', rand(1, 999));
63
            $sign      = hash_hmac('sha256', $timestamp . "\n" . $secret, $secret, true);
64
            $query['timestamp'] = $timestamp;
65
            $query['sign'] = base64_encode($sign);
66
        }
67
        return $this->hookUrl . "?" . http_build_query($query);
68
    }
69
70
    /**
71
     * send message
72
     * @param $url
73
     * @param $params
74
     * @return array
75
     * @author wangju 2019-05-17 20:48
76
     */
77
    public function send($params): array
78
    {
79
        $request = $this->client->post($this->getRobotUrl(), [
80
            'body' => json_encode($params),
81
            'headers' => [
82
                'Content-Type' => 'application/json',
83
            ],
84
            'verify' => $this->config['ssl_verify'] ?? true,
85
        ]);
86
87
        $result = $request->getBody()->getContents();
88
        return json_decode($result, true) ?? [];
89
    }
90
}
91