小程序的二維碼分為小程序碼和二維碼;
生成小程序二維碼文檔中說后端來生成。
參考 小程序開發文檔資料:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html
文檔的參數介紹還是蠻詳細的,但是沒有具體的demo,對於請求的接口的返回值是進制流(也就是在瀏覽器顯示一堆亂碼)也是很令人懊惱,這里貼一下我的代碼:
//獲取小程序碼,這里調用的是小程序碼的A接口類型
public function getQRCodeAction()
{
$data['scene'] = $this->_req->getQuery('shareId',11); //scence、page的使用要參考文檔(比如:scene的值不能超過32個字符等)
$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); //如果這里明確是圖片的話我建議獲取圖片類型這句可以省略,直接知道了mine_type='image/png',因為我這里我雖然存的圖片,但是讀到的mine_type值為text/plain
$base64_data = base64_encode(file_get_contents($file));
$base64_file = 'data:'.$mime_type.';base64,'.$base64_data; //$base64_file = 'data:image/png;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實現的代碼目前我還沒找到,這個自己用的還行。如有不恰當的地方,歡迎指出~ _
