微信小程序接口B二维码接口调用保存到本地
微信小程序生成二维码共有三个接口(详情见官方文档),由于业务量的需要,B接口运用较多,这里主要记录B接口的调用。
微信官方文档。 —— [ 微信小程序二维码获取文档 ]
第一步:获得access_token
微信官方文档。 —— [ 获取access_token ]
第二步:生成二维码
后台完整代码
//获取access_token
public function get_access_token(){
$appid = '';//配置appid
$secret = '';//配置secret
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
return $this->curl_get($url);
}
//开启curl get请求
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;
}
//获得二维码
public function create_qrcode(){
$qr_path = "./Uploads/";
if(!file_exists($qr_path.'user/')){
mkdir($qr_path.'user/', 0700,true);//判断保存目录是否存在,不存在自动生成文件目录
}
$filename = 'user/'.time().'.png';
$file = $qr_path.$filename;
$access = json_decode($this->get_access_token(),true);
$access_token= $access['access_token'];
$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
$qrcode = array(
'scene' => 'id='.$qrcode_id,//二维码所带参数
'width' => 200,
'page' => '',//二维码跳转路径(要已发布小程序)
'auto_color' => true
);
$result = $this->sendCmd($url,json_encode($qrcode));//请求微信接口
$errcode = json_decode($result,true)['errcode'];
$errmsg = json_decode($result,true)['errmsg'];
if($errcode) {
$this->render(0,$errmsg);
}
$res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件
if($res===false){
$this->render(0,'生成二维码失败');
}else{
$this->return['data'] = $this->config->item('base_url').'/Uploads/'.$filename;//返回图片地址链接给前端
}
}
//开启curl post请求
function sendCmd($url,$data)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
}
##附:微信小程序js文件中查看scene所带的参数
Page({
onLoad: function(options) {
// options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
var scene = decodeURIComponent(options.scene)
consol.log(scene)
}
})