PHP 微信小程序给公众号推送消息

首先需要去微信公众平台配置一下关联  可以看一下这个链接 有详细讲述
微信小程序向公众号推送消息超详细教程_小程序通过公众号推送消息_亿只王菜菜的博客-CSDN博客

配置好以后就是代码部分

//获取token
    public function get_token(){
        $appid = '公众号appid';
        $appsecret = '公众号appsecret';
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $res = json_decode(file_get_contents($url), true);
        dd($res);
        $access_token = $res['access_token'];
        return $access_token;
    }

 public function sendMessage(){
        $ACCESS_TOKEN = $this->get_token();//通过微信获取access_token接口 获取的token
//        dd($ACCESS_TOKEN);
        $template_id = 'xxxxxxxx';//配置的模板id
        $url = 'index';//点击模板消息跳转的链接

        $template = array(
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => $url,
            'data' => array(
                'first' => array('value' => 'xxxxx'), //标题
                'keyword1' => array('value' => 'xxxxx'),  //姓名
                'keyword2' => array('value' => 'xxxxx'),  //手机
                'keyword3' => array('value' => 'xxxxx'),  //时间
                'remark' => array('value' => 'xxxxx'))//消息内容
        );

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

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $send_template_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($template));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

这样就可以直接拿过去用了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值