<?php
class GetWxQrHandler {
  private $appid;
  private $secret;
  private $id;
  private $page;
  
  public function __construct($id = 0, $page = null)
  {
    $this->appid = "wxeef50c5d0ef117d1";
    $this->secret = "48dd0dfd509d1438aa4950d7dcdbee9e";
    $this->id = $id;
    $this->page = $page;
  }
  
  //获取access_token
  public function get_access_token()
  {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
    return $data = $this->curl_get($url);
  }
  
  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);
    error_log($data);
    return $data;
  }
  
  //获得二维码
  public function get_qrcode() {
    //header('content-type:image/gif');
    //header('content-type:image/png');格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
    //header('content-type:image/jpg');
    $id = $this->id;
    $data = array();
    $data['scene'] = "qrId=".$id;
    $data['page'] = $this->page;  //参数跳转到product/show，产品详情
    $data['width'] = 430;
    $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);
    return $da;
  }
  public function get_http_array($url,$post_data) {
    error_log("url--->" . $url);
    $httpInfo = array();
    $ch = curl_init();
    
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt( $ch , CURLOPT_POST , 1 );
    curl_setopt( $ch , CURLOPT_POSTFIELDS , $post_data);
    curl_setopt( $ch , CURLOPT_URL , $url );
    $response = curl_exec( $ch );
    if ($response === FALSE) {
      return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
  }
}