Laravel 小程序生成二维码

最近公司业务涉及到小程序的二维码分享,看了网上好多教程,不是很完善,有很多坑,所以这里我来实现一下完整的流程。

微信官方说明

官网的地址链接https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

官方有三个接口如下:

  1. 接口 A: 适用于需要的码数量较少的业务场景https://developers.weixin.qq.com/miniprogram/dev/api/open-api/qr-code/createWXAQRCode.html
  2. 接口B: 适用于需要的码数数量极多的业务场景https://developers.weixin.qq.com/miniprogram/dev/api/open-api/qr-code/getWXACode.html
  3. 接口C: 适用于需要的码数量较少的业务场景https://developers.weixin.qq.com/miniprogram/dev/api/open-api/qr-code/createWXAQRCode.html

 

PHP代码实现

首先先实现公共函数,如下:

 private  function httpRequest($url, $data='', $method='GET'){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
            if($method=='POST')
            {
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data != '')
                {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                }
            }

            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);
            curl_close($curl);
            return $result;
          }

 接下来实现调用公共方法生成二维码

 public function createQrCode(){
        header('content-type:text/html;charset=utf-8');
        //配置APPID、APPSECRET
        $APPID = config('wechat.mini_program.default.app_id');
        $APPSECRET =  config('wechat.mini_program.default.secret');
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

       
        //缓存access_token
        // session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;

         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {

             $json =  $this->httpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
           
         }
         else{

             $ACCESS_TOKEN =  $_SESSION["access_token"];
         }

        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $url =  env("APP_URL")."/api/login";
        $param = json_encode(array("path"=> $url,"width"=> 150));
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //生成二维码
        file_put_contents("qrcode.png", $result);
        $base64_image ="data:image/jpeg;base64,".base64_encode($result);
}

到这里调用createQrCode这个方法,就会生成Base64的码,接下来只需要转码保存二维码就行。

完整代码如下:

  public function createQrCode(){
        header('content-type:text/html;charset=utf-8');
        //配置APPID、APPSECRET
        $APPID = config('wechat.mini_program.default.app_id');
        $APPSECRET =  config('wechat.mini_program.default.secret');
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

       
        //缓存access_token
        // session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;

         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {

             $json =  $this->httpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
           
         }
         else{

             $ACCESS_TOKEN =  $_SESSION["access_token"];
         }

        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $url =  env("APP_URL")."/api/login";
        $param = json_encode(array("path"=> $url,"width"=> 150));
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //生成二维码
        file_put_contents("qrcode.png", $result);
        $base64_image ="data:image/jpeg;base64,".base64_encode($result);
        $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.png';
        if (strstr($base64_image,",")){
          $base64_image = explode(',',$base64_image);
        $base64_image = $base64_image[1];
        }
        $path = "C:/Users/Administrator/Desktop/develop/testing-backend/".date("Ymd",time());
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
          mkdir($path,0777,true);
        }
        $imageSrc= $path."/". $imageName; //图片名字
        $r = file_put_contents($imageSrc, base64_decode($base64_image));//返回的是字节数
        if (!$r) {
         $tmparr1=array('data'=>null,"code"=>1,"msg"=>"图片生成失败");
         echo json_encode($tmparr);
        }else{
         $tmparr2=array('data'=>1,"code"=>0,"msg"=>"图片生成成功");
         echo json_encode($tmparr2);
        }
              
}
         //把请求发送到微信服务器换取二维码
    private  function httpRequest($url, $data='', $method='GET'){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
            if($method=='POST')
            {
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data != '')
                {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                }
            }

            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);
            curl_close($curl);
            return $result;
          }

 这是去看图片保存的文件里是否有这个

不错成功生成了。

注意:在获取二维码时,需要post向接口提交数据,只是说返回的是object。没有直接在文件中说明提交的post数据也需要是json对象。发送的既然不是数组,那么在curl请求就不能写成

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post))

必须写成

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

关于作者

Taurus
获得点赞
文章被阅读