標籤:
應用時基於yii的。目前流程如下:
產生oschina授權連結
使用者訪問該連結之後得到 code
利用code換取access_token
代碼:
<?php/** * @author xialei <[email protected]> */class OschinaOauth extends CComponent{ public $ak; public $sk; public $callback; private $host = ‘https://www.oschina.net‘; public function init() { } /** * 擷取授權連結 * @return string */ public function getRedirectUrl() { $params = array( ‘response_type‘ => ‘code‘, ‘client_id‘ => $this->ak, ‘redirect_uri‘ => Yii::app()->createAbsoluteUrl($this->callback) ); return $this->host . ‘/action/oauth2/authorize?‘ . http_build_query($params); } /** * 擷取AccessToken * @param $code * @return string * @throws CException * @throws Exception */ public function getAccessToken($code) { $params = array( ‘client_id‘ => $this->ak, ‘client_secret‘ => $this->sk, ‘grant_type‘ => ‘authorization_code‘, ‘code‘ => $code, ‘dataType‘ => ‘json‘ ); $url = $this->host . ‘/action/openapi/token‘; $resp = Request::post($url, $params); $data = json_decode($resp,true); return $data; } public function refreshAccessToken() { }}
<?php/** * @author xialei <[email protected]> */class OauthController extends Controller{ public function actionCallback($code, $state) { $data = Yii::app()->oauth->getAccessToken($code); print_r($data); } public function actionRedirect() { $url = Yii::app()->oauth->getRedirectUrl(); $this->redirect($url); }}
目前的問題是可以得到 code,但是利用code去oschina擷取access_token的時候報錯了。
oschina openapi php 調用