public function getcode(){
//微信小程序楚传递的参数值
$user_id=$_REQUEST['user_id'];
$APPID=$_REQUEST['appId'];
$AppSecret=$_REQUEST['appSecret'];
$qrpath='qrcode'; //路径在public文件夹里面
if(!is_dir('.'.$qrpath)){ // /public/qrcode/
mkdir(iconv("GBK","UTF-8",'.'.$qrpath),0777,true);
}
$file = $qrpath.'/'.$user_id;
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$fileUrl = $protocol.$_SERVER['HTTP_HOST'].$file; // http://XXXX/
$savePath = '.'.$file; // /public/qrcode/
if(file_exists($savePath)){
//当前时间-文件创建时间<过期时间
if( (time()-filemtime($savePath)) < $expires_in ) return array('status'=>1,'info'=>$fileUrl);
}
//获取access_token
$access = json_decode($this->get_access_token($APPID,$AppSecret),true);
$access_token= $access['access_token'];
$url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
//传递参数,用$user_id区分每个用户生成的二维码
$data=[
'scene'=>$user_id,
'width'=>430,
'auto_color'=>false,
];
$listdata=json_encode($data);
$result=$this->api_notice_increment($url,$listdata);
if (!$result) {
return false;
}
//查询是否存在二维码
$list=UserModel::where('id', $user_id)->field('qrcode')->find();
if(empty($list['qrcode'])){
$res = file_put_contents("qrcode/".$user_id.".jpg", $result);
// 将获取到的二维码图片流保存成图片文件
if($res===false) return json_encode(array('status'=>0,'info'=>'生成二维码失败','res'=>$res));
$filename="qrcode/".$user_id.".jpg";//用id编号当二维码名称
$datafile=['qrcode'=>$filename];
$info=UserModel::where('id', $user_id)->update($datafile);
$listi=UserModel::where('id', $user_id)->field('qrcode')->find();
return json_encode(array('status'=>1,'msg'=>'success','list'=>$listi['qrcode']));
}else{
return json_encode(array('status'=>1,'msg'=>'success','list'=>$list['qrcode']));
}
}
public function api_notice_increment($url, $data){
$curl = curl_init();
$ch = curl_init();
$header = "Accept-Charset: utf-8";
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($curl, 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);
if (curl_errno($ch)) {
return false;
}else{
return $tmpInfo;
}
}
public function get_access_token($APPID,$AppSecret){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$AppSecret;
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);
return $data;
}