php 公众号模板消息推送

再申请完模板后,根据官方文档,我们知道需要将数据json化后post到下面这个地址

https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

那么我们就需要获取ACCESS_TOKEN,这个如何获取呢?获取的方式官方给出了好多种,找了一会就用这个最直接的吧,其中的appid和appsecret,请在公号基本配置中查找。

https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

正常情况下,请求GET请求这个地址微信会返回如下数据:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

其中的access_token就是我们需要的,将数据对应申请的模板填写一下 执行发送就可以了,完整代码如下:


public  function http_curl($url,$type,$res,$arr){
            /*
            $url 请求的url
            $type 请求类型
            $res 返回数据类型
            $arr post请求参数
             */
            $ch=curl_init();
            /*$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET';  */
            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);
            if($type=='post'){
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
            }
            $output = curl_exec($ch);
            curl_close($ch);
            if($res=='json'){
                return json_decode($output,true);
            }
    }


function send(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
        $urlgetcon = file_get_contents($url);
        $usera = json_decode($urlgetcon, TRUE); 
        $token = $usera['access_token'];
    	$posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
        $openid = '获取用户openid';
        $dt = array(
            "touser" => $openid,
            'template_id'  => '模板id',
            'url'   => "点击跳转URL",
			'data' => array(
              'first' =>array('value' => '您好,您寄卖的券出现纠纷!'),
              'keyword1' =>array('value' =>$quann ),
              'keyword2' =>array('value' => date('Y-m-d H:i:s')),
              'keyword3' =>array('value' => 'XX权益'),
              'remark' 	=>array('value' => '感谢您对我们平台的支持!'),
              ),
        );
		$postjson = json_encode($dt);
		$resder = $this->http_curl($posturl,'post','json',$postjson);
}

效果:
效果演示
有啥问题可以直接评论哦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值