PHP 微信公众号开发 - 消息推送

时间:2018-03-06 12:02:37   收藏:0   阅读:366

项目微信公众号开发,需要做用户消息推送,记录下来以便日后使用

1,接上一篇文章,可以查看如何获取用户openid

  PHP 微信公众号开发 - 获取用户信息

2,添加模板消息

技术分享图片

 

 3,查看模板详情

  根据模板详情设置对应推送消息

技术分享图片

4,代码实现

 

  1 <?php
  2 // 字符编码
  3 header("Content-Type:text/html; charset=utf-8");
  4 
  5 // 微信接口类
  6 class WeChat{
  7     private static $appid;
  8     private static $appsecret;
  9 
 10     function __construct(){
 11         self::$appid = ‘‘;      // 开发者ID(AppID)
 12         self::$appsecret = ‘‘;  // 开发者密码(AppSecret)
 13     }
 14 
 15     // 微信授权地址
 16     public static function getAuthorizeUrl($url){
 17         $url_link = urlencode($url);
 18         return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . self::$appid . "&redirect_uri={$url_link}&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
 19     }
 20 
 21     // 获取TOKEN
 22     public static function getToken(){
 23         $urla = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::$appid . "&secret=" . self::$appsecret;
 24         $outputa = self::curlGet($urla);
 25         $result = json_decode($outputa, true);
 26         return $result[‘access_token‘];
 27     }
 28 
 29     /**
 30      * getUserInfo 获取用户信息
 31      * @param  string $code         微信授权code
 32      * @param  string $weiwei_token Token
 33      * @return array
 34      */
 35     public static function getUserInfo($code, $weiwei_token){
 36         $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . self::$appid . "&secret=" . self::$appsecret . "&code={$code}&grant_type=authorization_code";
 37         $access_token_json = self::curlGet($access_token_url);
 38         $access_token_array = json_decode($access_token_json, true);
 39         $openid = $access_token_array[‘openid‘];
 40         $new_access_token = $weiwei_token;
 41 
 42         //全局access token获得用户基本信息
 43         $userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$new_access_token}&openid={$openid}";
 44         $userinfo_json = self::curlGet($userinfo_url);
 45         $userinfo_array = json_decode($userinfo_json, true);
 46         return $userinfo_array;
 47     }
 48 
 49     /**
 50      * pushMessage 发送自定义的模板消息
 51      * @param  array  $data          模板数据
 52         $data = [
 53             ‘openid‘ => ‘‘, 用户openid
 54             ‘url‘ => ‘‘, 跳转链接
 55             ‘template_id‘ => ‘‘, 模板id
 56             ‘data‘ => [ // 消息模板数据
 57                 ‘first‘    => [‘value‘ => urlencode(‘黄旭辉‘),‘color‘ => "#743A3A"],
 58                 ‘keyword1‘ => [‘value‘ => urlencode(‘男‘),‘color‘=>‘blue‘],
 59                 ‘keyword2‘ => [‘value‘ => urlencode(‘1993-10-23‘),‘color‘ => ‘blue‘],
 60                 ‘remark‘   => [‘value‘ => urlencode(‘我的模板‘),‘color‘ => ‘#743A3A‘]
 61             ]
 62         ];
 63      * @param  string $topcolor 模板内容字体颜色,不填默认为黑色
 64      * @return array
 65      */
 66     public static function pushMessage($data = [],$topcolor = ‘#0000‘){
 67         $template = [
 68             ‘touser‘      => $data[‘openid‘],
 69             ‘template_id‘ => $data[‘template_id‘],
 70             ‘url‘         => $data[‘url‘],
 71             ‘topcolor‘    => $topcolor,
 72             ‘data‘        => $data[‘data‘]
 73         ];
 74         $json_template = json_encode($template);
 75         $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . self::getToken();
 76         $result = self::curlPost($url, urldecode($json_template));
 77         $resultData = json_decode($result, true);
 78         return $resultData;
 79     }
 80 
 81     /**
 82      * addLog 日志记录
 83      * @param string $log_content 日志内容
 84      */
 85     public static function addLog($log_content = ‘‘){
 86         $data = "";
 87         $data .= "DATE: [ " . date(‘Y-m-d H:i:s‘) . " ]\r\n";
 88         $data .= "INFO: " . $log_content . "\r\n\r\n";
 89         file_put_contents(‘/wechat.log‘, $data, FILE_APPEND);
 90     }
 91 
 92     /**
 93      * 发送get请求
 94      * @param string $url 链接
 95      * @return bool|mixed
 96      */
 97     private static function curlGet($url){
 98         $curl = curl_init();
 99         curl_setopt($curl, CURLOPT_URL, $url);
100         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
101         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
102         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
103         $output = curl_exec($curl);
104         if(curl_errno($curl)){
105             return ‘ERROR ‘ . curl_error($curl);
106         }
107         curl_close($curl);
108         return $output;
109     }
110 
111     /**
112      * 发送post请求
113      * @param string $url 链接
114      * @param string $data 数据
115      * @return bool|mixed
116      */
117     private static function curlPost($url, $data = null){
118         $curl = curl_init();
119         curl_setopt($curl, CURLOPT_URL, $url);
120         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
121         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
122         if(!empty($data)){
123             curl_setopt($curl, CURLOPT_POST, 1);
124             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
125         }
126         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
127         $output = curl_exec($curl);
128         curl_close($curl);
129         return $output;
130     }
131 }
132 
133 /**
134  * get_page_url 获取完整URL
135  * @return url
136  */
137 function get_page_url($type = 0){
138     $pageURL = ‘http‘;
139     if($_SERVER["HTTPS"] == ‘on‘){
140         $pageURL .= ‘s‘;
141     }
142     $pageURL .= ‘://‘;
143     if($type == 0){
144         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
145     }else{
146         $pageURL .= $_SERVER["SERVER_NAME"];
147     }
148     return $pageURL;
149 }
150 
151 // 获取用户openid
152 
153 // 微信接口类
154 $WeChat = new WeChat();
155 if(empty($_GET[‘code‘]) || !isset($_GET[‘code‘])){
156     // 通过授权获取code
157     $url = get_page_url();
158     $authorize_url = $WeChat->getAuthorizeUrl($url);
159     header("Location:{$authorize_url}"); // 重定向浏览器
160     exit();
161 }else{
162     // 获取微信用户信息
163     $code = $_GET[‘code‘];
164     $weiwei_token = $WeChat->getToken(); // 获取微信token
165     $user_info = $WeChat->getUserInfo($code, $weiwei_token);
166     $openid = $user_info[‘openid‘];
167     # 公众号消息推送
168     $WeChat::pushMessage([
169         ‘openid‘ => $openid, // 用户openid
170         ‘access_token‘ => $weiwei_token,
171         ‘template_id‘ => "ONZapeZi5OzxHym7IaZw7q4eJHEV4L6lzdQrEIWBs60", // 填写你自己的消息模板ID
172         ‘data‘ => [ // 模板消息内容,根据模板详情进行设置
173             ‘first‘    => [‘value‘ => urlencode("尊敬的某某某先生,您好,您本期还款已成功扣收。"),‘color‘ => "#743A3A"],
174             ‘keyword1‘ => [‘value‘ => urlencode("2476.00元"),‘color‘=>‘blue‘],
175             ‘keyword2‘ => [‘value‘ => urlencode("13期"),‘color‘=>‘blue‘],
176             ‘keyword3‘ => [‘value‘ => urlencode("15636.56元"),‘color‘ => ‘green‘],
177             ‘keyword4‘ => [‘value‘ => urlencode("6789.23元"),‘color‘ => ‘green‘],
178             ‘remark‘   => [‘value‘ => urlencode("更多贷款详情,请点击页面进行实时查询。"),‘color‘ => ‘#743A3A‘]
179         ],
180         ‘url_link‘ => ‘https://www.cnblogs.com/‘ // 消息跳转链接
181     ]);
182 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!