简体   繁体   English

laravel5.4控制器中具有一个变量的两个函数

[英]two function with one variable in controller of laravel5.4

I work with api Instagram and I'm using access_token variable in indexx function that it is json result that server send,Now I'm Trying to use this variable in picture function and send HTTP to server with Guzzle what Can I do? 我使用api Instagram,并且在indexx函数中使用access_token变量,它是服务器发送的json结果,现在我正在尝试在图片函数中使用此变量,并使用Guzzle将HTTP发送到服务器,我该怎么办? my controller has this Code: 我的控制器具有以下代码:

public function indexx(Request $request)
{
    $code = $this->code = $request->get('code');

    try {
        $client = new Client();
        $res = $client->request  ('POST', 'https://api.instagram.com/oauth/access_token', [
            'form_params' => [
                'client_id' => 'client_id' ,
                'client_secret' =>  'client_secret',
                'grant_type' => 'authorization_code',
                'redirect_uri' => 'http://hanie-asemi.ir/laravel/instagram/test',
                'code' => $code
            ]
        ]);
        $status = $res->getStatusCode();
        if ($status == 200) {
            $body = $res->getBody();
            $obj = \GuzzleHttp\json_decode($body);

            $access_token=$obj->access_token;
            echo view('json')->with($access_token);

        } else {
            echo "status is not 200";
        }

    } catch (BadResponseException $e) {
        echo "error1";
    }

}

public function picture()
{
    $client = new Client();
    $res2 = $client->request  ('GET', 'https://api.instagram.com/v1/users/self/media/recent/?access_token=Access_token');
}

Another way would be to writing to the config and reading from it 另一种方法是写入config并从中读取

public function indexx(Request $request)
{
    ...
    $access_token = $obj->access_token;
    config(['app.access_token' => $access_token]);
    ...
}

public function picture()
{
    $client = new Client();
    $access_token = config('app.access_token', 'fallback token');
    $res2 = $client->request('GET', 'https://api.instagram.com/v1/users/self/media/recent/?access_token='.$access_token);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM