美文网首页
php 推送整合思路

php 推送整合思路

作者: 明天你好_ee9a | 来源:发表于2021-01-27 18:43 被阅读0次

开发中我们经常遇到一些推送类需求,例如小程序模板消息,短信推送,邮箱推送等等,本文主要讲述推送整合,在使用这些推送的时候比较便捷
整合类

<?php


namespace app\index\service\sdk\push;


use Exception;
use think\Db;

/**
 * @author jinanav 2020年7月15日15:49:59
 * @desc 消息推送服务类
 */
class PushService {
    //提供服务类
    public static $service;
    //推送服务类列表
    public $serviceList = [
        //邮箱
        'Email' => EmailPush::class,
        //小程序模板
        'Mini' => MiniPush::class,
        //短信
        'Sms' => SmsPush::class,
        //微信公众号模板
        'WeChat' => WeChatPush::class
    ];
    //配置文件
    protected $config = [];
    //服务类型
    protected $serviceType = "";
    //错误信息
    protected $errorMsg = '未获取任何异常';
    //结果
    protected $result = '';
    //推送状态
    protected $pushStatus = 1;
    //调试模式
    protected $debug = false;

    /**
     * 初始化
     * PushService constructor.
     * @param array $servicesClass 注入其他服务类
     */
    public function __construct(array $servicesClass = [){
        !empty($servicesClass) && $this->serviceList = array_merge($this->serviceList,$servicesClass);
    }


    /**
     * 调度器
     * @return object
     */
    public function dispatch(){
        $name = md5(serialize($this->config));
        if(isset(self::$service[$name])){
            return self::$service[$name];
        }
        $class = $this->serviceList[$this->serviceType];
        return self::$service[$name] = new $class($this->config);

    }

    /**
     * 发送短信
     * @param array $config 配置文件
     * @return $this
     */
    public function sms(array $config = []){
        $this->config = config('sms.');
        !empty($config) && $this->config = array_merge($this->config,$config);
        $this->serviceType = "Sms";
        return $this;
    }

    /**
     * 发送公众号模板消息
     * @param array $config 配置文件
     * @return $this
     */
    public function weChat(array $config = []){
        $this->config = config('wechat.');
        !empty($config) && $this->config = array_merge($this->config,$config);
        $this->serviceType = "WeChat";
        return $this;
    }

    /**
     * 发送邮箱信息
     * @param array $config 配置文件
     * @return $this
     */
    public function email(array $config = []){
        $this->config = config('email.');
        !empty($config) && $this->config = array_merge($this->config,$config);
        $this->serviceType = "Email";
        return $this;
    }

    /**
     * 发送小程序模板消息
     * @param array $config 配置文件
     * @return $this
     */
    public function mini(array $config = []){
        $this->config = config('mini.');
        !empty($config) && $this->config = array_merge($this->config,$config);
        $this->serviceType = "Mini";
        return $this;
    }

    /**
     * 修改配置文件
     * @param array $config 配置文件
     * @return $this
     */
    public function setConfig(array $config){
        $this->config = array_merge($this->config,$config);
        return $this;
    }

    /**
     * 获取配置文件
     * @return array
     */
    public function getConfig(){
        return $this->config;
    }

    /**
     * 调试模式
     * @param bool $debug 是否启用调试
     * @return $this
     */
    public function debug($debug = true){
        $this->debug = $debug;
        return $this;
    }

    /**
     * 获取错误,异常信息
     * @return string
     */
    public function getErrorInfo(){
        return $this->errorMsg;
    }

    /**
     * 消息推送
     * @param string $to 推送给谁,即接收人
     * @param array|string $contents 推送内容
     * @param array $param 模板参数
     * @param string $from 发出者
     * @param array $option 额外参数
     * @return bool
     */
    public function send($to, $contents,  $param = [],$from = null, $option = []){
        try {
            $this->result = $this->dispatch()->send($to,$contents,$param,$from,$option);
        }catch (Exception $e){
            $this->errorMsg = $e->getMessage();
            if($this->debug) exit($this->errorMsg);
            $this->pushStatus = 0;
        }
        $this->log($this->serviceType,$to,$contents,$from,$param,$option);
        return $this->pushStatus ? true : false;
    }


    /**
     * 记录推送日志
     * @author jinanav 2020年7月15日15:53:10
     * @param int $type 消息类型 1-短信 2-邮箱 3-微信 4-系统内部消息
     * @param string $to 接受者
     * @param string|array $contents 推送内容
     * @param string $from 发送者
     * @param array $param 推送参数
     * @param array $option 额外参数
     * @param array $push_status 推送状态
     * @param array $push_result 推送结果
     * @return bool 返回结果
     */
    public function log($type,$to,$contents,$from = '',$param = [],$option = []){
        try {
            return Db::name('log_push')->insert([
                'to'            => $to,
                'from'          => $from,
                'contents'      => json_encode($contents,JSON_UNESCAPED_UNICODE),
                'push_param'    => json_encode($param,JSON_UNESCAPED_UNICODE),
                'push_option'   => json_encode($option,JSON_UNESCAPED_UNICODE),
                'push_status'   => $this->pushStatus,
                'push_result'   => $this->result,
                'type'          => $type
            ]);
        }catch (Exception $e){
            return false;
        }

    }
}

举例实现一个邮箱推送类

<?php


namespace app\index\service\sdk\push;


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use stdClass;


/**
 * @author jinanav 2020年7月15日15:56:41
 * @desc 邮箱消息推送服务类
 */
class EmailPush{
    protected $config;
    /**
     * SmsPush constructor.
     * @param array $config 配置文件
     */
    public function __construct(array $config){
        $this->config = $config;
    }

    /**
     * 发送短信
     * @param string|array $to 接收者 这里指邮箱 可以多个
     * @param string $contents 推送内容,这里邮箱内容
     * @param string $from 发送者 默认 短信模板签名
     * @param array $param 模板参数
     * @param array $option 额外参数
     * @return bool|stdClass
     */
    public function send($to, $contents, $param = [], $from = null, $option = []){
        $mail = new PHPMailer(true);
        $from = $from ?: $this->config['username'];
        //服务器配置
        //设定邮件编码
        $mail->CharSet ="UTF-8";
        // 调试模式输出
        $mail->SMTPDebug = 0;
        // 使用SMTP
        $mail->isSMTP();
        // SMTP服务器
        $mail->Host = $this->config['host'];
        // 允许 SMTP 认证
        $mail->SMTPAuth = true;
        // SMTP 用户名  即邮箱的用户名
        $mail->Username = $this->config['username'];
        // SMTP 密码  部分邮箱是授权码(例如163邮箱)
        $mail->Password = $this->config['password'];
        // 允许 TLS 或者ssl协议
        $mail->SMTPSecure = 'ssl';
        // 服务器端口 25 或者465 具体要看邮箱服务器支持
        $mail->Port = 465;

        //发送内容
        //发件人
        $mail->setFrom($from, "测试");
        // 收件人
        $mail->addAddress($to);
        //回复的时候回复给哪个邮箱 建议和发件人一致
        $mail->addReplyTo($from, '测试');

        //附件
        if(isset($param['attachment']) && !empty($param['attachment'])){
            $mail->AddAttachment($param['attachment'],$param['attachment_name']);
        }

        // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
        $mail->isHTML(true);
        //标题
        $mail->Subject = $param['title'];
        //内容
        $mail->Body    = $contents;
        //如果不支持HTML则发送以下内容
        $mail->AltBody = strip_tags($contents);
        //执行发送
        return $mail->send();
    }
}

调用,调试模式下可以查看到异常

 $push = new PushService();
 $push->debug()->email()->send('chenja@e-class2.com','百家云容量已不足5G,剩下:'.(50),['title'=>'百家云容量不足提醒']);
 $push->weChat()->send("xxx","xxx");
image.png

相关文章

网友评论

      本文标题:php 推送整合思路

      本文链接:https://www.haomeiwen.com/subject/bmextltx.html