wxtemple.class.php,tp框架下的微信模板消息

一、开发环境要求:

1、有一个已经认证的微信服务号;

2、有一定的微信开发基础;

3、爱学习、爱探索、爱步浪博客;

二、代码展示:

1、模板消息所需类库:<?php

class sendMessage {

//获取accesstoken

function getAccesstoken(){

$ch=curl_init();

$appid="";//公众号的appid;

$appsecret="";公众号的appsecret;

$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";

//GET方式抓取URL

curl_setopt($ch,CURLOPT_URL,$url);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//执行

$outopt=curl_exec($ch);

$outoptarr=json_decode($outopt,TRUE);

return $outoptarr['access_token'];

}

function http_request($url,$data=array()){

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

// 我们在POST数据哦!

curl_setopt($ch, CURLOPT_POST, 1);

// 把post的变量加上

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$output = curl_exec($ch);

curl_close($ch);

return $output;

}

}

2、控制器调用:<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller {

//还车函数

public function ajaxhuanche(){

import('Common.Class.WxTemple');

$sendMes = new \sendMessage();

//data的数据根据模板的不同内容不同

$template=array(

'touser'=>'',//接收模板消息的用户openid

'template_id'=>"oI4HUHs49sHAnFKAYjvwP-JOXlvnyzr51DY8b4cFitA",//模板消息的id

'url'=>'http://www.bulang123.com',

'topcolor'=>"#7B68EE",

'data'=>array(

'first'=>array('value'=>urlencode("用户还车通知"),'color'=>"#743A3A"),

'keyword1'=>array('value'=>urlencode("步浪----18335908000"),'color'=>'#333'),

'keyword2'=>array('value'=>urlencode("2017-4-19"),'color'=>'#333'),

'keyword3'=>array('value'=>urlencode("888元"),'color'=>'#333'),

'remark'=>array('value'=>urlencode('步浪博客,助各位同仁更上一层楼'),'color'=>'#DD5044'),

)

);

$access_token = $sendMes->getAccesstoken();

$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;

$res=$sendMes->http_request($url,urldecode($json_template));

if ($res[errcode]==0){

$this->ajaxReturn("200");//发送成功

}else{

$this->ajaxReturn("400");//发送失败

};

}

}

三、代码部署解析:

1、第一个类库文件放到自己习惯放的文件目录(个人习惯在common文件夹);

2、注意引入类库时路径的修改;

3、在类库里面修改自己的公众号的appid和appsecret;

4、在微信的后台有上千个模板,如果没有找到自己中意的女神,可以申请自己开发一个;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值