在Thinkphp/ThinkPHP/Library/Vendor/WeixinMsg 创建WeixinMsg.php 文件
<?php
namespacewxmsg;
class WeiXin {
public function __construct() {
$config = C("THINK_SDK_WXOAUTH");
$this->appid = 'appid'; //appid
$this->appsecret = 'appsecret'; //秘钥
$this->access_token = '';
//判断access_token是否存在,不存在重新获取
if (session('access_token_bd')) {
$this->access_token = session('access_token_bd');
} else {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
$res = json_decode($this->http_request($url), true);
$this->access_token = $res['access_token'];
session(array('name' => 'access_token_bd', 'value' => $this->access_token, 'expire' => 7200)); //保存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->http_request($url, $data);
return $res;
return json_decode($res, true);
}
public function template($openid, $template_id, $data, $url, $topcolor) {
$url = "your url"; //example htt://www.baidu.com
$openid = $openid; //根据用户id获取数据库保存的openid
switch ($template_id) {
case 1:
$tpl = "模板id"; //可以有多个值
break;
default:
$tpl = '';
break;
}
if (!$tpl) {
return '';
}
$template = array('touser' => $openid, 'template_id' => $tpl, 'url' => $url, 'topcolor' => $topcolor, 'data' => $data);
return $template;
}
protected function http_request($url, $data = null) {
$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)) {
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;
}
}
注意:将自己的服务器ip将入微信公众平台的白名单中。
在对应的方法中 加入:
$key1 = '1';
$key2 = '2';
$key3 = '3';
$key4 = '4';
$key5 = '5';
$key6 = '6';//获取用户id
$abc= array(
'first' => array('value'=>urlencode("自定义"),'color'=>''),
'keywords1' => array('value'=>urlencode("$key1"),'color'=>''),
'keywords2' => array('value'=>"$key2",'color'=>''),
'keywords3' => array('value'=>"$key3",'color'=>''),
'keywords4' => array('value'=>urlencode("$key4"),'color'=>''),
'keywords5' => array('value'=>urlencode("$key5"),'color'=>''),
'keywords6' => array('value'=>urlencode("$key6"),'color'=>''),
'remark' => array('value'=>urlencode("自定义"),'color'=>''),
);
Vendor('WeixinMsg.WeixinMsg');
$wxtlp = new \wxmsg\WeiXin();
$template = $wxtlp->template($openid,1,$abc);
$res=$wxtlp->send_template_message(urldecode(json_encode($template)));
$data=json_decode($res,true);
