octobercms 插件学习 验证码

Laravel框架
418
0
0
2022-04-24

Pkurg.SiteCaptcha

基于 mews/captcha

细节

生成配置文件
% php artisan vendor:publish --provider='Mews\Captcha\CaptchaServiceProvider'
Copied File [/plugins/pkurg/sitecaptcha/vendor/mews/captcha/config/captcha.php] To [/config/captcha.php]
Publishing complete.
这里测试 用该命令能否直接将插件包里的配置发布出去,我的客户没权限修改这个配置

截图

效果

页面组件

用法说明

安装

插件市场安装

备用地址下载压缩包

php artisan plugin:refresh pkurg.sitecaptcha
前台页面使用

使用SiteCaptchaComponent组件,可设置验证码类型,是否显示刷新按钮,按钮的class

组件默认的是

<img src="{{ sitecaptcha.getImg() }}" alt="captcha" class="captcha-img" data-refresh-config="{{ sitecaptcha.property('type') }}">

{% if  sitecaptcha.property('showrefresh') == 'show'  %}
<a class="refresh-captcha" id="refreshcaptcha"><span class="{{ sitecaptcha.property('iconclass') }}"></span></a>
{% endif %}

这里修改为

<img id="refreshcaptcha" src="{{ sitecaptcha.getImg() }}" alt="captcha" class="captcha-img img-yzm pull-right" data-refresh-config="{{ sitecaptcha.property('type') }}">
js中是根据captcha-img类的data-refresh-config获取验证码类型的,根据id=”refreshcaptcha”获取刷新按钮的。修改后点击验证码刷新
后台验证
<?php namespace RainLab\User\Components;
.
use Captcha;
.
/**
 * Sign in the user
 */public function onSignin()
{
    $data = post();

    //验证码验证  
    if (!Captcha::check($data['captcha'])){
        throw new ApplicationException('验证码错误');
    }

}

也可以

<?php namespace RainLab\User\Components;
use Session;
/**
 * Sign in the user
 */public function onSignin()
{
    $data = post();
    $rules = [];
    $rules['captcha'] = 'required|captcha_api:'. Session::get('captcha.key');

    $validation = Validator::make($data, $rules);
    if ($validation->fails()) {
        throw new ValidationException($validation);
    }

}

知识点

记录用的的知识点或技巧,方便自己查找,参考,复制
在插件中注册providers 和 aliases
<?php namespace Pkurg\SiteCaptcha;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    public function boot(){

        \App::register('\Mews\Captcha\CaptchaServiceProvider');

        $alias = \Illuminate\Foundation\AliasLoader::getInstance()->alias('Captcha', 'Mews\Captcha\Facades\Captcha');        

    }

}
在路由中使用
<?php

Route::get('/get_captcha/{config?}', function (\Mews\Captcha\Captcha $captcha, $config = 'default') {
     return $captcha->src($config);
});