应用时基于yii的。目前流程如下:
生成oschina授权链接
用户访问该链接之后得到 code
-
利用code换取access_token
代码:
<?php /** * @author xialei <xialeistudio@gmail.com> */ 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 <xialeistudio@gmail.com> */ 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的时候报错了。