<?php
use app\shared\model\App;
use think\facade\Cache;
//二维码
function qrcodeUrl($acid=1,$wxappPath="pages/index/index",$dirname="platform_qr",$filename="1"){
	$acid=App::where(['id'=>$acid])->find();
	$param= [
        'path' => $wxappPath,
    ];
    return getQcode($acid,$param,$dirname,$filename);
}
//微信小程序获取二维码
function getQcode($acid=[],$param=[],$dirname='user',$filename=1){
    //保存到本地
    $saveRoot = public_path();
    $saveDir="qrcode/{$acid['id']}/{$dirname}/";
    if (!is_dir($saveRoot . $saveDir)) {
        @mkdir($saveRoot . $saveDir, 0755, true);
        file_put_contents($saveRoot . $saveDir . '.gitignore', "*\r\n!.gitignore");
    }
    $saveName = $filename.'_'.md5($filename).'.png';
    $base_file = request()->baseFile();
    $base_dir  = substr($base_file, 0, strripos($base_file, '/') + 1);

    if(Cache::get($dirname.$filename)){
     	 return request()->domain().$base_dir.$saveDir.$saveName.'?time='.time();
    }
    if(!($acid['wxapp_app_id']&&$acid['wxapp_app_id'])){
        return request()->domain().$base_dir.$saveDir.$saveName.'?time='.time();
    }
    $token=getToken($acid['wxapp_app_id'],$acid['wxapp_app_secret']);
    if(isset($param['path'])){
    	//$url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$token}";//方形
    	$url="https://api.weixin.qq.com/wxa/getwxacode?access_token={$token}";//方形
    }else{
    	$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";//圆形
    }
    $params = json_encode($param, JSON_UNESCAPED_UNICODE);
    $data=httpRequest($url,'POST',$params);
    file_put_contents($saveRoot.$saveDir.$saveName, $data);
    Cache::get($dirname.$filename,1,20);
    return request()->domain().$base_dir.$saveDir.$saveName.'?time='.time();
}
//获取令牌
function getToken($appid,$secret)
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $data=httpRequest($url);
    $data=json_decode($data);
    if(isset($data->access_token)){
        return ($data->access_token);
    }else{
        return '';//die(json_encode(['code'=>1,'data'=>'','msg'=>'access_token获取错误二维码']));
    }
}