利用微信公众号的模板消息发送公众号通知
/**
* 发送模板消息
*/
public function sendNotice()
{
$openid = 'openid';
$template_id = 'template_id';
$data = [
"character_string1" => [
"value" => time()
],
"thing2" => [
"value" => '商品',
],
"amount3" => [
"value" => "42元"
],
"time5" => [
"value" => date('Y-m-d H:i:s')
],
"time6" => [
"value" => date('Y-m-d H:i:s')
]
];
sendTemplateNotice(0, $openid, $template_id, $data);
}
if (!function_exists('sendTemplateNotice')) {
/**
* 发送微信模板消息
* @param int $type 0:用户 1:商家
* @param string $openid
* @param string $template_id 模板Id
* @param array $data 模板消息数据
* @return bool
*/
function sendTemplateNotice($type = 0, $openid = '', $template_id = '', $data = [])
{
$client = new \GuzzleHttp\Client();
$config = get_addon_config('wanlshop');
$user_appid = $config['sdk_qq']['gz_appid'];
$user_secret = $config['sdk_qq']['gz_secret'];
$shop_appid = $config['sdk_qq']['gz_appids'];
$shop_secret = $config['sdk_qq']['gz_secrets'];
$user_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $user_appid .
'&secret=' . $user_secret;
$shop_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $shop_appid .
'&secret=' . $shop_secret;
if (!empty($type)) {
$accessTokenResponseData = $client->request('GET', $shop_access_token_url);
} else {
$accessTokenResponseData = $client->request('GET', $user_access_token_url);
}
$accessTokenResponse = $accessTokenResponseData->getBody();
$accessTokenResponse = json_decode($accessTokenResponse);
$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessTokenResponse->access_token;
$query = [
'json' => [
"touser" => $openid,
"template_id" => $template_id,
// "miniprogram" => [
// "appid" => "appid",
// "pagepath" => "pagepath"
// ],
"client_msg_id" => time(),
"data" => $data
],
'headers' => [
'Content-Type' => 'application/json',
]
];
write_log($query);
$responseData = $client->request('POST', $url, $query);
$response = $responseData->getBody();
write_log($response->getContents());
return true;
}
}