首页 / PHP / PHP获取小程序码并返回前端显示图片
PHP获取小程序码并返回前端显示图片
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP获取小程序码并返回前端显示图片,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2332字,纯文字阅读大概需要4分钟。
内容图文
小程序的二维码分为小程序码和二维码;
生成小程序二维码文档中说后端来生成。
参考 小程序开发文档资料:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html
文档的参数介绍还是蛮详细的,但是没有具体的demo,对于请求的接口的返回值是进制流(也就是在浏览器显示一堆乱码)也是很令人懊恼,这里贴一下我的代码:
//获取小程序码,这里调用的是小程序码的A接口类型
public function getQRCodeAction()
{
$data['scene'] = $this->_req->getQuery('shareId',11); //scence、page的使用要参考文档
$data['width'] = $this->_req->getQuery('width',220);
$data['auto_color'] = $this->_req->getQuery('auto_color');
$data['line_color'] = $this->_req->getQuery('line_color');
$data['is_hyaline'] = $this->_req->getQuery('is_hyaline',true);
$data['page'] = $this->_req->getQuery('page',""); //由这行以上代码是二维码的样式等由前端传值的形式,也可以直接在后端设置
$wxModel = new WxAuthModel();
$token = $wxModel->getAccessToken();
$res_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token"; //请求微信提供的接口
header('content-type:image/png');
$data = json_encode($data);
$Qr_code = $wxModel->http_request($res_url,$data); //到这里就已经返回微信提供的返回数据了,这个时候的数据是二进制流,要处理下再返回给前端
file_put_contents('/tmp/qr_code.png', $Qr_code); //将获得的数据读到一个临时文件里
$img_string = $this->fileToBase64('/tmp/qr_code.png'); //将图片文件转化为base64
response::result($img_string);
}
//本地文件转base64
private function fileToBase64($file){
$base64_file = '';
if(file_exists($file)){
$mime_type= mime_content_type($file);
$base64_data = base64_encode(file_get_contents($file));
$base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
}
return $base64_file;
}
/*获取access_token,不需要code参数,不能用于获取用户信息的token*/
public function getAccessToken()
{
$token_file = '/dev/shm/heka2_token.json'; //由于获取token的次数存在限制,所以将一段时间内的token缓存到一个文件(注意缓存路径服务器支持可写可读),过期后再重新获取
$data = json_decode(file_get_contents($token_file));
if ($data->expire_time < time()) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->http_request($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
file_put_contents($token_file, json_encode($data));
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
感觉一个完整的PHP实现的代码目前我还没找到,这个也还蛮常用的。如有不恰当的地方,欢迎指出~ ^_^
原文:https://www.cnblogs.com/xinxinmifan/p/wxCode.html
内容总结
以上是互联网集市为您收集整理的PHP获取小程序码并返回前端显示图片全部内容,希望文章能够帮你解决PHP获取小程序码并返回前端显示图片所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。