微信公眾號獲取二維碼
阿新 • • 發佈:2018-12-11
<?php /** * Created by PhpStorm. * User: zhoujianhui * Date: 2018/9/17 * Time: 下午4:30 */ //獲取token header('content-type:text/html;charset=utf-8'); include ("db.php"); //配置APPID、APPSECRET $APPID = $_POST['appid']; $APPSECRET = $_POST['appsecret']; $name = $_POST['name']; $uid = (int)$_COOKIE['id']; $picname = $APPID.$name; //獲取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_token1'] = ""; $_SESSION['expires_in1'] = 0; $ACCESS_TOKEN = ""; if(!isset($_SESSION['access_token1']) || (isset($_SESSION['expires_in1']) && time() > $_SESSION['expires_in1'])) { $json = httpRequest( $access_token ); $json = json_decode($json,true); $_SESSION['access_token1'] = $json['access_token']; $_SESSION['expires_in1'] = time()+7200; $ACCESS_TOKEN = $json["access_token"]; } else{ $ACCESS_TOKEN = $_SESSION["access_token1"]; } //構建請求二維碼引數 //path是掃描二維碼跳轉的小程式路徑,可以帶引數?id=xxx //width是二維碼寬度 $qcode ="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$ACCESS_TOKEN; $param = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}"; $result = httpRequest( $qcode, $param,"POST"); $result = json_decode($result,true); $ticket = $result['ticket']; $url1 = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket; $res = httpRequest($url1); //生成二維碼 file_put_contents("$picname.png", $res); $base64_image ="data:image/jpeg;base64,".base64_encode($res); $data1 = array('picname'=>$picname.".png"); //把請求傳送到微信伺服器換取二維碼 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; }
//注意公眾號需要後臺加入白名單