接入微信公众号登录-二维码图片
/**
* 返回微信登录二维码
*/
public function wx_Qr_code_login(){
//微信二维码自定义参数,建议设置唯一值
$scene_str = 'tx'.time();
$res = loginBusiness::wx_Qr_code($scene_str);
if ($res){
return show('200','微信二维码',$res);
}
}
/**
* 生成带参数的二维码
*/
public static function wx_Qr_code($scene_str){
//获取access_token
$access_token = login::get_access_token();
//生成带参数的二维码
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
$data = array(
"expire_seconds" => 60, //二维码的有效时间(60秒)
"action_name" => "QR_STR_SCENE",
"action_info" => array("scene" => array("scene_str" => $scene_str)),
);
$result = json_decode(login::httpRequest($url, json_encode($data)),true);
$img = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=". $result['ticket'];//二维码链接
$result = [
'img'=>$img,
'ticket'=>$scene_str
];
return $result;
}
//获取access_token
public static function get_access_token($token_file='./access_token'){
//处理是否过期问题,将access_token存储到文件
//也可写入缓存
$life_time = 3600;
if (file_exists($token_file) && time() - filemtime($token_file) < $life_time) {
// 存在有效的access_token 直接返回文件内容
return file_get_contents($token_file);
}
$appid = config('wechat.appid');//appid
$secret = config('wechat.secret');//AppSecret
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$access_token = json_decode(login::httpRequest($url),true);
$access_token = $access_token['access_token'];
//写入到文件
file_put_contents($token_file, $access_token);
return $access_token;
}
/***
* POST或GET请求
* @url 请求url
* @data POST数据
* @return
**/
private static function httpRequest($url, $data = ""){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if(!empty($data)){ //判断是否为POST请求
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接