1.参数配置等方面参考以下微信小程序官方文档
2.需要用到的一些方法
二进制转图片image/png 方法
//二进制转图片image/png
public function data_uri($contents, $mime)
{
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
curl POST请求 方法
public function curl_post_https($url,$data,$header=[]){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
3.php业务代码分两步几步
3.1 前端调用以下方法
//获取推广码
public function getPromotionCode(){
$data = $_POST;
$info = M('user')->where(['token'=>$data['token']])->find();
if($info){
if(empty($info['promotion_code'])){
$randChar = encrypt(2);
$promotion_code = $randChar . time();
if(M('user')->where(['token'=>$data['token']])->save(['promotion_code'=>$promotion_code])){
$wx = $this->qrcode($promotion_code);
$this->json(200, '请求成功,您的推广码已生成。',$wx);
}else{
$this->json(201, '生成错误,请重试。');
}
}else{
$wx = $this->qrcode($info['promotion_code']);
$this->json(200, '请求成功。',$wx);
}
}else{
$this->json(201, 'token已过期。');
}
}
3.2 post请求微信方法生成二维码图片,将二维码图片转换成base64返回给前端
//post调用微信方法生成二维码
public function qrcode($promotion_code){
$access_token=$this->getAccessToken();
$url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
$scene = 'promotion_code='.$promotion_code;
//拼接请求参数
$data=[
'scene'=>$scene,
'page'=>"pages/index/index",
];
//参数转为json类型
$data=json_encode($data);
//开始请求拿到二维码
$result = $this->curl_post_https($url,$data);
//
// $res=$this->isJson($result);
// if($res){
// dump($res);die;
// $res=json_decode($res);
// $this -> json(201,"二维码失败出现失误!".$res->errmsg);
// }
//调用方法,将二维码转为base64返回给前端
$result=$this->data_uri($result,'image/png');
return $result;
}