1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php namespace Msg\Lib\Type;
- use Dever;
- class Code
- {
- private $config;
- # 发送验证码
- public function send($template, $account, $param = array())
- {
- $this->config = Dever::db('template_code', 'msg')->find(array('template_id' => $template['id']));
- if (!$this->config) {
- Dever::error('验证码未配置');
- }
- $data['template_id'] = $template['id'];
- $data['day'] = date('Ymd', DEVER_TIME);
- $code = $this->createCode();
- if ($template['content']) {
- $template['content'] = \Dever\Helper\Str::val($template['content'], $param);
- }
- foreach ($template['method'] as $k => $v) {
- $handle = Dever::load('method/' . $v, 'msg');
- $data['account'] = $handle->init($template['id'], $account);
- $this->valid($data);
- if ($template['status'] == 1) {
- $data['record'] = $handle->send($template['content'], array('code' => $code));
- }
- $data['code'] = $code;
- $data['status'] = 1;
- Dever::db('code', 'msg')->insert($data);
- }
- $msg = '验证码发送成功';
- if ($template['status'] == 2) {
- $msg .= '::' . $code;
- }
- return $msg;
- }
- # 检测并使用验证码
- public function check($template_id, $account, $code, $update = 1)
- {
- $info = Dever::db('code', 'msg')->find(array('template_id' => $template_id, 'account' => $account));
- if ($info && $info['status'] == 1 && $code == $info['code']) {
- if ($update == 1) {
- Dever::db('code', 'msg')->update($info['id'], array('status' => 2));
- }
- return true;
- }
- return false;
- }
- private function createCode()
- {
- $len = $this->config['length'] ? $this->config['length'] : 4;
- $type = $this->config['type'] ? $this->config['type'] : 1;
- return \Dever\Helper\Str::rand($len, $type - 1);
- }
- protected function valid($where)
- {
- $info = Dever::db('code', 'msg')->find($where);
- if ($info) {
- if (DEVER_TIME - $this->config['cdate'] < $this->config['interval']) {
- Dever::error('请不要在'.$this->config['interval'].'秒之内申请多次验证码,请您稍后再试');
- } elseif (Dever::db('code', 'msg')->count($where) >= $this->config['total']) {
- Dever::alert('很抱歉,您已经申请获取验证码超过' . $this->config['total'] . '次,今天您已经无法获取验证码了,请您明天再来');
- }
- }
- }
- }
|