PHP 微信小程序 模板消息推送

PHP 推送 微信 小程序模版消息的方式,若有不足之处还望指正

form_id 是用户与小程序产生交互时产生的一个 key ,小程序推送模版消息必须要用到它。 获取方法及使用限制另作记录


<?php
namespace common\helpers;

use common\models\ManyCommon;

class WechatMiniPush
{

    public function PushOneMsg($pushInfo)
    {
        $access_token = $this->access_token($pushInfo['app_id'],$pushInfo['app_secret']);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
        $data = [
            'access_token' => $access_token,
            'touser' => $pushInfo['open_id'],
            'template_id' => '3WcSq-oH1-fcMrd-jyDyWRz_5gc4zIIT-5rlyCjTw_A',
            'page' => 'pages/tenant/index',
            'form_id' => $pushInfo['form_id'],
            'data' => $this->pushKeywords($pushInfo),
        ];
        return $this->http_post_data($url, $data);
    }

    public function pushKeywords($pushInfo)
    {
        $data = [
            'keyword1' => ['value' => "朋友,您最近在看的求租信息有更新",],
            'keyword2' => ['value' => "为您准备了1000+ 最新的机械求租信息"],
            'keyword3' => ['value' => "点击查看即可查看为你精心准备的求租信息,感谢您长期以来对 \"{$pushInfo['app_name']}\" 的支持!"],
        ];
        return $data;
    }

    /**http - post请求*/
    function http_post_data($url, $data)
    {
        $data = json_encode($data);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)
        ));
        $return_content = curl_exec($ch);
        return $return_content;
    }

    /**发起网络请求 获取 access_token */
    private function get_access_token($appId, $appSecret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $info = file_get_contents($url);
        $json = json_decode($info);
        $arr = get_object_vars($json);
        $access_token = $arr['access_token'];
        return $access_token;
    }

}

原文链接 PHP 微信小程序 模板消息推送

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容