没有不值得去解决的问题,也没有不值得去学习的技术!

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

在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 HTML 格式,符合预期
1、在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 XML 格式,因为 RESTful APIs 同时支持JSON和XML格式。但不支持 HTML 格式。如图1
在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 XML 格式,因为 RESTful APIs 同时支持JSON和XML格式。但不支持 HTML 格式
图1
2、在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 JSON 格式,如图2
在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 JSON 格式
图2


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


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

<?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);
    }
}


</pre>
4、在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 HTML 格式,符合预期,如图3
在浏览器打开网址:http://api.channel-pub-api.localhost/qq/v1/oauth2/authorize?group_id=015ce30b116ce86058fa6ab4fea4ac63 ,响应 HTML 格式,符合预期
图3
5、在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 HTML 格式,符合预期,如图4
在 Postman 中打开,Accept 的值为:application/json; version=0.0,响应 HTML 格式,符合预期
图4

PHP / Laravel / Yii2 老项目维护与长期技术支持

如果你的 PHP / Laravel / Yii2 项目已经上线,但遇到原开发离职、Bug 长期无人修复、接口不稳定、性能下降、代码难以接手等问题,可以联系我做一次远程技术排查。

适合以下情况:
✅ 老旧 PHP 系统无人维护
✅ Laravel / Yii2 项目 Bug 修复
✅ 后台管理系统小功能迭代
✅ RESTful API 接口排查
✅ MySQL / Redis / Nginx 性能问题
✅ 长期远程兼职维护

可先从一次小问题开始:
✅ 线上报错排查
✅ 接口异常分析
✅ 慢查询与性能瓶颈定位
✅ 代码结构初步评估
✅ 部署环境与日志检查

如需咨询,请联系我,并注明:PHP 维护咨询

联系方式:
Telegram:@shuijingwan
微信:13980074657
邮箱:shuijingwanwq@gmail.com

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理