//获取access_token
public function get_access_token(){
$appid = config('ttappid');//配置appid
// dump($appid);die();
$secret = config('ttappsecret');//配置secret
$url = "https://developer.toutiao.com/api/apps/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
return json_encode(http_curl($url));
}
//获得二维码
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://developer.toutiao.com/api/apps/qrcode';
$openid=Session::get('appid');
$qrcode = array(
"access_token"=> $access_token,
// 'scene' => $code['openid'],//二维码所带参数
'appname' => 'douyin',
// 'width' => '430',
// 'path' => urlencode("pages/index/index?openid=".$openid),//二维码跳转路径(要已发布小程序)
// 'platform' => 'miniapp',
// "set_icon" => true
);
$result = https_post($url,json_encode($qrcode));//请求接口
// dump($result);die;
$errcode = json_decode($result,true)['errcode'];
$errmsg = json_decode($result,true)['errmsg'];
if($errcode) {
$this->render(0,$errmsg);
}
$is_qecode=Db::name('user')->where('openid',$openid)->field('userqrcode')->find();
// dump($is_qecode);
if(!$is_qecode['userqrcode']){
$res = file_put_contents($file,$result);//将返回的图片数据流写入文件,并且保存起来
// $base64_image_content=$qrcode;
$userQrcode='/Uploads/'.$filename;
Db::name('user')->where('openid',$openid)->update(['userqrcode' => $userQrcode]);
}
}
一定要post请求不然啥都没得,下面封装了一个,可以参考
//通过CURL,发送http的post请求
function https_post($url,$data){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
// dump($curl);
$result = curl_exec($curl);
if(curl_errno($curl)) {
return 'Errno'.curl_errno($curl);
}
curl_close($curl);
return $result;
}