RakutenRws_Client::fetchAccessTokenFromCode PHP Method

fetchAccessTokenFromCode() public method

Fetches OAuth2 AccessToken from Code
public fetchAccessTokenFromCode ( string $code = null ) : string
$code string The Code
return string The Access Token, If response is invalid return null
    public function fetchAccessTokenFromCode($code = null)
    {
        if ($code === null) {
            if (!isset($_GET['code'])) {
                throw new LogicException("A parameter code is not set.");
            }
            $code = $_GET['code'];
        }
        $url = $this->getAccessTokenUrl();
        $parameter = array('grant_type' => 'authorization_code', 'client_id' => $this->developerId, 'client_secret' => $this->secret, 'code' => $code, 'redirect_uri' => $this->redirectUrl);
        $response = $this->httpClient->post($url, $parameter);
        if ($response->getCode() == 200) {
            $this->accessTokenInfo = json_decode($response->getContents(), true);
            if (isset($this->accessTokenInfo['access_token'])) {
                $this->accessToken = $this->accessTokenInfo['access_token'];
                return $this->accessToken;
            }
        }
        return null;
    }

Usage Example

Example #1
0
if ($scheme == 'http' && $port == ':80' || $scheme == 'https' && $port == ':443') {
    $port = '';
}
$url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $port . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
// Clientインスタンスを生成
$rwsclient = new RakutenRws_Client();
// アプリIDをセット
$rwsclient->setApplicationId(RAKUTEN_APP_ID);
// Secretをセット
$rwsclient->setSecret(RAKUTEN_APP_SECRET);
// アフィリエイトIDをセット (任意)
$rwsclient->setAffiliateId(RAKUTEN_APP_AFFILITE_ID);
// 認証時リダイレクトURLをセット
$rwsclient->setRedirectUrl($url);
// リクエストに 'code' があった場合、アクセストークンを取得し
// API を実行します。
// If a request has 'code', get access_token and execute API
if ($_GET['code']) {
    // アクセストークンを取得します。
    if ($rwsclient->fetchAccessTokenFromCode()) {
        // Bookmark追加APIを実行します (http://webservice.rakuten.co.jp/api/favoritebookmarkadd/)
        $response = $rwsclient->execute('FavoriteBookmarkAdd', array('itemCode' => $_GET['itemCode']));
    }
    // 検索画面へ戻ります
    header('Location: index.php?keyword=' . urlencode($keyword) . '&page=' . urlencode($page) . '&m=1');
    exit;
}
// パラメーターに 'code' がない場合は、rakuten_favoritebookmark_update scope の
// 承認画面へ遷移します
header('Location: ' . $rwsclient->getAuthorizeUrl('rakuten_favoritebookmark_update'));
exit;