使用Laravel Passport消耗API

时间:2017-10-30 14:04:45

标签: php laravel laravel-passport

我不明白如何发送令牌:

$response = $client->request('GET', '/api/user', [
'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
],

]);

如果我有HTML表单,我该如何发送令牌来使用API​​?

由于

2 个答案:

答案 0 :(得分:0)

如果您想在PHP中向外部应用API发送请求,可以使用例如 Guzzle HTTP Client https://github.com/guzzle/guzzle

答案 1 :(得分:0)

您需要首先在API中进行身份验证以获取令牌,然后使用该令牌发送任何其他请求。

Curl的例子:

首先进行身份验证:

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "http://laravel-app-with-passport.com/oauth/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "grant_type=password&client_id=".$outhCliendIdGeneratedInLaravelPassport ."&client_secret=".$OuthClientSecretGenerateInLaravelPassport ."&username=". $validLaravelUserName . "&password=" . $validLaravelUserPassword,
        CURLOPT_HTTPHEADER => array(
            "accept: application/json",
            "content-type: application/x-www-form-urlencoded",
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    $responseInfo = curl_getinfo($curl);

    curl_close($curl);

    if ($err) {
        set_error_handler($err);
    } else {

        if ($responseInfo['http_code'] == 200) {

            $_SESSION['TOKEN'] = json_decode($response)->access_token;
            $_SESSION['TOKE_TYPE'] = json_decode($response)->token_type;

        } else {

            set_error_handler("Login to api faild status 403");
            error_log("No login api status 403");

        }
    }

然后,你可以发送令牌并使用api中的任何网址:

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "http://laravel-app-with-passport.com/api/someurl",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_POSTFIELDS => null, // here you can send parameters
        CURLOPT_HTTPHEADER => array(
            "accept: application/json",
            "authorization: " . $_SESSION['TOKE_TYPE'] . " " . $_SESSION['TOKEN'] . "",
            "cache-control: no-cache",
            "content-type: application/json",
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    var_dump($response);

此外,如前所述,您可以使用Guzzle HTTP Client(https://github.com/guzzle/guzzle)来代替curl而不是