ThinkPHP5.1 工厂模式集成多个短信平台

2023-11-07

\app\index\controller\Sms

<?php


namespace app\index\controller;


use think\Controller;
use think\exception\ValidateException;
use app\index\validate\User;
use app\common\service\Sms as SmsService;
use think\response\Json;

class Sms extends Controller{

    /**
     * 发送短信到指定手机号码
     * @return Json
     */
    public function send(){
        $phoneNumber = input('post.phone','','trim');
        $data = [
            'phoneNumber' => $phoneNumber,
        ];
        try {
            validate(User::class)->scene("send_code")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"),$e->getError());
        }
        if (SmsService::sendCode($phoneNumber,6,'yunji')){
            return show(config("status.success"),"发送验证码成功");
        }
        return show(config("status.error"),"发送验证码失败");
    }
}

\app\common\service\Sms

<?php
namespace app\common\service;

use app\common\library\ClassFactory;
use app\common\library\Num;
use think\Controller;

class Sms extends Controller{

    public static function sendCode($phoneNumber, $len=6, $type="yunji"){
        //生成短信验证码 4/6位数字
        $code = Num::getCode($len);

        $classStats = ClassFactory::smsClassStat();
        $classObj = ClassFactory::initClass($type, $classStats,[],false);
        $sms = $classObj::sendCode($phoneNumber, $code);
        if ($sms){
            //发送成功,将短信验证码记录到redis,并且给出失效时间
            //1.检测PHP环境是否有redis扩展  windows:redis.dll  linux unix:redis.so
            //2.redis服务器
            cache(config("redis.code_pre").$phoneNumber,$code,config("redis.code_expire"));
            return true;
        }
        return false;
    }



}

\app\common\library\ClassFactory

<?php


namespace app\common\library;


class ClassFactory {

    /**
     * 如果通过工厂模式调用方法是静态的,则返回类,否则需要通过放射机制返回类的对象
     * @param $type ali、yunji……
     * @param $classes
     * @param array $params
     * @param bool $needInstance 是否需要实例化
     * @return bool|mixed|object
     * @throws \ReflectionException
     */
    public static function initClass($type, $classes, $params = [], $needInstance = false){
        if (!array_key_exists($type,$classes)) {
            return false;
        }

        $className = $classes[$type];

        return $needInstance == true ? (new \ReflectionClass($className))->newInstanceArgs($params): $className ;
    }

    public static function  smsClassStat() {
        return [
            "yunji" =>  "app\common\library\sms\YunjiSms",
/*
            "ali"   =>  "app\common\library\sms\AliSms",
            "baidu" =>  "app\common\library\sms\BaiduSms",
            "jd"    =>  "app\common\library\sms\JdSms",*/
        ];
    }
}

\app\common\library\sms\SmsBase

<?php

namespace app\common\library\sms;

interface SmsBase {

    public static function SendCode($phone, $code);

}

\app\common\library\sms\YunjiSms

<?php

namespace app\common\library\sms;
use Curl\Curl;
use think\Exception;
use think\Log;

/**
 * 云集短信平台
 * Class YunjiSms
 * @package app\common\library\sms
 */
class YunjiSms implements SmsBase{


    /**
     * 云集平台发送短信验证码场景
     * @param string $phone
     * @param int $code
     * @return bool
     */
    public static function SendCode($phone, $code){
        try {
            $msg = '【XXXXX】您的验证码为'.$code.',有效期为3分钟,请确保是本人操作,不要把验证码泄露给其他人。';
            $curl = new Curl();
            $msg_data = ['userCode'=>config('sms.userCode'),'userPass'=>config('sms.userPass'),'DesNo'=>$phone,'Msg'=>$msg];
            $url = config('sms.api_url');
            $curl->post($url,$msg_data);
            $res = xmlToArray($curl->response);
            $code_int = (integer)$res[0];
            if ($code_int<0){
                throw new Exception('发送失败', $code_int);
            }
            Log::info("alisms-sendCode-{$phone}-{$code}-result:".json_encode($res));
        }catch (Exception $e){
            Log::error("yunjisms-sendCode-{$phone}-ServerException:".$e->getCode());
            return false;
        }
        return true;
    }


}

config.php

    //云集短信
    'sms' => [
        'api_url'   =>  'http://118.178.116.15/winnerrxd/api/trigger/SendMsg',
        'userCode'  =>  'C********J',
        'userPass'  =>  'Z********!',
    ],

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ThinkPHP5.1 工厂模式集成多个短信平台 的相关文章

随机推荐