PHP获取微信小程序接口B二维码

微信小程序接口B二维码接口调用

微信小程序生成二维码共有三个接口(详情见官方文档),由于业务量的需要,B接口运用较多,这里主要记录B接口的调用。

微信官方文档。 —— [ 微信小程序二维码获取文档 ]


第一步:获得access_token

微信官方文档。 —— [ 获取access_token ]

第二步:生成二维码

后台完整代码


    //获取access_token
    public function get_access_token(){
            $appid = '';//配置appid 
            $secret = '';//配置secret 
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            return $this->curl_get($url);
        }
    //开启curl get请求    
    public function curl_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }
    //获得二维码
    public function get_qrcode() {
        //header('content-type:image/gif');
        //header('content-type:image/png');
        header('content-type:image/jpg');//格式自选,不同格式貌似加载速度略有不同,想加载更快可选择jpg
        $data = array();
        $data['page'] = '';//路径
        $data['scene'] = '';//场景参数
        $data = json_encode($data);
        $access = json_decode($this->get_access_token(),true);
        $access_token= $access['access_token'];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $da = $this->get_http_array($url,$data);
    }
    //开启curl post请求
    public function get_http_array($url,$post_data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //没有这个会自动输出,不用print_r();也会在后面多个1
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        echo $output;
        die;
    }

附:微信小程序js文件中查看scene所带的参数

    Page({
      onLoad: function(options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        var scene = decodeURIComponent(options.scene)
        consol.log(scene)
      }
    })

猜你喜欢

转载自blog.csdn.net/weixin_41722647/article/details/81286880