yii2配置api模块

1、在项目下添加目录weChatApi
2、在common/config/bootstrap.php文件添加一行代码:
Yii::setAlias( '@weChatApi' , dirname( dirname( __DIR__ ) ) . '/weChatApi' );
3、在weChatApi里面创建如下目录:
在这里插入图片描述
4、修改/etc/nginx/conf.d/default.conf添加如下代码:

    location /BlackCard/weChatApi/web/ {
        index  index.html index.htm index.php;
        try_files $uri $uri/ /BlackCard/weChatApi/web/index.php?$query_string;
    }

重启nginx服务:systemctl reload nginx
5、在weChatApi添加目录:runtime,命令如下:

mkdir runtime
chmod 777 runtime

6、各个文件的代码如下:
ApiController.php

<?php

namespace weChatApi\base\controllers;

use yii\filters\auth\HttpBasicAuth;
use yii\rest\ActiveController;
use Yii;

/**
 * restful api 底层控制器
 * Class ApiController
 * @package weChatApi\base\controllers
 */
class ApiController extends ActiveController
{

    /**
     * 操作成功标示码
     */
    const ACTION_SUCCESS_CODE = 1;

    /**
     * 操作失败标示码
     */
    const ACTION_FAIL_CODE = 0;

    /**
     * 开发的权限
     * @var array
     */
    private $allowedApis = [
        'user/login' ,
    ];

    /**
     * 关闭csrf验证
     * @var bool
     */
    public $enableCsrfValidation = false;

    /**
     * 验证授权
     *
     * @param array $optional
     *
     * @return array
     */
    public function behaviors( $optional = [] )
    {
        $behaviors = parent::behaviors();
        $behaviors[ 'authenticator' ] = [
            'class' => HttpBasicAuth::className() ,
        ];
        return $behaviors;
    }

    /**
     * 重写
     *
     * @param $action
     *
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction( $action )
    {
        if ( $this->isAllowedApi() ) {
            return true;
        }
        parent::beforeAction( $action );
        return true;
    }

    /**
     * 注销自带的 rest
     * @return array
     */
    public function actions()
    {
        $actions = parent::actions();
        unset(
            $actions[ 'index' ] ,
            $actions[ 'updat
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值