public function getCode() { $access_token = $this->getAccessToken(); $width = 430; //二维码宽度 $page = 'pages/index/index';//小程序路径(pages/index/index) $scene = '?type=1&user_id='.$this->auth->id; //携带的参数(?id=1&tag=2) $wx_api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token; $data = [ 'page' => $page, 'scene' => $scene, 'width' => $width, ]; $post_data = json_encode($data); $result = $this->getCurlQRcode($wx_api, $post_data); //获取微信小程序二维码 print_r($result);exit; $filename = md5($this->auth->id); $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/' . date('Ymd') . '/'; if (!is_dir($qrcodePath)) { @mkdir($qrcodePath); } file_put_contents('./uploads/qrcode/'.date('Ymd')."/".$filename.'.png', $result, true); $path ='/uploads/qrcode/'.date('Ymd')."/".$filename.'.png'; return $path; } function getCurlQRcode($url, $data) { $ch = curl_init(); $header = array("Accept-Charset: utf-8"); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { return false; }else{ return $tmpInfo; } } /** * @return mixed|void * @ 获取token */ public function getAccessToken() { $appid = config('site.app_id'); $app_secret = config('site.app_secret'); $url = "https://api.weixin.qq.com/cgi-bin/stable_token"; $data = [ 'grant_type' => 'client_credential', 'appid' => $appid, 'secret' => $app_secret, ]; $result = $this->httpPost($url, $data); if (isset($result['access_token']) && !empty($result['access_token'])) { return $result['access_token']; } else { $this->error('微信授权失败,错误码:'.$result['errmsg']); } } /** * 以post方式发起请求 * @param $url * @param $data * @return bool|mixed */ function httpPost($url, $data) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE)); list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl)); return (intval($status["http_code"]) === 200) ? json_decode($content, true) : false; }
标签:ch,setopt,程序,token,生成,二维码,curl,data,CURLOPT From: https://www.cnblogs.com/ixiangang06/p/18137505