1. 程式人生 > >PHP 微信公眾號開發 - 消息推送

PHP 微信公眾號開發 - 消息推送

function mic req ade appid encode enc pub cnblogs

項目微信公眾號開發,需要做用戶消息推送,記錄下來以便日後使用

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 }

PHP 微信公眾號開發 - 消息推送