1. 程式人生 > >微信獲取小程式的二維碼

微信獲取小程式的二維碼

<?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'];
$page = $_POST['page'];
$size = $_POST['size'];
$color = json_decode($_POST['color']);
$uid = (int)$_COOKIE['id'];
if($_POST['checkbox1']=="true"){
    $checkbox1 = true;
}else{
    $checkbox1 = false;
}
if($_POST['checkbox2']=="true"){
    $is_hyaline = true;
}else{
    $is_hyaline = false;
}
$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['access_token'.$APPID] = "";
$_SESSION['expires_in'.$APPID] = 0;

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

    $json = 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/wxa/getwxacode?access_token=".$ACCESS_TOKEN;
$param = json_encode(array("path"=>$page,"width"=> $size,"auto_color"=>$checkbox1,"line_color"=>$color,"is_hyaline"=>$is_hyaline));

//POST引數
$result = httpRequest( $qcode, $param,"POST");
//生成二維碼
file_put_contents("$picname.png", $result);
$base64_image ="data:image/jpeg;base64,".base64_encode( $result );
$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;
}