我这里是放在tp5中的common.php中作为一个工具方法使用
/**
* 生成带参数的二维码
*/
function showQrcode($courseId)
{
// $courseId = input('courseId');
if (!$courseId) {
return false;
}
$access_token = getAccessToken();
// 获取ticket
$getTicketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
// post方式发送的数据
// {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
$postData = array(
"action_name" => "QR_LIMIT_SCENE",
"action_info" => [
"scene" => [
"scene_id" => $courseId,
]
],
);
$ticketRes = httpRequest($getTicketUrl,json_encode($postData,true));
$ticketResArr = json_decode($ticketRes,true);
$ticket = urlencode($ticketResArr['ticket']);
// 通过ticket获取二维码
$getQrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
$res = httpRequest($getQrcodeUrl);
// 保存当前课程的微信带参数图片,返回字节数
$saveRes = file_put_contents("./upload/wxQrcode/".$courseId.".jpg", $res);
return $saveRes;
}
为curl发送封装的方法,第二个参数为空时为get方式,不为空时为post方式
function httpRequest($url, $postData=array()){
// (1)初始化
$ch = curl_init();
// (2)设置选项
// 设置请求的url
curl_setopt($ch, CURLOPT_URL, $url);
// 将curl_exec()获取的数据以字符串返回,而不是直接输出。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($postData)){
// 设置请求方式为post
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//curl注意事项,如果发送的请求是https,必须要禁止服务器端校检SSL证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// (3)执行
$result = curl_exec($ch);
// (4)关闭
curl_close($ch);
return $result;
}
这里是获取access_token的方法,可根据具体情况考虑是否将access_token保存
function getAccessToken(){
// 设置接口参数,这里填写将要设置的公众号的
$config = array(
'appid' => $this->appid,
'secret' => $this->secret,
);
$filename = './application/api/access_token_cache';
// 存在该文件且access_token未过期
if (is_file($filename) && filemtime($filename) + 7100 > time()) {
$data = file_get_contents($filename);
}else{
// 重新获取access_token
$api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&'.http_build_query($config);
// 发送接口请求,调用发送curl请求的函数(注意在面向对象环境下的引用方式)
$rs = httpRequest($api);
// 将获取的json字符串转成php数组
$result = json_decode($rs, true);
$data = $result['access_token'];
file_put_contents($filename, $data);
}
return $data;
}