public function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function http_request_json_data($url,$post_data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/*==============发送模板消息 独立的代码块=======================*/
//http://suez.xyhs.xin/index.php/api/weixin/pipei
//$Weixin = new WeixinController(); //实例化类
//$Weixin->sendpipei($openid,$clientName,$tel,$product); //调用方法
public function pipei(){
$this->sendpipei("omPn_0godUbAbwPgpUEVN_X87Css","用户主动匹配","匹配成功");
}
//获得全局access_token
public function get_token(){
//如果已经存在直接返回access_token
//if($_SESSION[‘access_token‘] && $_SESSION[‘expire_time‘]>time()){
//return $_SESSION[‘access_token‘];
//}else{
$appid = C(‘WX_APPID‘); //appid
$appsecret = C(‘WX_APPSERECT‘); //appid
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; //请求地址
$res=$this->http_request_json($url);
if( curl_errno($ch) ){
var_dump( curl_error($ch) ); //打印错误信息
}
curl_close( $ch );
$arr = json_decode($res, true); //将结果转为数组
//$_SESSION[‘access_token‘]=$arr[‘access_token‘]; //将access_token存入session中,可以不存,每次都获得新的token
//$_SESSION[‘expire_time‘]=time()+7200;
return $arr[‘access_token‘];
//}
}
//推送模板信息 参数:发送给谁的openid,客户姓名,客户电话,推荐楼盘(参数自定)
public function sendpipei($openid,$pipeileixing,$jindu) {
//获取全局token
$token = $this->get_token();
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token; //模板信息请求地址
//发送的模板信息(微信要求json格式,这里为数组(方便添加变量)格式,然后转为json)
$post_data = array(
"touser"=>$openid, //推送给谁,openid
"template_id"=>"h7_UWH1okF8PoDneH8Q86cGpdLxlvkFAKQCM9ZhNFmo", //微信后台的模板信息id
"url"=>"http://www.xxxx.xin/index.php/jmobile/index/my", //点击之后跳转页面
"data"=> array(
"first" => array(
"value"=>"您的匹配情况有了更新",
"color"=>"#173177"
),
"keyword1"=>array(
"value"=>$pipeileixing, //传的变量 类型:客户主动匹配
"color"=>"#173177"
),
"keyword2"=>array(
"value"=>$jindu,//传的变量 进度:匹配成功
"color"=>"#173177"
),
"remark"=> array(
"value"=>"欢迎您及时确定您的更新信息。",
"color"=>"#173177"
),
)
);
//将上面的数组数据转为json格式
$post_data = json_encode($post_data);
//发送数据,post方式
$data=$this->http_request_json_data($url,$post_data);
$data = json_decode($data,true); //将json数据转成数组
return $data;
}
/*==============发送模板消息 独立的代码块=======================*/
原文地址:https://www.cnblogs.com/thinkbig/p/10217188.html