forked from typecho-fans/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOfficialAccountService.php
82 lines (73 loc) · 2.97 KB
/
OfficialAccountService.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
78
79
80
81
82
<?php
/**
* @author gaobinzhan <gaobinzhan@gmail.com>
* @modify 小码农 <chengshongguo@qq.com> 增加实例化方法
*/
require_once 'Service.php';
class OfficialAccountService extends Service
{
public static function create(){
static $instance ;
if (!$instance){
$instance = new OfficialAccountService();
}
return $instance;
}
public function __handler($active, $comment, $plugin)
{
try {
$token = $plugin->officialAccountToken;
$appId = $plugin->officialAccountAppId;
$appSecret = $plugin->officialAccountAppSecret;
$openid = $plugin->officialAccountOpenid;
$templateId = $plugin->officialAccountTemplateId;
if (empty($token) || empty($appId) || empty($appSecret) || empty($openid) || empty($templateId)) throw new \Exception('缺少微信公众号配置参数');
$accessTokenResult = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}");
$accessTokenResult = json_decode($accessTokenResult, true);
if ($accessTokenResult == false || isset($r['errcode']) || isset($r['errmsg'])) {
self::logger(__CLASS__, '', '', $accessTokenResult);
return false;
}
$accessToken = $accessTokenResult['access_token'];
$title = $active->title;
$author = $comment['author'];
$link = $active->permalink;
$context = $comment['text'];
$params = json_encode([
'touser' => $openid,
'template_id' => $templateId,
'url' => $link . '#comment-' . $comment['coid'],
'appid' => $appId,
'data' => [
'title' => [
'value' => $title,
'color' => "#173177"
],
'user' => [
'value' => $author,
'color' => "#F00"
],
'ip' => [
'value' => $comment['ip'],
'color' => "#173177"
],
'content' => [
'value' => $context,
'color' => "#3D3D3D"
],
]
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => urldecode($params)
]
]);
$result = file_get_contents('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken, false, $context);
self::logger(__CLASS__, $openid, $params, $result);
} catch (\Exception $exception) {
self::logger(__CLASS__, '', '', '', $exception->getMessage());
}
}
}