php 抓取网页生成图片(小程序码和二维码;生成后端来生成)

优采云 发布时间: 2021-10-14 04:22

  php 抓取网页生成图片(小程序码和二维码;生成后端来生成)

  小程序二维码分为小程序码和二维码;

  小程序生成的二维码在文档中由后端生成。

  参考小程序开发文档:

  文档的参数介绍比较详细,但是没有具体的demo。也很烦人,请求接口的返回值是十六进制流(即浏览器显示一堆乱码)。这是我的代码:

   //获取小程序码,这里调用的是小程序码的A接口类型

public function getQRCodeAction()

{

$data['scene'] = $this->_req->getQuery('shareId',11); //scence、page的使用要参考文档(比如:scene的值不能超过32个字符等)

$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); //如果这里明确是图片的话我建议获取图片类型这句可以省略,直接知道了mine_type='image/png',因为我这里我虽然存的图片,但是读到的mine_type值为text/plain

$base64_data = base64_encode(file_get_contents($file));

$base64_file = 'data:'.$mime_type.';base64,'.$base64_data; //$base64_file = 'data:image/png;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实现代码,这个自己用就好了。如有不妥之处请指出~_

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线