通过php后台接口获取微信小程序任意页面的二维码,记录其中遇到的三个问题以及解决办法。
先上代码:
<?php
error_reporting(0);
$gettokenurl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
$tokentata = array('appid'=>'你的小程序AppID','secret'=>'你的小程序AppSecret');
$tokencontext = get_content_post($gettokenurl,$tokentata);
$tokenjson = json_decode($tokencontext,1);
if(!empty($tokenjson['errcode'])){
exit('小程序AppID和AppSecret不匹配!');
}
$token = $tokenjson['access_token'];
//接口A小程序码
$url = 'http://api.weixin.qq.com/wxa/getwxacode?access_token='.$token;
//接口C小程序二维码
//$url = 'http://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$token;
$data = array(
'path'=>'pages/member/index/index',
'width'=>intval(430)
);
$data=json_encode($data);
$file = './'.time().'.jpg';
file_put_contents($file,get_content_post($url,$data));
echo '<img src="'.$file.'">';
/**
* 通过post方法获取网页源码
* @param string $url 请求的链接
* @param array $post_data post提交的数据
* @param array $header 模拟请求头
* @return string 网页源码
*/
function get_content_post($url,$post_data=array(),$header=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_AUTOREFERER,true);
$content = curl_exec($ch);
$info = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($code == "200"){
return $content;
}else{
return "错误码:".$code;
}
}
?>记录下遇到的坑:
1、所有请求都是https的,在curl下加上如下代码,跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
2、获取小程序码A接口时,四个参数都传的话,一直报数据格式错误,把最后两个去掉就可以获取到
3、从腾讯服务器获取到的是图片流,要保存到本地才能显示