Ejemplo n.º 1
0
 public function getVerifyCode($regenerate = false)
 {
     if ($this->fixedVerifyCode !== null) {
         return $this->fixedVerifyCode;
     }
     $session = Yii::$app->session;
     $session->open();
     $name = $this->getSessionKey();
     $mobile = $this->mobile;
     $tableName = $this->tableName;
     if ($session[$name] === null || $regenerate) {
         $needSendSm = $regenerate ? true : false;
         $session[$name] = $this->generateVerifyCode();
         $session[$name . 'count'] = 1;
         if ($needSendSm) {
             if (U::haveProbability(10000)) {
                 $n = Yii::$app->db->createCommand("DELETE from {$tableName} where created < DATE_SUB(NOW(), INTERVAL 3 day)")->execute();
                 U::W("DELETE from {$tableName}, {$n}");
             }
             U::W("generate a sm verify code, mobile={$mobile}, code=" . $session[$name]);
             $sql = "SELECT COUNT(*) FROM {$tableName} WHERE mobile=:mobile AND created=:created";
             $command = yii::$app->db->createCommand($sql, [':mobile' => $mobile, ':created' => date("Y-m-d")]);
             $n = $command->queryScalar();
             if ($n >= $this->maxPerMobile) {
                 U::W("n={$n}, maxPerMobile={$this->maxPerMobile}, mobile={$mobile}, verify_code={$session[$name]}");
                 throw new HttpException(404, "今日校验次数满!");
             }
             $ip = U::getClientIp();
             $sql = "SELECT COUNT(*) FROM {$tableName} WHERE ip=:ip AND created=:created";
             $command = yii::$app->db->createCommand($sql, [':ip' => $ip, ':created' => date("Y-m-d")]);
             $n = $command->queryScalar();
             if ($n >= $this->maxPerIp) {
                 U::W("n={$n}, maxPerIp={$this->maxPerIp}, ip={$ip}, verify_code={$session[$name]}");
                 throw new HttpException(404, "今日校验次数满!!");
             }
             if (!self::DEBUG) {
                 $s = Yii::$app->sm->S($mobile, "【沃手科技】短信验证码:{$session[$name]}", '', null, true);
                 if ($s->isSendOk()) {
                     U::W('Send Sm OK');
                 } else {
                     U::W('Send Sm err');
                 }
             } else {
                 U::W('fake to send sm');
             }
             $n = Yii::$app->db->createCommand()->insert($this->tableName, ['mobile' => $mobile, 'created' => date("Y-m-d"), 'verify_code' => $session[$name], 'ip' => $ip])->execute();
             error_log($mobile . ',' . date('Y-m-d H:i:s') . ',' . $session[$name] . ',' . $ip . "\n", 3, Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'wx_mobile_verify_code.log');
         } else {
             U::W("Session is null, init code=" . $session[$name]);
         }
     }
     return $session[$name];
 }