Code.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php namespace Msg\Lib\Type;
  2. use Dever;
  3. class Code
  4. {
  5. private $config;
  6. # 发送验证码
  7. public function send($template, $account = [], $param = [], $project = 'api')
  8. {
  9. $data['template_id'] = $template['id'];
  10. $data['day'] = date('Ymd', DEVER_TIME);
  11. if (empty($param['code'])) {
  12. $this->config = Dever::db('template_code', 'msg')->find(['template_id' => $template['id']]);
  13. if (!$this->config) {
  14. Dever::error('验证码未配置');
  15. }
  16. $param['code'] = $this->createCode();
  17. }
  18. if ($template['content']) {
  19. $template['content'] = \Dever\Helper\Str::val($template['content'], $param);
  20. }
  21. $test = 1;
  22. foreach ($template['method'] as $k => $v) {
  23. $config = Dever::db('account', 'msg')->find(['method' => $v]);
  24. if ($config) {
  25. $handle = Dever::load('method/' . $config['method'], 'msg');
  26. $data['account'] = $handle->init($template['id'], $config['id'], $account, $project);
  27. $this->valid($data);
  28. if ($config['test'] == 2) {
  29. $test = 2;
  30. $api = Dever::load('account', 'api')->get($config['api_account_id'], $project);
  31. $data['record'] = $handle->send($api, $template['content'], $param);
  32. }
  33. $data['code'] = $param['code'];
  34. $data['status'] = 1;
  35. Dever::db('code', 'msg')->insert($data);
  36. # 这里以后加入计费机制
  37. }
  38. }
  39. $msg = '验证码发送成功';
  40. if ($test == 1) {
  41. $msg .= '::' . $param['code'];
  42. }
  43. return $msg;
  44. }
  45. # 检测并使用验证码
  46. public function check($template_id, $account, $code, $update = 1)
  47. {
  48. $info = Dever::db('code', 'msg')->find(['template_id' => $template_id, 'account' => $account], ['order' => 'cdate desc']);
  49. if ($info && $info['status'] == 1 && $code == $info['code']) {
  50. if ($update == 1) {
  51. Dever::db('code', 'msg')->update($info['id'], ['status' => 2]);
  52. }
  53. return true;
  54. }
  55. return false;
  56. }
  57. private function createCode()
  58. {
  59. $len = $this->config['length'] ? $this->config['length'] : 4;
  60. $type = $this->config['type'] ? $this->config['type'] : 1;
  61. return \Dever\Helper\Str::rand($len, $type - 1);
  62. }
  63. protected function valid($where)
  64. {
  65. $info = Dever::db('code', 'msg')->find($where);
  66. if ($info) {
  67. if (DEVER_TIME - $this->config['cdate'] < $this->config['interval']) {
  68. Dever::error('请不要在'.$this->config['interval'].'秒之内申请多次验证码,请您稍后再试');
  69. } elseif (Dever::db('code', 'msg')->count($where) >= $this->config['total']) {
  70. Dever::error('很抱歉,您已经申请获取验证码超过' . $this->config['total'] . '次,今天您已经无法获取验证码了,请您明天再来');
  71. }
  72. }
  73. }
  74. }