Browse Source

feat: 新短信平台

master
liyang 2 weeks ago
parent
commit
65554fbeea
  1. 10
      app/admin/job/SendSmsFromBackend.php
  2. 407
      app/home/service/BaseHomeService.php
  3. 42
      app/sms/Sms.php
  4. 8
      app/sms/contracts/SmsDriverInterface.php
  5. 165
      app/sms/drivers/WorldSmsDriver.php
  6. 79
      app/utility/SendSms.php
  7. 16
      config/sms.php

10
app/admin/job/SendSmsFromBackend.php

@ -1,6 +1,9 @@
<?php
namespace app\admin\job;
use think\queue\Job;
class SendSmsFromBackend
{
@ -14,7 +17,7 @@ class SendSmsFromBackend
$configStr = env('SMS.CONFIG');
$arr = explode(',', $configStr);
$config = [];
foreach ($arr as $value){
foreach ($arr as $value) {
$conArr = explode('@', $value);
$config[] = [
'access_key' => $conArr[0],
@ -33,7 +36,7 @@ class SendSmsFromBackend
*/
public function fire(Job $job, $data)
{
trace($job->getJobId().'---管理端发送短信任务开始--------'.json_encode($data), 'info');
trace($job->getJobId() . '---管理端发送短信任务开始--------' . json_encode($data), 'info');
$to = $data['mobile'];
$message = $data['message'];
$from = 'Bourse';
@ -47,5 +50,4 @@ class SendSmsFromBackend
// 删除任务
$job->delete();
}
}
}

407
app/home/service/BaseHomeService.php

@ -44,7 +44,7 @@ class BaseHomeService
}
public function __construct()
{
$this->redis=$this->getRedis();
$this->redis = $this->getRedis();
//$this->getTrcWalletAddress();
}
@ -53,14 +53,14 @@ class BaseHomeService
*/
private function getTrcWalletAddress()
{
$redis_key="TRCWallet";
$num=WalletListModel::where([
'user_id'=>0,
'wallet_type'=>'TRC-20'
$redis_key = "TRCWallet";
$num = WalletListModel::where([
'user_id' => 0,
'wallet_type' => 'TRC-20'
])->count();
$flag=$this->redis->exists($redis_key);
if($num<50 && empty($flag)){
$this->redis->setex($redis_key,120,2);
$flag = $this->redis->exists($redis_key);
if ($num < 50 && empty($flag)) {
$this->redis->setex($redis_key, 120, 2);
$queuename = 'app\home\job\Wallet';
Queue::push($queuename, "test", 'Wallet');
}
@ -74,8 +74,8 @@ class BaseHomeService
*/
public function getSmsContent(int $type = 1): array
{
$code = random_int(1000,9999);
$subject = "your code is [$code], valid for 5 minutes";
$code = random_int(1000, 9999);
$subject = "【Acm】あなたの認証コード[$code],有効10分以内";
return ['subject' => $subject, 'code' => $code];
}
@ -87,15 +87,16 @@ class BaseHomeService
*/
public function getEmailContent(int $type = 1): array
{
$code = random_int(1000,9999);
// $title = 'Verification Code';
// $subject = "your code is [$code], valid for 5 minutes, please do not reply to this email";
$code = random_int(1000, 9999);
// $title = 'Verification Code';
// $subject = "your code is [$code], valid for 5 minutes, please do not reply to this email";
$title = '検証コード';
$subject = "あなたのコードは[$code]で、5分間有効です";
return ['title' => $title, 'subject' => $subject, 'code' => $code];
}
public function getEmailTemplateForRegDone(){
public function getEmailTemplateForRegDone()
{
return [
'title' => '账号注册成功',
'content' => '您的账号注册成功.',
@ -109,23 +110,23 @@ class BaseHomeService
*/
public function getUniqUserNo(): string
{
$userNoData = UserNoModel::create(['created_time'=>date("Y-m-d H:i:s")]);
return 's'.$userNoData->id;
// $code = 's';
// $code .= date('ymd'); // s230629
// while (true)
// {
// $code .= rand(100000, 999999);
// // redis 去重
// $exist = Cache::store('redis')->get($code);
// // 存储有效期为距离明天还要多久
// $expire = strtotime('tomorrow') - time();
// if (!$exist) {
// Cache::store('redis')->set($code, 1, $expire);
// break;
// }
// }
// return $code;
$userNoData = UserNoModel::create(['created_time' => date("Y-m-d H:i:s")]);
return 's' . $userNoData->id;
// $code = 's';
// $code .= date('ymd'); // s230629
// while (true)
// {
// $code .= rand(100000, 999999);
// // redis 去重
// $exist = Cache::store('redis')->get($code);
// // 存储有效期为距离明天还要多久
// $expire = strtotime('tomorrow') - time();
// if (!$exist) {
// Cache::store('redis')->set($code, 1, $expire);
// break;
// }
// }
// return $code;
}
/**
@ -136,11 +137,11 @@ class BaseHomeService
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
function getUniqInviteCode($length = 6) {
function getUniqInviteCode($length = 6)
{
$characters = '1234567890abcdefghijklmnpqrstwxyzABCDEFGHIJKLMNPQRSTWXYZ';
$inviteCode = '';
while (true)
{
while (true) {
for ($i = 0; $i < $length; $i++) {
$index = rand(0, strlen($characters) - 1);
$inviteCode .= $characters[$index];
@ -148,12 +149,12 @@ class BaseHomeService
// 查询去重
$user = UserModel::where('invite_code', $inviteCode)->value('user_id');
if(empty($user)){
if (empty($user)) {
break;
}
// 查询去重
$agent = AdminModel::where('invite_code', $inviteCode)->value('id');
if(empty($agent)){
if (empty($agent)) {
break;
}
}
@ -169,13 +170,23 @@ class BaseHomeService
{
$code = '';
$arr = [
'9','t','6', 'k', 'h', '8', '5','f', 'm', 'd', 's', '6'
'9',
't',
'6',
'k',
'h',
'8',
'5',
'f',
'm',
'd',
's',
'6'
];
// redis 去重
while (true)
{
$rand_num = time().rand(10,99);
for($i = 0; $i<strlen($rand_num); $i++) {
while (true) {
$rand_num = time() . rand(10, 99);
for ($i = 0; $i < strlen($rand_num); $i++) {
$code .= $arr[$rand_num[$i]];
}
$exist = Cache::store('redis')->get($code);
@ -253,11 +264,11 @@ class BaseHomeService
public function checkGetNoTradeCodeNum($key): bool
{
$num = env('LOGIN.PER_IP_GET_CODE_NUM');
if(!Cache::store('redis')->has($key)){
if (!Cache::store('redis')->has($key)) {
return false;
}
$hadNum = Cache::store('redis')->get($key);
if($hadNum >= $num ){
if ($hadNum >= $num) {
return true;
}
@ -273,11 +284,11 @@ class BaseHomeService
public function checkGetNoTradeCodeNumPhone($key): bool
{
$num = env('LOGIN.PER_PHONE_GET_CODE_NUM');
if(!Cache::store('redis')->has($key)){
if (!Cache::store('redis')->has($key)) {
return false;
}
$hadNum = Cache::store('redis')->get($key);
if($hadNum >= $num ){
if ($hadNum >= $num) {
return true;
}
@ -292,10 +303,10 @@ class BaseHomeService
*/
public function updateHadGetCodeNumCache($key)
{
if(!Cache::store('redis')->has($key)){
if (!Cache::store('redis')->has($key)) {
$expire = 24 * 60 * 60;
Cache::store('redis')->set($key, 1, $expire);
}else{
} else {
Cache::store('redis')->inc($key, 1);
}
}
@ -323,7 +334,7 @@ class BaseHomeService
public function checkCode($key, $code)
{
$cacheCode = Cache::store('redis')->get($key);
if(empty($cacheCode)){
if (empty($cacheCode)) {
return false;
}
@ -338,7 +349,7 @@ class BaseHomeService
public function checkRegisterLimit($key)
{
$setCanRegisterNumPerDayPerIp = env('LOGIN.PER_IP_REGISTER_NUM_EVERY_DAY');
if(!Cache::store('redis')->has($key)){
if (!Cache::store('redis')->has($key)) {
return false;
}
@ -354,7 +365,7 @@ class BaseHomeService
*/
public function updateHadRegisterNumCache($key)
{
if(!Cache::store('redis')->has($key)){
if (!Cache::store('redis')->has($key)) {
$expire = 24 * 60 * 60;
Cache::store('redis')->set($key, 1, $expire);
}
@ -372,7 +383,7 @@ class BaseHomeService
public function getParentIdByInviteCode($inviteCode)
{
$parentUser = UserModel::getUserByInviteCode($inviteCode);
if(empty($parentUser)){
if (empty($parentUser)) {
return 0;
}
return $parentUser['user_id'];
@ -392,115 +403,117 @@ class BaseHomeService
public function setUserTokenCache($token, $userId)
{
// 清除之前的token 设置新的token
$userTokenKey = 'USER:TOKEN:'.$userId; // 根据用户id 查找token
$userTokenKey = 'USER:TOKEN:' . $userId; // 根据用户id 查找token
$oldToken = Cache::store('redis')->get($userTokenKey);
if($oldToken){
$oldTokenKey = 'TOKEN:USER:'.$oldToken;
if ($oldToken) {
$oldTokenKey = 'TOKEN:USER:' . $oldToken;
Cache::store('redis')->delete($oldTokenKey);
}
$tokenKey = 'TOKEN:USER:'.$token; // 根据token查找用户id
$tokenKey = 'TOKEN:USER:' . $token; // 根据token查找用户id
$expired = 30 * 24 * 60 * 60;
// 由中间件自动续期
Cache::store('redis')->set($tokenKey, $userId, $expired);
Cache::store('redis')->set($userTokenKey, $token, $expired);
}
public function delUserTokenCache($userId)
{
// user -> token
$userTokenKey = 'USER:TOKEN:'.$userId; // 根据用户id 查找token
$userTokenKey = 'USER:TOKEN:' . $userId; // 根据用户id 查找token
$token = Cache::store('redis')->get($userTokenKey);
Cache::store('redis')->delete($token);
// token -> user
$tokenUser = 'TOKEN:USER:'.$token;
$tokenUser = 'TOKEN:USER:' . $token;
Cache::store('redis')->delete($tokenUser);
}
public function setUserLevel($userId,$level_info)
public function setUserLevel($userId, $level_info)
{
$key='USER:LEVEL:'.$userId;
$key = 'USER:LEVEL:' . $userId;
// 由中间件自动续期
Cache::store('redis')->set($key, $level_info);
}
public function initSetting(){
public function initSetting()
{
$this->initTradeFeeSetting();
$this->initBrokerageRegSetting();
$this->initUserLevelSetting();
$this->initContractSetting();
$this->initDigitalList();
$this->initDrawalSetting(1);
return $this->toData(0,'ok');
return $this->toData(0, 'ok');
}
public function initDigitalList(){
$result=DigitalListModel::getMarketList([
'page'=>1,
'page_size'=>2000
public function initDigitalList()
{
$result = DigitalListModel::getMarketList([
'page' => 1,
'page_size' => 2000
]);
foreach ($result['list'] as $val){
$key="DIGITAL:LIST:".$val['name'];
foreach ($result['list'] as $val) {
$key = "DIGITAL:LIST:" . $val['name'];
$this->redis->del($key);
$this->redis->hMSet($key,$val);
$this->redis->hMSet($key, $val);
}
return $result['list'];
}
public function getDigitalList(){
$data=$this->redis->keys('DIGITAL:LIST:*');
$list=[];
foreach ($data as $val){
$list[]=$this->redis->hGetAll($val);
public function getDigitalList()
{
$data = $this->redis->keys('DIGITAL:LIST:*');
$list = [];
foreach ($data as $val) {
$list[] = $this->redis->hGetAll($val);
}
return [
'total'=>count($data),
'list'=>$list,
'total' => count($data),
'list' => $list,
];
}
public function initDrawalSetting($type=0)
public function initDrawalSetting($type = 0)
{
$key="DRAWAL:FEE:SETTING";
if($type==1){
$info=DrawalSettingModel::getDrawalFee();
$this->redis->hMset($key,$info);
}else{
$key = "DRAWAL:FEE:SETTING";
if ($type == 1) {
$info = DrawalSettingModel::getDrawalFee();
$this->redis->hMset($key, $info);
} else {
return $this->redis->hGetAll($key);
}
}
public function initContractSetting()
{
$list=ContractListMode::getMarketFaceList();
foreach ($list as $val){
$key="CONTRACT:LIST:".$val['name'];
$list = ContractListMode::getMarketFaceList();
foreach ($list as $val) {
$key = "CONTRACT:LIST:" . $val['name'];
$this->redis->del($key);
$this->redis->hMSet($key,$val);
$this->redis->hMSet($key, $val);
}
return $list;
}
public function getContractFaceList($type=0)
public function getContractFaceList($type = 0)
{
$list=$this->redis->keys('CONTRACT:LIST:*');
$list = $this->redis->keys('CONTRACT:LIST:*');
//var_dump($list);
if(empty($list)){
$list=$this->initContractSetting();
if($type){
if (empty($list)) {
$list = $this->initContractSetting();
if ($type) {
return $list;
}else{
} else {
return [
'total'=>count($list),
'list'=>$list
'total' => count($list),
'list' => $list
];
}
}else{
$data=[];
foreach ($list as $val){
$data[]=$this->redis->hGetAll($val);
}
if($type){
} else {
$data = [];
foreach ($list as $val) {
$data[] = $this->redis->hGetAll($val);
}
if ($type) {
return $data;
}else{
} else {
return [
'total'=>count($data),
'list'=>$data
'total' => count($data),
'list' => $data
];
}
}
@ -508,22 +521,22 @@ class BaseHomeService
public function initBrokerageRegSetting()
{
//注册返佣
$brokerage_reg_key='BROKERAGE:REG:SETTING';
$brokerage_reg_key = 'BROKERAGE:REG:SETTING';
//开仓返佣
$brokerage_buy_key='BROKERAGE:BUY:SETTING';
$brokerage_buy_key = 'BROKERAGE:BUY:SETTING';
//平仓返佣
$brokerage_sale_key='BROKERAGE:SALE:SETTING';
$list=BrokerageSettingModel::getBrokerageSetting();
foreach ($list as $val){
switch ($val['brok_type']){
$brokerage_sale_key = 'BROKERAGE:SALE:SETTING';
$list = BrokerageSettingModel::getBrokerageSetting();
foreach ($list as $val) {
switch ($val['brok_type']) {
case 1:
$this->redis->hMset($brokerage_buy_key,$val);
$this->redis->hMset($brokerage_buy_key, $val);
break;
case 2:
$this->redis->hMset($brokerage_sale_key,$val);
$this->redis->hMset($brokerage_sale_key, $val);
break;
default:
$this->redis->hMset($brokerage_reg_key,$val);
$this->redis->hMset($brokerage_reg_key, $val);
break;
}
}
@ -535,179 +548,177 @@ class BaseHomeService
public function getBrokerageRegSetting()
{
//注册返佣
$brokerage_reg_key='BROKERAGE:REG:SETTING';
$res= $this->redis->hGetAll($brokerage_reg_key);
if(empty($res)){
$this->initBrokerageRegSetting();
$res= $this->redis->hGetAll($brokerage_reg_key);
$brokerage_reg_key = 'BROKERAGE:REG:SETTING';
$res = $this->redis->hGetAll($brokerage_reg_key);
if (empty($res)) {
$this->initBrokerageRegSetting();
$res = $this->redis->hGetAll($brokerage_reg_key);
}
return $res;
}
public function initUserLevelSetting()
{
$list=UserLevelModel::getUserLevelList();
foreach ($list as $item){
$key='USER:LEVEL:'.$item['user_id'];
$this->redis->hMset($key,$item);
}
}
public function initTradeFeeSetting($market_type=0)
{
$digital_fee_key='TRADE:FEE:DIGITAL';
$contract_fee_key='TRADE:FEE:CONTRACT';
$us_stock_fee_key='TRADE:FEE:US_STOCK';
$idn_stock_fee_key='TRADE:FEE:IDN_STOCK';
$mys_stock_fee_key='TRADE:FEE:MYS_STOCK';
$tha_stock_fee_key='TRADE:FEE:THA_STOCK';
$in_stock_fee_key='TRADE:FEE:IN_STOCK';
$SGD_stock_fee_key='TRADE:FEE:SGD_STOCK';
$hk_stock_fee_key='TRADE:FEE:HK_STOCK';
$uk_stock_fee_key='TRADE:FEE:UK_STOCK';
$fur_stock_fee_key='TRADE:FEE:FUR_STOCK';
$eur_stock_fee_key='TRADE:FEE:EUR_STOCK';
$brl_stock_fee_key='TRADE:FEE:BR_STOCK';
$jp_stock_fee_key='TRADE:FEE:JP_STOCK';
$forex_fee_key='TRADE:FEE:FOREX';
$list = UserLevelModel::getUserLevelList();
foreach ($list as $item) {
$key = 'USER:LEVEL:' . $item['user_id'];
$this->redis->hMset($key, $item);
}
}
public function initTradeFeeSetting($market_type = 0)
{
$digital_fee_key = 'TRADE:FEE:DIGITAL';
$contract_fee_key = 'TRADE:FEE:CONTRACT';
$us_stock_fee_key = 'TRADE:FEE:US_STOCK';
$idn_stock_fee_key = 'TRADE:FEE:IDN_STOCK';
$mys_stock_fee_key = 'TRADE:FEE:MYS_STOCK';
$tha_stock_fee_key = 'TRADE:FEE:THA_STOCK';
$in_stock_fee_key = 'TRADE:FEE:IN_STOCK';
$SGD_stock_fee_key = 'TRADE:FEE:SGD_STOCK';
$hk_stock_fee_key = 'TRADE:FEE:HK_STOCK';
$uk_stock_fee_key = 'TRADE:FEE:UK_STOCK';
$fur_stock_fee_key = 'TRADE:FEE:FUR_STOCK';
$eur_stock_fee_key = 'TRADE:FEE:EUR_STOCK';
$brl_stock_fee_key = 'TRADE:FEE:BR_STOCK';
$jp_stock_fee_key = 'TRADE:FEE:JP_STOCK';
$forex_fee_key = 'TRADE:FEE:FOREX';
$indian_stock_index_key = 'TRADE:FEE:INDEX_INR'; // 印度股指
$gold_futures_key = 'TRADE:FEE:GOLD_FUTURES'; // 黄金期货
if($market_type==0){
$trade_fee_list=FeeSettingModel::getTradeFeeById(0);
foreach ($trade_fee_list as $item){
switch ($item['market_type']){
if ($market_type == 0) {
$trade_fee_list = FeeSettingModel::getTradeFeeById(0);
foreach ($trade_fee_list as $item) {
switch ($item['market_type']) {
case 1:
$this->redis->del($digital_fee_key);
$this->redis->hMset($digital_fee_key,$item);
$this->redis->hMset($digital_fee_key, $item);
break;
case 2:
$this->redis->del($contract_fee_key);
$this->redis->hMset($contract_fee_key,$item);
$this->redis->hMset($contract_fee_key, $item);
break;
case 3:
$this->redis->del($us_stock_fee_key);
$this->redis->hMset($us_stock_fee_key,$item);
$this->redis->hMset($us_stock_fee_key, $item);
break;
case 4:
$this->redis->del($idn_stock_fee_key);
$this->redis->hMset($idn_stock_fee_key,$item);
$this->redis->hMset($idn_stock_fee_key, $item);
break;
case 5:
$this->redis->del($mys_stock_fee_key);
$this->redis->hMset($mys_stock_fee_key,$item);
$this->redis->hMset($mys_stock_fee_key, $item);
break;
case 6:
$this->redis->del($tha_stock_fee_key);
$this->redis->hMset($tha_stock_fee_key,$item);
$this->redis->hMset($tha_stock_fee_key, $item);
break;
case 7:
$this->redis->del($in_stock_fee_key);
$this->redis->hMset($in_stock_fee_key,$item);
$this->redis->hMset($in_stock_fee_key, $item);
break;
case 9:
$this->redis->del($SGD_stock_fee_key);
$this->redis->hMset($SGD_stock_fee_key,$item);
$this->redis->hMset($SGD_stock_fee_key, $item);
break;
case 12:
$this->redis->del($hk_stock_fee_key);
$this->redis->hMset($hk_stock_fee_key,$item);
$this->redis->hMset($hk_stock_fee_key, $item);
break;
case 14:
$this->redis->del($uk_stock_fee_key);
$this->redis->hMset($uk_stock_fee_key,$item);
$this->redis->hMset($uk_stock_fee_key, $item);
break;
case 15:
$this->redis->del($fur_stock_fee_key);
$this->redis->hMset($fur_stock_fee_key,$item);
$this->redis->hMset($fur_stock_fee_key, $item);
break;
case 16:
$this->redis->del($eur_stock_fee_key);
$this->redis->hMset($eur_stock_fee_key,$item);
$this->redis->hMset($eur_stock_fee_key, $item);
break;
case 17:
$this->redis->del($brl_stock_fee_key);
$this->redis->hMset($brl_stock_fee_key,$item);
$this->redis->hMset($brl_stock_fee_key, $item);
break;
case 18:
$this->redis->del($jp_stock_fee_key);
$this->redis->hMset($jp_stock_fee_key,$item);
$this->redis->hMset($jp_stock_fee_key, $item);
break;
case 19:
$this->redis->del($forex_fee_key);
$this->redis->hMset($forex_fee_key,$item);
$this->redis->hMset($forex_fee_key, $item);
break;
case 20:
$this->redis->del($indian_stock_index_key);
$this->redis->hMset($indian_stock_index_key,$item);
$this->redis->hMset($indian_stock_index_key, $item);
break;
case 21:
$this->redis->del($gold_futures_key);
$this->redis->hMset($gold_futures_key,$item);
$this->redis->hMset($gold_futures_key, $item);
break;
}
}
return $trade_fee_list;
}else{
$res=[];
switch ($market_type){
} else {
$res = [];
switch ($market_type) {
case 1:
$res= $this->redis->hGetAll($digital_fee_key);
break;
$res = $this->redis->hGetAll($digital_fee_key);
break;
case 2:
$res=$this->redis->hGetAll($contract_fee_key);
break;
$res = $this->redis->hGetAll($contract_fee_key);
break;
case 3:
$res=$this->redis->hGetAll($us_stock_fee_key);
break;
$res = $this->redis->hGetAll($us_stock_fee_key);
break;
case 4:
$res=$this->redis->hGetAll($idn_stock_fee_key);
$res = $this->redis->hGetAll($idn_stock_fee_key);
break;
case 5:
$res=$this->redis->hGetAll($mys_stock_fee_key);
$res = $this->redis->hGetAll($mys_stock_fee_key);
break;
case 6:
$res=$this->redis->hGetAll($tha_stock_fee_key);
$res = $this->redis->hGetAll($tha_stock_fee_key);
break;
case 7:
$res=$this->redis->hGetAll($in_stock_fee_key);
$res = $this->redis->hGetAll($in_stock_fee_key);
break;
case 9:
$res=$this->redis->hGetAll($SGD_stock_fee_key);
$res = $this->redis->hGetAll($SGD_stock_fee_key);
break;
case 12:
$res=$this->redis->hGetAll($hk_stock_fee_key);
$res = $this->redis->hGetAll($hk_stock_fee_key);
break;
case 14:
$res=$this->redis->hGetAll($uk_stock_fee_key);
$res = $this->redis->hGetAll($uk_stock_fee_key);
break;
case 15:
$res=$this->redis->hGetAll($fur_stock_fee_key);
$res = $this->redis->hGetAll($fur_stock_fee_key);
break;
case 16:
$res=$this->redis->hGetAll($eur_stock_fee_key);
$res = $this->redis->hGetAll($eur_stock_fee_key);
break;
case 17:
$res=$this->redis->hGetAll($brl_stock_fee_key);
$res = $this->redis->hGetAll($brl_stock_fee_key);
break;
case 18:
$res=$this->redis->hGetAll($jp_stock_fee_key);
$res = $this->redis->hGetAll($jp_stock_fee_key);
break;
case 19:
$res=$this->redis->hGetAll($forex_fee_key);
$res = $this->redis->hGetAll($forex_fee_key);
break;
case 20:
$res=$this->redis->hGetAll($indian_stock_index_key);
$res = $this->redis->hGetAll($indian_stock_index_key);
break;
case 21:
$res=$this->redis->hGetAll($gold_futures_key);
$res = $this->redis->hGetAll($gold_futures_key);
break;
}
return $res;
}
}
private function checkEmpty($value1, $value2, $value3) :bool
private function checkEmpty($value1, $value2, $value3): bool
{
$count = 0; // 用于计数非空值的个数
if (!empty($value1)) {
@ -722,16 +733,17 @@ class BaseHomeService
// 如果非空值的个数等于1,则返回 true,否则返回 false
return $count == 3;
}
public function getRedis(){
$config=\think\facade\Config::get('cache.stores.redis');
$redis=new \Redis();
public function getRedis()
{
$config = \think\facade\Config::get('cache.stores.redis');
$redis = new \Redis();
try{
$redis->connect($config['host'], $config['port'],10);
}catch (\Exception $exception){
try {
$redis->connect($config['host'], $config['port'], 10);
} catch (\Exception $exception) {
echo 'redis连接失败';
}
if(!empty($config['password'])){
if (!empty($config['password'])) {
$redis->auth($config['password']);
}
@ -743,7 +755,8 @@ class BaseHomeService
* @param int $length
* @return false|string
*/
public function generateOrderNumber(int $length=20) {
public function generateOrderNumber(int $length = 20)
{
$prefix = date('ymd'); // 可选的订单号前缀,如需要可以在这里设置
$timestamp = time();
$randomNum = mt_rand(10000, 99999); // 使用 mt_rand() 生成一个四位的随机数
@ -991,6 +1004,4 @@ class BaseHomeService
return $result;
}
}
}
}

42
app/sms/Sms.php

@ -0,0 +1,42 @@
<?php
namespace app\sms;
use app\sms\contracts\SmsDriverInterface;
class Sms
{
protected $driver;
/**
* Sms constructor.
* @param string|null $channel
* @throws \Exception
*/
public function __construct(?string $channel = null)
{
$channel = $channel ?: config('sms.default');
$drivers = config('sms.channels');
if (!isset($drivers[$channel])) {
throw new \Exception("短信通道 [$channel] 未配置");
}
$class = $drivers[$channel]['driver'];
$config = $drivers[$channel]['config'];
if (!class_exists($class)) {
throw new \Exception("短信驱动类 [$class] 不存在");
}
$this->driver = new $class($config);
if (!($this->driver instanceof SmsDriverInterface)) {
throw new \Exception("[$class] 必须实现 SmsDriverInterface 接口");
}
}
public function send(string $mobile, string $templateId, array $data = []): array
{
return $this->driver->send($mobile, $templateId, $data);
}
}

8
app/sms/contracts/SmsDriverInterface.php

@ -0,0 +1,8 @@
<?php
namespace app\sms\contracts;
interface SmsDriverInterface
{
public function send(string $mobile, string $templateId, array $data = []): array;
}

165
app/sms/drivers/WorldSmsDriver.php

@ -0,0 +1,165 @@
<?php
namespace app\sms\drivers;
use app\sms\contracts\SmsDriverInterface;
use GuzzleHttp\Client;
class WorldSmsDriver implements SmsDriverInterface
{
protected $config;
protected $client;
public function __construct(array $config)
{
$this->config = $config;
$this->client = new Client([
'base_uri' => rtrim($this->config['host'], '/') . '/',
'timeout' => 5.0,
]);
}
/**
* 发送短信
* @param string $mobile 手机号(多个用逗号分隔)
* @param string $templateId 未使用模板可留空
* @param array $data ['content' => '短信内容']
* @return array
*/
public function send(string $mobile, string $templateId = '', array $data = []): array
{
$url = 'sendsms';
$body = [
'account' => $this->config['account'],
'password' => $this->config['password'],
'numbers' => $mobile,
'smstype' => $data['smstype'] ?? 0,
'sender' => $data['title'] ?? '',
'content' => $data['content'] ?? '',
];
try {
$response = $this->client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json;charset=utf-8'
],
'body' => json_encode($body, JSON_UNESCAPED_UNICODE),
]);
$result = json_decode($response->getBody()->getContents(), true);
return [
'success' => $result['status'] === 0,
'data' => $result,
'msg' => $result['status'] === 0 ? '发送成功' : '发送失败',
];
} catch (\Throwable $e) {
return [
'success' => false,
'msg' => '请求失败:' . $e->getMessage(),
'data' => [],
];
}
}
/**
* 查询余额
*/
public function getBalance(): array
{
$url = 'getbalance';
$body = [
'version' => '3.4',
'account' => $this->config['account'],
'password' => $this->config['password'],
];
return $this->getJson($url, $body);
}
/**
* 查询短信状态(单条)
*/
public function getStatus(string $msgid): array
{
$url = 'getstatus';
$body = [
'account' => $this->config['account'],
'password' => $this->config['password'],
'msgid' => $msgid,
];
return $this->getJson($url, $body);
}
/**
* 获取接收短信
*/
public function getInbox(): array
{
$url = 'getinbox';
$body = [
'account' => $this->config['account'],
'password' => $this->config['password'],
];
return $this->getJson($url, $body);
}
/**
* 通用 POST 请求
*/
protected function postJson(string $url, array $body): array
{
try {
$response = $this->client->post($url, [
'headers' => [
'Content-Type' => 'application/json;charset=utf-8',
],
'json' => $body,
]);
$result = json_decode($response->getBody()->getContents(), true);
return [
'success' => $result['status'] === 0,
'msg' => $result['status'] === 0 ? '操作成功' : ($result['message'] ?? '失败'),
'data' => $result,
];
} catch (\Throwable $e) {
return [
'success' => false,
'msg' => '请求异常: ' . $e->getMessage(),
'data' => [],
];
}
}
/**
* 通用 GET 请求
*/
protected function getJson(string $url, array $query = []): array
{
try {
$response = $this->client->get($url, [
'headers' => [
'Accept' => 'application/json',
],
'query' => $query,
]);
$result = json_decode($response->getBody()->getContents(), true);
return [
'success' => $result['status'] === 0,
'msg' => $result['status'] === 0 ? '操作成功' : ($result['message'] ?? '失败'),
'data' => $result,
];
} catch (\Throwable $e) {
return [
'success' => false,
'msg' => '请求异常: ' . $e->getMessage(),
'data' => [],
];
}
}
}

79
app/utility/SendSms.php

@ -32,16 +32,16 @@ class SendSms
])
->request();
$res = $result->toArray();
if(!isset($res['ResponseCode']) || $res['ResponseCode'] != 'OK'){
trace('短信发送失败:'.json_encode([$res]), 'error');
if (!isset($res['ResponseCode']) || $res['ResponseCode'] != 'OK') {
trace('短信发送失败:' . json_encode([$res]), 'error');
}
return true;
}catch (ClientException $clientException) {
trace('短信发送失败01_'.$clientException->getMessage(), 'error');
}catch (ServerException $serverException) {
trace('短信发送失败02_'.$serverException->getErrorMessage(), 'error');
}catch (\Exception $exception) {
trace('短信发送失败03_'.$exception->getMessage(), 'error');
} catch (ClientException $clientException) {
trace('短信发送失败01_' . $clientException->getMessage(), 'error');
} catch (ServerException $serverException) {
trace('短信发送失败02_' . $serverException->getErrorMessage(), 'error');
} catch (\Exception $exception) {
trace('短信发送失败03_' . $exception->getMessage(), 'error');
}
return false;
@ -51,36 +51,47 @@ class SendSms
public function sendMessageToGlobe($toNum, $content, $from, $accessKey, $secret)
{
try {
AlibabaCloud::accessKeyClient($accessKey, $secret)
->regionId('ap-southeast-1') // 服务点对应的公网接入地址: https://www.alibabacloud.com/help/zh/sms/developer-reference/api-dysmsapi-2018-05-01-endpoint?spm=a2c63.p38356.help-menu-44282.d_3_2_1.248f60deo2Ug5G
->asDefaultClient();
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
->version('2018-05-01')
->action('SendMessageToGlobe')
->method('POST')
->host('dysmsapi.ap-southeast-1.aliyuncs.com')
->options([
'query' => [
"To" => $toNum,
"Message" => $content,
"From" => $from, // Sender ID 在阿里云控制台申请
],
])
->request();
$res = $result->toArray();
trace('短信发送结果:'.json_encode([$res]), 'error');
if(!isset($res['ResponseCode']) || $res['ResponseCode'] != 'OK'){
// 新对接的短信平台
$sms = new \app\sms\Sms();
$result = $sms->send($toNum, '', [
'content' => $content,
'title' => $from,
]);
trace('短信发送结果:' . json_encode([$result]), 'error');
if ($result['success'] !== 0) {
trace('短信发送失败:' . json_encode($result), 'error');
return false;
}
// AlibabaCloud::accessKeyClient($accessKey, $secret)
// ->regionId('ap-southeast-1') // 服务点对应的公网接入地址: https://www.alibabacloud.com/help/zh/sms/developer-reference/api-dysmsapi-2018-05-01-endpoint?spm=a2c63.p38356.help-menu-44282.d_3_2_1.248f60deo2Ug5G
// ->asDefaultClient();
// $result = AlibabaCloud::rpc()
// ->product('Dysmsapi')
// ->version('2018-05-01')
// ->action('SendMessageToGlobe')
// ->method('POST')
// ->host('dysmsapi.ap-southeast-1.aliyuncs.com')
// ->options([
// 'query' => [
// "To" => $toNum,
// "Message" => $content,
// "From" => $from, // Sender ID 在阿里云控制台申请
// ],
// ])
// ->request();
// $res = $result->toArray();
// trace('短信发送结果:'.json_encode([$res]), 'error');
// if(!isset($res['ResponseCode']) || $res['ResponseCode'] != 'OK'){
// return false;
// }
return true;
} catch (ClientException $clientException) {
trace('短信发送失败01_'.$clientException->getErrorMessage(), 'error');
}catch (ServerException $serverException) {
trace('短信发送失败02_'.$serverException->getErrorMessage(), 'error');
}catch (\Exception $exception) {
trace('短信发送失败03_'.$exception->getMessage(), 'error');
trace('短信发送失败01_' . $clientException->getErrorMessage(), 'error');
} catch (ServerException $serverException) {
trace('短信发送失败02_' . $serverException->getErrorMessage(), 'error');
} catch (\Exception $exception) {
trace('短信发送失败03_' . $exception->getMessage(), 'error');
}
return false;
}
}
}

16
config/sms.php

@ -0,0 +1,16 @@
<?php
return [
'default' => 'world',
'channels' => [
'world' => [
'driver' => \app\sms\drivers\WorldSmsDriver::class,
'config' => [
'host' => 'http://8.218.111.176:20003/',
'account' => '068109OTP',
'password' => 'y5CjJzUOL',
],
],
// 其他通道...
],
];
Loading…
Cancel
Save