public function actionToken() { $request = Yii::$app->getRequest(); $params = $request->get(); $params = array_map('htmlEntityString', $params); $appid = isset($params['app_id']) ? $params['app_id'] : ''; $appkey = isset($params['app_key']) ? $params['app_key'] : ''; if (!$appid) { return responseArray(1101, 'appid_params_missing', '缺失应用ID参数'); } if (!$appkey) { return responseArray(1102, 'appkey_params_missing', '缺失应用KEY参数'); } try { // 验证app_id app_key有效性 $application = new ApplicationBase(); $ret = $application->validateApp($appid, $appkey); if (!$ret) { return responseArray(2101, 'appid_appkey_invalid', '应用ID或者应用KEY无效'); } $accessToken = new AccessToken(); $tokenEntity = $accessToken->getAccessToken($appid, $appkey); $result = null; if ($tokenEntity == null || strtotime($tokenEntity->expires_in) < time()) { $token = generateRandString(); // 有效期默认两小时 $expires_in = date('Y-m-d H:i:s', time() + 7200); if ($tokenEntity == null) { $result = $accessToken->setAccessToken($token, $appid, $appkey, $expires_in); } else { $tokenEntity->access_token = $token; $tokenEntity->expires_in = $expires_in; $result = $tokenEntity->save(); } //TODO:: 保存access_token失败的处理 if (!$result) { return responseArray(1, 'network_anomaly', '网络异常请稍后重试'); } } else { $token = $tokenEntity->access_token; // 有效期默认两小时 $expires_in = $tokenEntity->expires_in; } $ret = ['access_token' => $token, 'expires' => $expires_in]; return responseArray(1, 'success', '授权成功', $ret); } catch (Exception $ex) { return responseArray(1, 'network_anomaly', '网络异常,请稍后重试'); } }