接入微信公眾號登入-二維碼圖片

MEILI發表於2021-07-09
     /**
     * 返回微信登入二維碼
     */
    public function wx_Qr_code_login(){
        //微信二維碼自定義引數,建議設定唯一值
        $scene_str = 'tx'.time();
        $res = loginBusiness::wx_Qr_code($scene_str);
        if ($res){
            return show('200','微信二維碼',$res);
        }
    }
     /**
     * 生成帶引數的二維碼
     */
    public static function wx_Qr_code($scene_str){
        //獲取access_token
        $access_token = login::get_access_token();
        //生成帶引數的二維碼
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
        $data = array(
            "expire_seconds" => 60, //二維碼的有效時間(60秒)
            "action_name" => "QR_STR_SCENE",
            "action_info" => array("scene" => array("scene_str" => $scene_str)),
        );
        $result = json_decode(login::httpRequest($url, json_encode($data)),true);
        $img = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=". $result['ticket'];//二維碼連結
        $result = [
            'img'=>$img,
            'ticket'=>$scene_str
        ];
        return $result;
    }
    //獲取access_token
    public static function get_access_token($token_file='./access_token'){
        //處理是否過期問題,將access_token儲存到檔案
        //也可寫入快取
        $life_time = 3600;
        if (file_exists($token_file) && time() - filemtime($token_file) < $life_time) {
            // 存在有效的access_token 直接返回檔案內容
            return file_get_contents($token_file);
        }
        $appid = config('wechat.appid');//appid
        $secret = config('wechat.secret');//AppSecret
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $access_token = json_decode(login::httpRequest($url),true);
        $access_token = $access_token['access_token'];
        //寫入到檔案
        file_put_contents($token_file, $access_token);
        return $access_token;
    }
/***
     * POST或GET請求
     * @url 請求url
     * @data POST資料
     * @return
     **/
    private static function httpRequest($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);
        if(!empty($data)){  //判斷是否為POST請求
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章