PHP獲取小程式碼並返回前端顯示圖片
阿新 • • 發佈:2018-12-05
小程式的二維碼分為小程式碼和二維碼;
生成小程式二維碼文件中說後端來生成。
參考 小程式開發文件資料:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html
文件的引數介紹還是蠻詳細的,但是沒有具體的demo,對於請求的介面的返回值是進位制流(也就是在瀏覽器顯示一堆亂碼)也是很令人懊惱,這裡貼一下我的程式碼:
//獲取小程式碼,這裡呼叫的是小程式碼的A介面型別 public function getQRCodeAction() { $data['scene'] = $this->_req->getQuery('shareId',11); //scence、page的使用要參考文件 $data['width'] = $this->_req->getQuery('width',220); $data['auto_color'] = $this->_req->getQuery('auto_color'); $data['line_color'] = $this->_req->getQuery('line_color'); $data['is_hyaline'] = $this->_req->getQuery('is_hyaline',true); $data['page'] = $this->_req->getQuery('page',""); //由這行以上程式碼是二維碼的樣式等由前端傳值的形式,也可以直接在後端設定 $wxModel = new WxAuthModel(); $token = $wxModel->getAccessToken(); $res_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token"; //請求微信提供的介面 header('content-type:image/png'); $data = json_encode($data); $Qr_code = $wxModel->http_request($res_url,$data); //到這裡就已經返回微信提供的返回資料了,這個時候的資料是二進位制流,要處理下再返回給前端 file_put_contents('/tmp/qr_code.png', $Qr_code); //將獲得的資料讀到一個臨時檔案裡 $img_string = $this->fileToBase64('/tmp/qr_code.png'); //將圖片檔案轉化為base64 response::result($img_string); } //本地檔案轉base64 private function fileToBase64($file){ $base64_file = ''; if(file_exists($file)){ $mime_type= mime_content_type($file); $base64_data = base64_encode(file_get_contents($file)); $base64_file = 'data:'.$mime_type.';base64,'.$base64_data; } return $base64_file; } /*獲取access_token,不需要code引數,不能用於獲取使用者資訊的token*/ public function getAccessToken() { $token_file = '/dev/shm/heka2_token.json'; //由於獲取token的次數存在限制,所以將一段時間內的token快取到一個檔案(注意快取路徑伺服器支援可寫可讀),過期後再重新獲取 $data = json_decode(file_get_contents($token_file)); if ($data->expire_time < time()) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $res = json_decode($this->http_request($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; file_put_contents($token_file, json_encode($data)); } } else { $access_token = $data->access_token; } return $access_token; }
感覺一個完整的PHP實現的程式碼目前我還沒找到,這個也還蠻常用的。如有不恰當的地方,歡迎指出~ ^_^