【问题标题】:two function with one variable in controller of laravel5.4laravel5.4控制器中的两个函数,一个变量
【发布时间】:2017-05-26 07:19:05
【问题描述】:

我使用 api Instagram 并在 indexx 函数中使用 access_token 变量,它是服务器发送的 json 结果,现在我正在尝试在图片函数中使用此变量并使用 Guzzle 向服务器发送 HTTP 我能做什么? 我的控制器有这个代码:

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');
}

【问题讨论】:

  • 从索引函数返回代码并访问索引函数 insdie 图片视图
  • @Exprator 你能解释更多吗?
  • 在索引函数的末尾返回 $code;并在图片视图中调用函数 index() 然后你会得到代码
  • 在任何函数开始之前定义一个名为 access_token (private access_token) 的私有变量,然后您可以使用 $this->access_token 访问该变量(分配给它或任何东西);

标签: php laravel instagram-api guzzle


【解决方案1】:

另一种方法是写入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);
}

【讨论】:

  • 我给这个错误Client error: GET api.instagram.com/v1/users/self/media/recent/…` 导致400 Bad Request 响应:{"meta": {"code": 400, "error_type": "OAuthAccessTokenException", "error_message ": "提供的 access_token 无效(被截断...)`
  • dd($access_token)picture() 中的输出是什么?你没有得到更新的访问令牌吗?
  • 是的,我确定我更新了 access_token,当回显 access_token 时,我给出了备用令牌
  • 访问令牌只会在indexx 方法中设置,如果不调用该方法,access_token 将不会设置并回退到fallback token
  • 我用session保存access_token
猜你喜欢
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 2020-11-23
相关资源
最近更新 更多