微信公众平台|模板消息群发功能

小编之前发布过一微信公众平台开发|发送模板消息”的文章,这篇只是发送给某个用户的,那么如何群发给关注该公众号的所有用户呢?下面我们来探讨一下。

最近关注了一个公众号,偶尔会给我发送一些信息,看了这公众号为服务号,知道服务号一个月只能发布4篇文章,那怎么现在可以天天给我发送带链接的消息的?小编就好奇去研究了一下,知道这就是模板消息,那怎么是群发的呢?看了一下微信公众平台的开发文档,有一篇“获取用户列表”的文章,那就清楚了,通过获取关注该公众号的用户,然后分别发送模板消息。下面见代码:

WeChatSendMsg.class.php

// +----------------------------------------------------------------------
// | 微信公众平台 发送模板消息
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.lrfun.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: lrfun 
// +----------------------------------------------------------------------

Class WeChatSendMsg{
	protected $appid;
    protected $secrect;
	
	function __construct(){
		$this->appid = "xxx";
		$this->secrect = "xxx";
	}
	
	/***
	 * POST或GET请求
	 * @url 请求url
	 * @data POST数据
	 * @return
	 **/
	private function httpRequest($url, $data = ""){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if(!empty($data)){	//判断是否为POST请求
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
	/***
	 * 获取access_token
	 * @return
	 **/
	public function getAccessToken(){
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secrect;
		$res = json_decode($this->httpRequest($url),true);
		return $res['access_token'];
	}
	
	//获取用户列表(openid)
	public function getUserOpenidList($token){
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$token;
		$result = $this->httpRequest($url);
		return json_decode($result, true);
	}
	
	/***
	 * 发送模板短信
	 * @data 请求数据
	 * @return
	 **/
	public function sendTemplateMessage($token, $data = ""){
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
		$result = $this->httpRequest($url, $data);
		return json_decode($result, true);
	}
}

sendTemplateMessage.php

require_once('WeChatSendMsg.class.php');
$sendMsg = new WeChatSendMsg();
$token = $sendMsg->getAccessToken(); //获取token
$users = $sendMsg->getUserOpenidList($token); //获取用户列表
$data = array(
	"template_id"=>"iq91YDi7QaACAyZlm7RaboyNEHDdU2YizPju7rshUq8", //模板ID
	"url"=>"http://www.lrfun.com", //链接地址
	"data"=>array( //模板内容
		"name"=> array("value"=>"lrfun博客", "color"=>"#173177"),
		"remark"=>array("value"=>"^_^欢迎大家关注转载!", "color"=>"#173177")
	)
);
foreach($users['data']['openid'] as $v){
	$data['touser'] = $v;
	$result = $sendMsg->sendTemplateMessage($token, json_encode($data));
	print_r($result);
}


欢迎转载,原文地址:http://www.lrfun.com/html/technology/PHP/2017/0914/120.html

上一篇:public、protected、private权限控制的区别
下一篇:微信开发|现金红包接口