在 Yii 2 中,当处理一个 RESTful API 请求时,支持新的响应格式:text/html,且仅支持 HTML 格式

1、在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 XML 格式,因为 RESTful APIs 同时支持JSON和XML格式。但不支持 HTML 格式。如图1

图1

2、在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 JSON 格式,如图2

图2

{
    "name": "Unprocessable entity",
    "message": "数据验证失败:第三方服务平台授权后重定向的回调链接不能为空",
    "code": 40004,
    "status": 422,
    "type": "yii\\web\\UnprocessableEntityHttpException"
}

3、现在需要增加对于 HTML 格式的支持,且仅支持 HTML 格式,因为是一个页面,而不是一个接口,最后还会跳转至对应的回调链接页面,编辑 \qq\rests\oauth2\AuthorizeAction.php,设置 format 属性,format 属性指定 data 中数据格式化后的样式

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
namespace qq\rests\oauth2;

use Yii;
use yii\base\Model;
use yii\web\Response;
use yii\base\DynamicModel;
use yii\web\ServerErrorHttpException;
use yii\web\UnprocessableEntityHttpException;

/**
 * 第三方服务平台授权(引导用户进入授权页面登录同意授权)
 *
 * 1、请求参数列表
 * (1)redirect_uri:必填,第三方服务平台授权后重定向的回调链接
 *
 * 2、输入数据验证规则
 * (1)必填:redirect_uri
 * (2)网址:redirect_uri
 *
 * 3、操作数据
 * (1)302 跳转至 https://auth.om.qq.com/omoauth2/authorize?response_type=code&client_id=626d0ce988bf5fddb3d9dd9ce627b2ba&state=STATE&redirect_uri=http%3A%2F%2Fapi.channel-pub-api-localhost.chinamcloud.com%2Fqq%2Fv1%2Foauth2%2Faccess-token%3Fgroup_id%3D015ce30b116ce86058fa6ab4fea4ac63%26redirect_uri%3Dhttp%3A%2F%2Fwww.zmt.com
 *
 * For more details and usage information on AuthorizeAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Wang <shuijingwanwq@163.com>
 * @since 1.0
 */class AuthorizeAction extends Action
{
    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */    public $scenario = Model::SCENARIO_DEFAULT;
    /**
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
     */    public $viewAction = 'view';

    /**
     * Authorizes a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
     * @throws ServerErrorHttpException if there is any error when creating the model
     */    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        $request = Yii::$app->request;
        $get = $request->get();
        $redirect_uri = $request->get('redirect_uri');

        Yii::$app->response->format = Response::FORMAT_HTML;

        // 临时验证
        $model = DynamicModel::validateData(compact('redirect_uri'), [
            [['redirect_uri'], 'required'],
            [['redirect_uri'], 'url'],
        ]);

        if ($model->hasErrors()) {
            foreach ($model->getFirstErrors() as $message) {
                $firstErrors = $message;
                break;
            }
            throw new UnprocessableEntityHttpException(Yii::t('error', Yii::t('error', Yii::t('error', '20004'), ['firstErrors' => $firstErrors])), 20004);
        }

        // 包含 host info 的整个 URL,编码 URL 字符串
        $redirectUri = urlencode($request->hostInfo . $request->baseUrl . '/v1/oauth2/access-token?group_id=' . Yii::$app->params['groupId'] . '&redirect_uri=' . $redirect_uri);

        /* 浏览器跳转:引导用户进入授权页面登录同意授权,获取 code */        Yii::$app->response->redirect(Yii::$app->params['qqAuth']['hostInfo'] . Yii::$app->params['qqAuth']['baseUrl'] . '/authorize?response_type=code&client_id=' . Yii::$app->params['qqAuth']['tpApp']['clientId'] . '&state=STATE&redirect_uri=' . $redirectUri);
    }
}

4、在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 HTML 格式,符合预期,如图3

图3

5、在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 HTML 格式,符合预期,如图4

图4

永夜