生成微信小程序碼


一、前言

1、官方開發文檔:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

2、項目要上線才可以生成哦

二、生成二維碼方法(Tp5.0版)

//生成企業二維碼
public function createCompanyEwm(){

    $post =input();

    if(!isset($post['id'])||empty($post['token'])){
        $param = array(
          'code' => 0,
          'msg'  =>'參數錯誤!',
         
        );
        return json($param);
    }

    $peizhi = [];
   //獲取配置
    $peizhi['appid']=Db::name('config')->where(['name'=>'appid'])->value('value');
    $peizhi['appsecret']=Db::name('config')->where(['name'=>'appsercet'])->value('value');
    $peizhi['qn_domain']=Db::name('config')->where(['name'=>'qn_domain'])->value('value');

    $token_content=file_get_contents("common_token.txt");//用於存儲access_token

    if($token_content==''){//獲取新的access_token
      
        $token_result=$this ->get_new_token($peizhi);
        $res= $token_result['res'];
        $new = $token_result['new'];
        //判斷失敗
        if(!$new['access_token']){
          $param = array(
            'code' => 0,
            'msg'  =>'獲取token失敗!',
            'new'=>$new
          );
          return json($param);
        }

        $access_token=$new['access_token'];
        //更新token緩存
        
        $maxTime=time()+intval($new['expires_in']);
        $access_arr=str_replace('}', ",\"maxTime\":".$maxTime."}", $res);
        file_put_contents("common_token.txt",$access_arr);
     
      }else{

        $token_arr=json_decode($token_content,true);

        if(intval($token_arr['maxTime'])<time()){

          $token_result=$this ->get_new_token($peizhi);
          $res= $token_result['res'];
          $new = $token_result['new'];

          if(!$new['access_token']){
            $param = array(
              'code' => 0,
              'msg'  =>'獲取token失敗!',
              'errcode'=>$new['errcode']
            );
            return json($param);
          }

          $access_token=$new['access_token'];

          $maxTime=time()+intval($new['expires_in']);
          $access_arr=str_replace('}', ",\"maxTime\":".$maxTime."}", $res);

          file_put_contents("common_token.txt",$access_arr);

        }else{

          $access_token=$token_arr['access_token'];

        }

      }


     if($access_token==''||strlen($access_token)<10){
          $param = array(
            'code' => 0,
            'msg'  =>'獲取token失敗!',
           
          );
          return json($param);
      }

      $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;

      $data=array(
        'scene'=>intval($post['id']).','.trim($post['token']),
        'page'=>'pages/details/details',
        'width'=>430,
        'auto_color'=>true,
        'is_hyaline'=>false
      );

        
      //header("Content-type: image/jpg");
      $ewm_res= $this->api_notice_increment($url,json_encode($data));


      $dejson_ewm_res=json_decode($ewm_res,1);

        if($dejson_ewm_res['errcode']==41030){
            $param = array(
                'code' => 0,
                'msg'  =>'所傳page頁面不存在,或者小程序沒有發布',
                'dejson_ewm_res'=>$dejson_ewm_res
               
            );
            return json($param);

        }
        if($dejson_ewm_res['errcode']==45009){
                $param = array(
                'code' => 0,
                'msg'  =>'調用分鍾頻率受限(目前5000次/分鍾,會調整),如需大量小程序碼,建議預生成。',
                'dejson_ewm_res'=>$dejson_ewm_res
               
            );
            return json($param);

        }


      if($dejson_ewm_res['errcode']==40001){//token無效


        $token_result=$this ->get_new_token($peizhi);
        $res= $token_result['res'];
        $new = $token_result['new'];
        $access_token=$new['access_token'];

        $maxTime=time()+intval($new['expires_in']);
        $access_arr=str_replace('}', ",\"maxTime\":".$maxTime."}", $res);

        file_put_contents("common_token.txt",$access_arr);
        
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;

        //header("Content-type: image/jpg");

        $ewm_res= $this->api_notice_increment($url,json_encode($data));

      }
      $img=$this->change_picture($ewm_res);
      $base64_img=$this->base64EncodeImage($img);
      $this->delDirAndFile('./public/uploads/temporary/');

      error_reporting(0);
      //上傳到七牛
      $Qiniu=new Qiniu();
      $data=json_decode($Qiniu->liuUpload($base64_img),true);
      $data['url']='http://'.$peizhi['qn_domain'].'/'.$data['hash'];
      $file_exists=file_exists_get($data['url']);
      if(!$file_exists){
           return json(['code'=>0,'msg'=>'生成失敗!']);
      }

      //數據存入數據庫
      $companyObj = new CompanyModel();
      $flag = $companyObj->editCompany(['id'=>$post['id'],'ewm'=>$data['url'],'addtime'=>time()]);
      
      $param = array(
          'code' => 1,
          'msg'  =>'獲取成功',
          'data'=>$data,
      );

      return json($param);

}

 //獲取新的token
  function get_new_token($peizhi){
    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$peizhi['appid']."&secret=".$peizhi['appsecret'];
    $res= httpRequest($url);
    $new = json_decode($res,1);
    $result=array('res'=>$res,'new'=>$new);
    return $result;
  }
  
  //網絡requst
  function httpRequest($url,$data = null){
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      if (!empty($data)){
       curl_setopt($curl, CURLOPT_POST, 1);
       curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     //執行
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
  }

  /**
   * 網絡請求-用於獲取二維碼函數
   * @param  [type] $url  [description]
   * @param  [type] $data [description]
   * @return [type]       [description]
   */
  function api_notice_increment($url, $data){
      $ch = curl_init();
      $header = ["Content-type: image/jpg"];
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $tmpInfo = curl_exec($ch);
      curl_close($ch);

      return $tmpInfo;
  }

  //二進制二維碼圖片buffer,保存為臨時圖片
  public function change_picture($imgs){
      $path="./public/uploads/temporary/";
      if(!is_dir($path)){
          mkdir($path);
      }
      $new_file = "./public/uploads/temporary/" .'ewm'.date('Y-m-d',time()).getRandomString(8).".jpg"; //生成圖片的名字
      if(!empty($imgs)){
          $file = fopen($new_file,"w");//打開文件准備寫入
          fwrite($file,$imgs);//寫入
          fclose($file);//關閉
      }
      return $new_file;
  }

3、小程序獲取參數

Page({
  onLoad(query) {
    // scene 需要使用 decodeURIComponent 才能獲取到生成二維碼時傳入的 scene
    const scene = decodeURIComponent(query.scene)
  }
})

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM