From 692faa93e9010a4f2506621f3f970db570efc4c6 Mon Sep 17 00:00:00 2001 From: Easy Date: Wed, 23 Jun 2021 11:51:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=B8=A6access=20token?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E7=9A=84=E5=AE=9E=E7=8E=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 ++ README.md | 2 ++ index.php | 45 +++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..318dc65 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +demo.php +show.php \ No newline at end of file diff --git a/README.md b/README.md index 783005c..7acd657 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ PS:如果出现`接口请求正常,企业微信接受消息正常,个人 #### 第五步,通过以下函数发送消息: +PS:为使用方便,以下函数没有对 `access_token` 进行缓存。对于个人低频调用已经够用。带缓存的实现可查看 `index.php` 中的示例代码(依赖Redis实现)。 + PHP版: ```php diff --git a/index.php b/index.php index 67fb557..8c73c4c 100644 --- a/index.php +++ b/index.php @@ -1,11 +1,22 @@ connect(REDIS_HOST, REDIS_PORT); + } + + return $GLOBALS['REDIS_INSTANCE']; +} + function send_to_wecom($text, $wecom_cid, $wecom_secret, $wecom_aid, $wecom_touid = '@all') { - $info = @json_decode(file_get_contents("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".urlencode($wecom_cid)."&corpsecret=".urlencode($wecom_secret)), true); + $access_token = false; + // 如果启用redis作为缓存 + if (REDIS_ON) { + $access_token = redis()->get(REDIS_KEY); + } + + if (!$access_token) { + $info = @json_decode(file_get_contents("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".urlencode($wecom_cid)."&corpsecret=".urlencode($wecom_secret)), true); - if ($info && isset($info['access_token']) && strlen($info['access_token']) > 0) { - $access_token = $info['access_token']; + if ($info && isset($info['access_token']) && strlen($info['access_token']) > 0) { + $access_token = $info['access_token']; + } + } + + if ($access_token) { $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.urlencode($access_token); $data = new \stdClass(); $data->touser = $wecom_touid; @@ -44,7 +76,12 @@ function send_to_wecom($text, $wecom_cid, $wecom_secret, $wecom_aid, $wecom_toui curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); + if ($response !== false && REDIS_ON) { + redis()->set(REDIS_KEY, $access_token, REDIS_EXPIRED); + } return $response; } + + return false; }