代碼說明javascript
1.實現了調用了圖靈的聊天機器人接口,實現了部分功能回覆文本消息圖文消息,不能接收圖片消息php
2.關注事件回覆歡迎關注css
3.獲取關注人員的信息html
4.memcache緩存java
5.網頁受權的兩種方式json
6.建立自定義菜單api
6.curl發送請求緩存
7.jssdk預覽本機圖片服務器
主要有四個文件微信
1.接收微信服務器消息的頁面wx_sample.php
<?php require "./config.php"; require "./wxApi.class.php"; $echostr = $_GET['echostr']; $weixin = new wxApi(APPID, APPSECRET); $weixin->valid(); //接收處理微信服務器轉發的xml數據包 $post = $HTTP_RAW_POST_DATA; $weixin->chat($post);
2.配置文件config.php
<?php define("TOKEN", "xxx"); define("APPID", "xxxxxxxxxxx"); define("APPSECRET", "xxxxxxxxxxxx");
3.微信網頁受權的頁面weixin.php
<?php require "./config.php"; require "./wxApi.class.php"; $echostr = $_GET['echostr']; $weixin = new wxApi(APPID, APPSECRET); $signPackage = $weixin->jssdk_signture(); var_dump($signPackage); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"> <title></title> <link rel="stylesheet" href="./weui/dist/style/weui.min.css"> </head> <body> <button id="dog" class="weui_btn weui_btn_primary">img</button> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script type="text/javascript"> wx.config({ debug: true, appId: '<?php echo $signPackage["appId"];?>', timestamp: <?php echo $signPackage["timestamp"];?>, nonceStr: '<?php echo $signPackage["nonceStr"];?>', signature: '<?php echo $signPackage["signature"];?>', jsApiList: ['chooseImage' // 全部要調用的 API 都要加到這個列表中 ] }); wx.ready(function () { // 在這裏調用 API var img = document.getElementById('dog'); img.onclick = function(){ wx.chooseImage({ count: 1, // 默認9 sizeType: ['original', 'compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有 sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有 success: function (res) { var localIds = res.localIds; // 返回選定照片的本地ID列表,localId能夠做爲img標籤的src屬性顯示圖片 } }); } }); </script> </body> </html>
4.類文件 wxApi.class.php
1 <?php 2 class wxApi 3 { 4 public $appid; 5 public $appsecret; 6 private $access_token; 7 public function init_access_token() 8 { 9 $this->access_token = $this->get_access_token(); 10 } 11 public function __construct($appid='',$appsecret='') 12 { 13 $this->appid = $appid; 14 $this->appsecret = $appsecret; 15 $this->init_access_token(); 16 } 17 public function valid(){ 18 if($this->checkSignature()) 19 { 20 echo $_GET['echostr']; 21 } 22 else 23 { 24 echo "Error"; 25 } 26 } 27 //檢驗微信加密簽名 28 private function checkSignature() 29 { 30 $signature = $_GET['signature']; 31 $timestamp = $_GET['timestamp']; 32 $nonce = $_GET['nonce']; 33 34 //加密 35 //1.將token,timestamp,nonce三個參數進行字典排序 36 37 $tmpArr = array(TOKEN, $timestamp, $nonce); 38 sort($tmpArr, SORT_STRING); 39 40 //2.將三個參數字符串拼接成爲一個字符串進行sha1加密 41 42 $tmpStr = implode($tmpArr); 43 $tmpStr = sha1($tmpStr); 44 45 //3.將開發者得到的加密後的字符串與signature對比 46 47 if($tmpStr == $signature){ 48 echo true; 49 }else{ 50 echo false; 51 } 52 } 53 //獲取接口調用憑證access_token 54 public function get_access_token() 55 { 56 if(!$this->memcache_get('access_token')){ 57 $this->create_access_token(); 58 } 59 return $this->memcache_get('access_token'); 60 } 61 //生成access_token 62 public function create_access_token() 63 { 64 $uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}"; 65 $data = $this->curl_get($uri); 66 $access_token = $data['access_token']; 67 $this->memcache_set('access_token', $access_token); 68 } 69 //緩存數據到memcache 70 public function memcache_set($key, $value) 71 { 72 $mmc = new Memcache; 73 $mmc->connect(); 74 $mmc->set($key, $value, 0, 7200); 75 } 76 //得到memcache的數據 77 public function memcache_get($key) 78 { 79 $mmc = new Memcache; 80 $mmc->connect(); 81 return $mmc->get($key); 82 } 83 //清空memcache數據 84 public function memcache_flush() 85 { 86 $mmc = new Memcache; 87 $mmc->connect(); 88 return $mmc->flush(); 89 } 90 91 //發送curl get請求 92 public function curl_get($uri='') 93 { 94 $ch = curl_init (); 95 curl_setopt ( $ch, CURLOPT_URL, $uri ); 96 curl_setopt ( $ch, CURLOPT_HEADER, 0 ); 97 curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); 98 $return = curl_exec($ch); 99 curl_close ( $ch ); 100 $return = json_decode($return, true); 101 return $return; 102 } 103 //發送post請求 104 public function curl_post($url, $post) 105 { 106 $ch = curl_init (); 107 curl_setopt ( $ch, CURLOPT_URL, $url ); 108 curl_setopt ( $ch, CURLOPT_HEADER, 0 ); 109 curl_setopt($ch, CURLOPT_POST, 1); 110 curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 111 112 curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); 113 $return = curl_exec($ch); 114 curl_close ( $ch ); 115 return $return; 116 } 117 //接收傳遞的數據 118 public function receive($post) 119 { 120 //處理xml數據包 121 $xmlobj = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA); 122 123 $data['toUserName'] = $xmlobj->ToUserName; 124 $data['fromUserName'] = $xmlobj->FromUserName; 125 $data['msgType'] = $xmlobj->MsgType; 126 $data['Content'] = $xmlobj->Content; 127 128 return $data; 129 } 130 131 //發送數據 132 public function send($content) 133 { 134 //發送get 135 $uri = "http://www.tuling123.com/openapi/api?" . "key=d92dd28bbcb446a8a127beb6eae611ee&info=" . $content; 136 return $this->curl_get($uri); 137 } 138 public function chat($post) 139 { 140 $data = $this->receive($post); 141 142 $msgType = $data['msgType']; 143 144 switch($msgType){ 145 case 'text': 146 $this->chat_chat($data); 147 break; 148 case 'event': 149 $this->event($data); 150 break; 151 } 152 } 153 //聊天消息 154 public function chat_chat($data) 155 { 156 $content = $data['Content']; 157 158 $return = $this->send($content); 159 160 $fromUserName = $data['fromUserName']; 161 $toUserName = $data['toUserName']; 162 $msgType = $data['msgType']; 163 164 165 $content = $return['text']; 166 $code = $return['code']; 167 168 switch($code){ 169 case 100000: 170 $reply = "<xml> 171 <ToUserName><![CDATA[%s]]></ToUserName> 172 <FromUserName><![CDATA[%s]]></FromUserName> 173 <CreateTime>%s</CreateTime> 174 <MsgType><![CDATA[%s]]></MsgType> 175 <Content><![CDATA[%s]]></Content> 176 </xml>"; 177 echo sprintf($reply, $fromUserName, $toUserName, time(), $msgType, $content); 178 break; 179 case 200000: 180 $reply = "<xml> 181 <ToUserName><![CDATA[%s]]></ToUserName> 182 <FromUserName><![CDATA[%s]]></FromUserName> 183 <CreateTime>%s</CreateTime> 184 <MsgType><![CDATA[news]]></MsgType> 185 <ArticleCount>1</ArticleCount> 186 <Articles> 187 <item> 188 <Title><![CDATA[%s]]></Title> 189 <Description><![CDATA[%s]]></Description> 190 <PicUrl><![CDATA[%s]]></PicUrl> 191 <Url><![CDATA[%s]]></Url> 192 </item> 193 </Articles> 194 </xml>"; 195 $title = $return['text']; 196 $Description = ''; 197 $PicUrl = 'http://1.catrazy.applinzi.com/img/t01f69da5a3069ac3b3.jpg'; 198 $Url = $return['url']; 199 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url); 200 break; 201 case 302000: 202 $reply = "<xml> 203 <ToUserName><![CDATA[%s]]></ToUserName> 204 <FromUserName><![CDATA[%s]]></FromUserName> 205 <CreateTime>%s</CreateTime> 206 <MsgType><![CDATA[news]]></MsgType> 207 <ArticleCount>1</ArticleCount> 208 <Articles> 209 <item> 210 <Title><![CDATA[%s]]></Title> 211 <Description><![CDATA[%s]]></Description> 212 <PicUrl><![CDATA[%s]]></PicUrl> 213 <Url><![CDATA[%s]]></Url> 214 </item> 215 </Articles> 216 </xml>"; 217 $num = ceil(rand(0,10)); 218 $title = $return['text']; 219 $Description = $return['list'][$num]['article']; 220 $PicUrl = $return['list'][$num]['icon']; 221 $Url = $return['list'][$num]['detailurl']; 222 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url); 223 break; 224 case 308000: 225 $reply = "<xml> 226 <ToUserName><![CDATA[%s]]></ToUserName> 227 <FromUserName><![CDATA[%s]]></FromUserName> 228 <CreateTime>%s</CreateTime> 229 <MsgType><![CDATA[news]]></MsgType> 230 <ArticleCount>1</ArticleCount> 231 <Articles> 232 <item> 233 <Title><![CDATA[%s]]></Title> 234 <Description><![CDATA[%s]]></Description> 235 <PicUrl><![CDATA[%s]]></PicUrl> 236 <Url><![CDATA[%s]]></Url> 237 </item> 238 </Articles> 239 </xml>"; 240 $num = ceil(rand(0,10)); 241 $title = $return['text']; 242 $Description = $return['list'][$num]['article']; 243 $Url = $return['list'][$num]['detailurl']; 244 $str = file_get_contents($Url); 245 $preg = '/<img\s+src=.*>/'; 246 preg_match($preg, $str, $match); 247 $PicUrl = $match[0]; 248 echo sprintf($reply, $fromUserName, $toUserName, time(), $title, $Description, $PicUrl, $Url); 249 break; 250 } 251 } 252 //事件推送消息(關注事件) 253 public function event($data) 254 { 255 $fromUserName = $data['fromUserName']; 256 $toUserName = $data['toUserName']; 257 $content = "歡迎關注"; 258 $reply = "<xml> 259 <ToUserName><![CDATA[%s]]></ToUserName> 260 <FromUserName><![CDATA[%s]]></FromUserName> 261 <CreateTime>%s</CreateTime> 262 <MsgType><![CDATA[text]]></MsgType> 263 <Content><![CDATA[%s]]></Content> 264 </xml>"; 265 echo sprintf($reply, $fromUserName, $toUserName, time(),$content); 266 } 267 //建立自定義菜單 268 public function create_menu() 269 { 270 $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->get_access_token()}"; 271 $post = '{ 272 "button":[ 273 { 274 "name":"菜單", 275 "sub_button":[ 276 { 277 "name":"關於咱們", 278 "type":"view", 279 "url":"http://www.soso.com/" 280 }, 281 { 282 "name":"搜索", 283 "type":"view", 284 "url":"http://www.soso.com/" 285 } 286 ] 287 288 }, 289 { 290 "name":"哈哈哈", 291 "type":"view", 292 "url":"http://1.catrazy.applinzi.com/weixin.php" 293 } 294 ] 295 }'; 296 297 echo $this->curl_post($url, $post); 298 } 299 //獲取用戶列表 300 public function get_user_list() 301 { 302 $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $this->access_token; 303 $data = $this->curl_get($url); 304 // echo '<pre>'; 305 // var_dump($data); 306 $openids = $data['data']['openid']; 307 // var_dump($openids); 308 return $openids; 309 } 310 //獲取用戶全部的基本信息 311 public function get_user_info() 312 { 313 $access_token = $this->access_token; 314 $openids = $this->get_user_list(); 315 foreach($openids as $openid){ 316 $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN"; 317 $user_info[] = $this->curl_get($url); 318 } 319 return $user_info; 320 } 321 //base型受權 322 public function snsapi_base($redirect_uri) 323 { 324 // 1.準備scope爲scope_base的網頁受權頁面url 325 $snsapi_base_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect"; 326 // 2. 靜默受權 獲取code 327 328 //頁面將跳轉至redirect_uri/?code=CODE&state=STATE 329 if(!isset($_GET['code'])){ 330 header("Location:{$snsapi_base_url}"); 331 } 332 333 // 3.經過code換區頁面受權access_token 334 $code = $_GET['code']; 335 336 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code"; 337 $return = $this->curl_get($url); 338 $key = "token"; 339 $value = $return['openid']; 340 $this->memcache_set($key, $value); 341 return $return; 342 } 343 //userinfo型受權 344 public function snsapi_userinfo($redirect_uri) 345 { 346 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"; 347 if(!isset($_GET['code'])){ 348 header("Location:{$url}"); 349 } 350 $code = $_GET['code']; 351 352 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code"; 353 $return = $this->curl_get($url); 354 355 $token = $return['access_token']; 356 $openid = $return['openid']; 357 358 $url_info = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$openid}&lang=zh_CN"; 359 return $this->curl_get($url_info); 360 } 361 //獲取jsapi 362 public function get_jsapi() 363 { 364 $jsapi_ticket = $this->memcache_get('jsapi_ticket'); 365 if(!$jsapi_ticket){ 366 $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$this->access_token}&type=jsapi"; 367 $data = $this->curl_get($url); 368 $this->memcache_set('jsapi_ticket', $data['ticket']); 369 } 370 return $jsapi_ticket; 371 } 372 //獲取jssdk簽名 373 public function jssdk_signture() 374 { 375 $jsapiTicket = $this->get_jsapi(); 376 377 // 注意 URL 必定要動態獲取,不能 hardcode. 378 $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; 379 $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 380 381 $timestamp = time(); 382 $nonceStr = "hkasfhkh"; 383 384 // 這裏參數的順序要按照 key 值 ASCII 碼升序排序 385 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; 386 387 $signature = sha1($string); 388 389 $signPackage = array( 390 "appId" => $this->appid, 391 "nonceStr" => $nonceStr, 392 "timestamp" => $timestamp, 393 "url" => $url, 394 "signature" => $signature, 395 "rawString" => $string 396 ); 397 return $signPackage; 398 } 399 }