1.根目录下的ThinkPHP\Library\Com文件夹中的WechatAuth.class.php文件中没有预览群发接口的方法,首先打开这个文件,添加这个方法:
~~~
/*
*预览群发接口
*/
public function meassageMass($msgtype,$openid,$content){
$data=array(
'touser'=>$openid,
$msgtype=>array("content"=>$content),
'msgtype'=>$msgtype
);
//echo json_encode($data);
//exit;
return $this->api("message/mass/preview",$data);
}
~~~
![](https://box.kancloud.cn/913b708a55309c57fce41a2f8dd693a1_909x589.png)
2.根目录下的/Application/Home/Controller文件夹中的MassController.class.php文件,书写代码为:
~~~
<?php
namespace Home\Controller;
use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
class MassController extends Controller
{
private $appid="wx165112bf167af76c";
private $appSecret="c65b22bfcf03fdd98504eac299701b03";
private $WechatAuth="";//初始化WechatAuth类
private $access_token="";//缓存token
public function __construct(){
parent::__construct();//可能内部已经有这个构造方法了,因此加上这个
if(!session('token')){
$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret);//初始化WechatAuth类
$WechatAuth=$this->WechatAuth;
$token=$WechatAuth->getAccessToken();
session(array('expire'=>$token['expires_in']));//设置过期时间
session('token',$token['access_token']);//缓存token
$this->access_token=$token;
}else{
$token=session('token');
$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret,$token);//初始化WechatAuth类
$this->access_token=$token;//缓存token
}
}
//预览群发消息
public function send(){
header('Content-type:text/html;charset=utf-8;');
$WechatAuth=$this->WechatAuth;
$msgtype="text";
$openid="orVDLwCI0NcQk0skZPNrfZkaj-aE";//暂时直接从数据库中复制的openid
$content="你好,我在预览群发消息";
$arr=$WechatAuth->meassageMass($msgtype,$openid,$content);
var_dump($arr);
}
}
~~~
3.注意点
![](https://box.kancloud.cn/aec826ccfc5b8afa5176b213167bb133_677x285.png)
4.在微信web开发者工具上测试结果为
![](https://box.kancloud.cn/aed194890ecfff4f50ca1fc066119cf0_996x382.png)
5.在微信客户端的公众号里查看是否群发了消息
![](https://box.kancloud.cn/66881fc381ce3605fed7803d1bc59f57_360x73.png)
6.本节源码下载(下载密码:mjol)
[源码下载](https://pan.baidu.com/s/1KZD1CJUE73jTq4mCFMsY2A)