小程序二维码生成中的一些坑

小程序二维码生成接口: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:微信接口返回的是二进制图片,所以需要先处理一番再渲染
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值