微信模板消息发送

Posted yite

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信模板消息发送相关的知识,希望对你有一定的参考价值。



<meta charset="utf-8">

<?php


//使用此代码前需做以下准备工作:
//1、建立一个名为access_token.php的空php文件
//2、在微信公众平台使用管理员权限设置好ip白名单,并在功能设置中绑定业务域名(此文件所在的网络地址),记得根据提示下载MP_verify_TcfRJJNVAMluRK8C.txt文件放在同级目录下
//3、在数据库中建立一个名为send的表,表中包含id、openid、nickname、groupid字段






//公众号模板消息群发


class WxMessage


/**
* @return mixed
*/


//封装数据库连接方法
public function dataBase()


$dbms=‘mysql‘; //数据库类型
$host=‘‘; //数据库主机名
$dbName=‘‘; //使用的数据库
$user=‘‘; //数据库连接用户名
$pass=‘‘; //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";

try
$dbh = new PDO($dsn, $user, $pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES‘utf8‘;")); //初始化一个PDO对象
//PDO是连接数据库的方法,其内依次放置 ,用户名,密码,展现格式
catch (PDOException $e)
die ("Error!: " . $e->getMessage() . "<br/>");
//处理抛出的异常


return $dbh;





var $appid = ‘‘; //开发者appid
var $appsecret = ‘‘; //开发者密钥

//access_token需动态获取,存于access_token.php,access_token会过期,过期后需重新获取(清空线上access_token.php里的内容)


//构造函数,获取token;
public function __construct($appid = null,$appsecret = null)

if($appid && $appsecret)
$this->appid = $appid;
$this->appsecret=$appsecret;


$this->lasttime=1406469747;
$this->access_token=" ";//动态获取

$file= file_get_contents(‘access_token.php‘);
$file = json_decode($file,true);

if (!$file||$file[‘expires_time‘]<time())

$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret."";
$res = $this->https_request($url);

$result = json_decode($res,true);

$result[‘expires_time‘] = time()+7000;

file_put_contents(‘access_token.php‘,json_encode($result));


else

$result = $file;
// exit();



$this->access_token = $result[‘access_token‘];

// print_r($this->access_token);






//发送模板消息
public function send_template_message($data)

$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$res = $this->https_request($url,$data);

// print_r($res);

$result = json_decode($res,true);

echo "<script>
alert(‘发送成功!‘);location.href=‘http://rs.xinhuang.net.cn/send.php‘;
</script>";




//获取粉丝
public function getMemberList($openid=‘‘)

ini_set(‘max_execution_time‘,‘0‘);


if (!$openid)
$openid=(new WxMessage())->dataBase()->query(‘select openid from send order BY id DESC ‘)->fetch()[‘openid‘];

// exit();
// print_r($openid);




$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$openid;
$res = $this->https_request($url);
$result = json_decode($res,true);
// print_r($result);
// exit();

if ($result[‘count‘]==0)
return true;


foreach ($result[‘data‘][‘openid‘] as $key=>$value)


// print_r($value);

// if ($key===10)
// break;
//

$userInfo = ‘https://api.weixin.qq.com/cgi-bin/user/info?access_token=‘.$this->access_token.‘&openid=‘.$value.‘&lang=zh_CN‘;


$res = $this->https_request($userInfo);
$result1 = json_decode($res,true);
// print_r($result1);

$openid = $result1[‘openid‘];
$nickname = $result1[‘nickname‘];
$groupid = $result1[‘groupid‘];

$sql = "insert into send (openid,nickname,groupid) values(‘$openid‘,‘$nickname‘,‘$groupid‘)";

$rows = (new WxMessage())->dataBase()->query($sql);

sleep(0.3);

// print_r($sql);

// exit();
//
// if ($key==5)
// break;
//




if ($result[‘total‘]==$result[‘count‘])
return true;


if ($openid!=$result[‘next_openid‘])

$this->getMemberList($result[‘next_openid‘]);




return true;

// return $result;






//https请求(支持GET和POST)
protected function https_request($url,$data=null)

$curl = curl_init(); // 初始化一个cURL会话
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,$url);
if(!empty($data))
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);


curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($curl); // 抓取 URL 并把它传递给浏览器
curl_close($curl);
return $output;








//执行操作
if (isset($_POST["submit"]))

//添加粉丝进数据库
if (isset($_POST["sen"]))

(new WxMessage())->getMemberList();



//确认后发送模板消息
if (isset($_POST["sending"]))

// $remark = $_POST["modelarea"];

$groupselect = $_POST["groupselect"];

if($groupselect!=‘选取分组‘)

// $result = (new WxMessage())->dataBase()->query($sql_r);//不知何用

// $openid=(new WxMessage())->dataBase()->query("select openid from send where groupid =".$groupselect);

$data=orderSuccess(‘‘);//括号内为用户openid,一般情况下填$openid,在测试时为了不误发信息骚扰用户应使用开发者的openid,测试情况下发送消息成功后,只有开发者可以收到信息

(new WxMessage())->send_template_message(json_encode($data));

// foreach ($result as $value)
//
// $data=orderSuccess($value[‘open_id‘]);
//
// (new WxMessage())->send_template_message($data);
//
//
//





// exit();







//下单成功通知模板

function orderSuccess($openid=null, $orderSn=null, $remark=null)

$activityName=$_POST[‘activityName‘];
$activityHost=$_POST[‘activityHost‘];
$activityTime=$_POST[‘activityTime‘];
$remark=$_POST[‘modelarea‘];

$template = array(
"touser" => "$openid",
"template_id" => "tcH2Ij9T1hKS8Fu38BeYVhj5Ghf6NOv8zrkSztPOSvI",
‘url‘ => ‘‘,//此处是用户点击详情后的跳转页面的地址
‘topcolor‘ => ‘#ccc‘,
‘data‘ => array(‘first‘ => array(‘value‘ =>‘亲,本店最近有新活动哦,敬请关注‘,
‘color‘ =>"#743A3A",
),
‘keyword1‘ => array(‘value‘ => $activityName, //活动名称
‘color‘ =>‘#FF0000‘
),
‘keyword2‘ => array(‘value‘ => $activityHost, //活动主办方
‘color‘ =>‘#FF0000‘
),
‘keyword3‘ => array(‘value‘ => "$activityTime", //活动时间
‘color‘ =>‘#FF0000‘
),
‘remark‘ => array(‘value‘ => "$remark", //活动描述
‘color‘ =>‘#FF0000‘
),
)
);

// echo $template;

return $template;
// return $remark;




//$message = new \WxMessage();
//
//
//$message->

//
//$data = orderSuccess();
//
//print_r((new WxMessage())->send_template_message($data));


//引用模板消息发送到微信公众号中

foreach ([] as $value)

$template =orderSuccess($openid,$reoderSn,$goodsNames,$sum,$money);
//引入模板消息类
//Loader::import(‘org\WxMessage‘, EXTEND_PATH);
//实例化消息类
$message = new \WxMessage();
//发送消息
$message->send_template_message(urldecode(json_encode($template)));







?>


<div style="text-align: center;padding: 20px;font-size: 24px;">微信模板消息发送</div>


<div style="text-align: center;margin-bottom: 20px;">

<div style="display: inline-block;width: auto;color: white;">
<form action="" name="send" method="post" >
<input name="sen" type="hidden" value="1" />
<input style="padding: 10px 20px;" type="submit" name="submit" value="同步粉丝" onclick="alert(‘加载需要一点时间,请稍等‘);return;"/>
</form>
</div>

<form action="" name="group" method="post">

<div style="display: inline-block;width: auto;">
活动名称:
<input name="activityName" type="text" value="" placeholder="请输入活动名称" style="width:250px;height: 50px;margin-bottom: -20px;text-align: center;"/>
</div>

<div style="display: inline-block;width: auto;">
主&nbsp办&nbsp方:
<input name="activityHost" type="text" value="" placeholder="请输入活动主办方" style="width:250px;height: 50px;margin-bottom: -20px;text-align: center;"/>
</div>

<br><br>

<div style="display: inline-block;width: auto;">
活动时间:
<input name="activityTime" type="text" value="" placeholder="请输入活动时间" style="width:250px;height: 50px;margin-bottom: -20px;text-align: center;"/>
</div>

<div style="display: inline-block;width: auto;">
通知内容:
<textarea name="modelarea" placeholder="请输入通知内容" style="width:250px;height: 50px;margin-bottom: -20px;"></textarea>
</div>

<br><br>

<div style="display: inline-block;width: auto;color: white;margin: 0 40px;">
<!-- <form action="" name="group" method="post">-->
<input name="groupsen" type="hidden" value="1" />
<!-- <input style="padding: 10px 20px;" type="submit" name="submit" value="选取分组"/>-->
<select style="padding: 11px 20px;" name="groupselect" value="选取分组">

<option>选取分组</option>

<?php

$sql_g = "SELECT * FROM send group by groupid ORDER BY id DESC";

foreach ((new WxMessage())->dataBase()->query($sql_g) as $key=> $groups)

?>

<option value="<?php echo $groups[‘id‘];?>" name="groupid"><?php echo $groups[‘groupid‘]; ?></option>

<?php ?>

</select>

<!-- </form>-->
</div>

<div style="display: inline-block;width: auto;margin: 0 30px;">
<input name="sending" type="hidden" value=" " />
<input id="submit" style="padding: 10px 20px;" type="submit" name="submit" value="发送消息"/>
</div>

</form>

</div>



<table class="table table-bordered table-striped table-hover" style="width: 90%;border: 1px solid black;margin: 0 auto;">
<thead style="border: 1px solid black;">
<tr style="border: 1px solid black;">
<th style="border: 1px solid black;">序号</th>
<th style="border: 1px solid black;">用户openid</th>
<th style="border: 1px solid black;">用户昵称</th>
<th style="border: 1px solid black;">用户分组</th>
<!-- <th style="border: 1px solid black;">选择模板</th>-->
<!-- <th style="border: 1px solid black;">操作</th>-->
</tr>
</thead>
<tbody>

<?php

// $ProType = empty($_REQUEST["ProType"]) ? ‘‘ : $_REQUEST["ProType"];
//
// if ($ProType==1)

$sql_r = "SELECT * FROM send ORDER BY id DESC";

foreach ((new WxMessage())->dataBase()->query($sql_r) as $key=> $values)
?>
<tr class="cen" >
<td style="border: 1px solid black;color: #b2b2b2;text-align: center;margin: 0;"><?php echo $values[‘id‘]; ?></td>
<td style="border: 1px solid black;color: #b2b2b2;text-align: center;margin: 0;"><?php echo $values[‘openid‘]; ?></td>
<td style="border: 1px solid black;color: #b2b2b2;text-align: center;margin: 0;"><?php echo $values[‘nickname‘]; ?></td>
<td style="border: 1px solid black;color: #b2b2b2;text-align: center;margin: 0;"><?php echo $values[‘groupid‘]; ?></td>
<!-- <td style="border: 1px solid black;color: #b2b2b2;text-align: center;margin: 0;">--><?php //echo $values[‘groupid‘]; ?><!--</td>-->
<!-- <td style="width:5%;border: 1px solid black;text-align: center;">-->
<!-- <a href=" " title="发送" class="mr-5" style="text-decoration: none;color: #0e9aff;">发送</a>-->
<!-- </td>-->
</tr>
<?php
//

?>

</tbody>
</table>




























以上是关于微信模板消息发送的主要内容,如果未能解决你的问题,请参考以下文章

消息推送之微信模板消息

主动发送微信公众平台“模板消息”需要啥条件?

微信发送模板消息

微信公众平台 发送模板消息

微信开发-- 发送模板消息

php之微信公众号发送模板消息