LoginSignup
5
4

More than 5 years have passed since last update.

CakePHPでYConnect

Last updated at Posted at 2015-10-08

yahooショッピング関連でAPIを使用し管理をしたかったため、下記にその流れを記載していきます。

準備

アプリ登録

https://e.developer.yahoo.co.jp/shopping/register
API利用に必要なアプリケーションID、シークレットを取得。
アプリ登録後3~5営業日程でメールが届き、テスト環境のストアが利用できます。

アプリ詳細

アプリケーションの管理>アプリケーションの詳細にて、コールバックURLを設定する。
ここで設定したURLが、アクセストークン発行後に遷移するURLとなります。

ライブラリ導入

http://developer.yahoo.co.jp/yconnect/server_app/php/
今回はcakephp1.3に組み込むため、php版を採用しました。

STEP3: サンプルコードを確認して実装する>2. 認可コードを取得してトークンを発行 付近にあるダウンロードボタンをクリックして、cakeのvendors以下にDLしたYConnectを設置する。

実装

APIを使うには、下記のような流れになります。
1.認証コードを生成
2.認証コードを元にアクセストークン(有効期限は1時間)リフレッシュトークン(有効期限は4週間)を生成
3.アクセストークンを使用してAPIを実行

詳細はこちら↓
http://developer.yahoo.co.jp/yconnect/server_app/php/sample.html

認証コード、アクセストークン生成

controller.php
<?php
function createToken() {
    if (isset($this->params['url']['code']) && isset($this->params['url']['state'])) {
        if (!$this->Model->getToken()) {
            echo "トークンの生成に失敗しました。";
            return false;
        }
    }
}
model.php
<?php
require_once(VENDORS . "YConnect/YConnectClient.php");
require_once(VENDORS . "YConnect/Credential/ClientCredential.php");
require_once(VENDORS . "YConnect/Credential/BearerToken.php");
require_once(VENDORS . "YConnect/Credential/RefreshToken.php");
require_once(VENDORS . "YConnect/Endpoint/ApiClient.php");
require_once(VENDORS . "YConnect/Endpoint/TokenClient.php");
require_once(VENDORS . "YConnect/Endpoint/AuthorizationCodeClient.php");
require_once(VENDORS . "YConnect/Exception/TokenException.php");
require_once(VENDORS . "YConnect/Constant/GrantType.php");
require_once(VENDORS . "YConnect/Util/HttpClient.php");
require_once(VENDORS . "YConnect/Util/Logger.php");


class Model extends AppModel{
    var $useTable     = false;
    var $clientId     = ""; // アプリケーションID
    var $clientSecret = ""; // シークレット
    var $redirectUri  = ""; // アプリ詳細で設定したURI
    var $state        = ""; // CSRF対策用文字列
    var $client       = "";

    function __construct() {
        parent::__construct();
        if (empty($this->client)) {
            $cred = new YConnect\Credential\ClientCredential($this->clientId, $this->clientSecret);
            $this->client = new YConnect\YConnectClient($cred);
        }
    }

    function getToken() {
        try {
            $codeResult = $this->client->getAuthorizationCode($this->state);
            $this->client->requestAccessToken($this->redirectUri, $codeResult);
            $this->__writeToken($this->client->getAccessToken(), $this->client->getRefreshToken());
        } catch (Exception $e) {
            return false;
        }
        return true;
    }

    function updToken() {
        $this->client->refreshAccessToken(Cache::read('RefreshToken'));
        $this->__writeToken($this->client->getAccessToken());
    }

    function runApi($url, $data = array()) {
        if (!$this->__checkToken()) {
            return false;
        }
        try {
            $header = array(
                'Authorization: Bearer '. Cache::read('AccessToken'),
                'Content-Type: application/xml; charset=UTF-8'
            );
            $ch = curl_init($url);

            curl_setopt($ch, CURLOPT_USERPWD, $this->clientId . ":" . $this->clientSecret);
            //curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            if (empty($data)) {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            } else {
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

            $xml = new Xml(curl_exec($ch));
            return $xml->toArray();
        } catch ( ApiException $e ) {
            return false;
        }
    }

    private function __writeToken($AccessToken, $RefreshToken = false) {
        Cache::set(array('duration' => '+3600 seconds'));
        Cache::write('AccessToken', $AccessToken);
        if ($RefreshToken) {
            Cache::set(array('duration' => '+4 week'));
            Cache::write('RefreshToken', $RefreshToken);
        }
    }

    private function __checkToken() {
        if (!Cache::read('AccessToken')) {
            if (Cache::read('RefreshToken')) {
                $this->updToken();
            } else {
                echo "トークンの有効期限が切れました。";
                return false;
            }
        }
        return true;
    }
}

下記URLを叩いて、アクセスキー、リフレッシュキーが取得できれば成功!
https://auth.login.yahoo.co.jp/yconnect/v1/authorization?response_type=code&client_id=[アプリケーションID]&redirect_uri=[アプリ詳細で設定したURI]&state=[CSRF対策用文字列]

以上です。
随時更新していきます。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4