1. 程式人生 > >小程式二維碼生成中的一些坑

小程式二維碼生成中的一些坑

小程式二維碼生成介面:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
官方提供了三種介面,我這裡使用的是B類介面,遇到的幾個坑都是通用的。

1、access_token應放在url中,不在post傳遞的引數中
在這裡,如果你僅把access_token放在post傳遞的引數中或url和post傳參中都放,會報錯access_token失效或資料格式錯誤
2、scene不能為空,隨意填寫就行,但不能為空

方案一(將二維碼儲存在本地):

public function getQRcode()
    {
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret),true)['access_token'];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
        $ch = curl_init();
        $data = json_encode(['scene' => 'test']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳過ssl檢測
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要將結果直接返回到變數裡,那加上這句。
        $res = curl_exec($ch);

        file_put_contents('test.png',$res);
        $this->smarty_lib->tmp("getQRcode.html",'');
    }

方案二(直接渲染):

public function getQRcode()
    {
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret),true)['access_token'];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
        $ch = curl_init();
        $data = json_encode(['scene' => 'test']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要將結果直接返回到變數裡,那加上這句。
        $res = curl_exec($ch);
        $data = 'data:image/jpeg;base64,'.base64_encode($res);//補全base64加密字串頭
        $html = "<!DOCTYPE html>
                <html lang='en'>
                <head>
                    <meta charset='UTF-8'>
                    <title>二維碼</title>
                </head>
                <body>
                <img src='$data'>
                </body>
                </html>";
        echo $html;
        exit;
    }
  • note:微信介面返回的是二進位制圖片,所以需要先處理一番再渲染