基于redis+mysql+php的简单微信服务号通知队列

本文阅读 1 分钟
首页 PHP笔记 正文

Queue.php

<?php

/**
 * Queue.php
 * User: Administrator
 * Date: 2019/4/4
 * Time: 13:19
 */
namespace Index;
require_once('Weixin/Wxapi.php');
require_once('Mysql/Mysql.php');
use Weixin\Wxapi;
use Mysql\Mysql;
class Index {
    private $Redis;
    private $Expire;
    private $WxData;
    private $DB;
    public function __construct()
    {
        $this->WxData = [
            //服务号1
            "a"  =>  [ "AppId"     =>"",
                "AppSecret" =>"",
                "Token"     =>"",
                "Crypt"     =>"",
                "template"  =>""
            ],
            //服务号2
            "b"   =>  [
                "AppId"     =>  "",
                "AppSecret" =>  "",
                "Token"     =>"",
                "Crypt"     =>"",
                "template"  =>  ""

            ],
            "c"   =>  [
                "AppId"     =>  "",
                "AppSecret" =>  "",
                "Token"     =>"",
                "Crypt"     =>"",
                "template"  =>  ""

            ]
        ];

        $this ->Redis = new \Redis();
        $this ->Redis -> connect( "127.0.0.1", "6379" );
        $this->DB = new Mysql();

//        $this ->Redis ->auth("123456");
        self::init();
    }
    public function init(){
        while (true) {

            $key = $this->Redis->keys("*");
            if(  !$key  ){

                sleep(10);

            }else{

                foreach ($key as $k) {
                    $value = $this->Redis->lpop($k);
                    $data = json_decode($value, true);
                    if ($data) {
                        $AppId = $this->WxData[$k]["AppId"];
                        $AppSecret = $this->WxData[$k]["AppSecret"];
                        $templateId = $this->WxData[$k]["template"];
//               echo $AppId;
                        $Wxapi = new Wxapi($AppId, $AppSecret);
//               var_dump($data);
                        $url = "http://www.qq.com";
                        if ($data["send_type"] == "custom") {

                            $send = [
                                "type" => "news", //类型
                                "title" => $data["title"], //消息标题
                                "description" => "点击进入查看详情", //图文详情
                                "picurl" => "http://www.abc.com/abc.jpg",
                                "url" => $url,
                            ];
                            $res = $Wxapi->send_custom_message($data["wx_openid"], $send);
                            $type = 1;
                        }
                        $ret = json_decode($res, true);
                        if ($data["send_type"] == "template" or $ret["errcode"] !=0 ) {
                            $template = [
                                "first" => [
                                    "value" => $data["title"],
                                    "color" => "#ff0000"
                                ],
                                "keyword1" => [
                                    "value" => "服务消息",
                                    "color" => "#ff0000"
                                ],
                                "keyword2" => [
                                    "value" => date('Y-m-d H:i'),
                                    "color" => "#173177"
                                ],
                                "remark" => [
                                    "value" => "点击进入查看详情",
                                    "color" => "#173177"
                                ],
                            ];
                            $res = $Wxapi->send_template_message($data["wx_openid"], $templateId, $template, $url);
                            $type = 2;
                        }
                        $ret = json_decode($res, true);
                        $log = [
                            "user_id" => $data["id"],
                            "tradelist_id" => $data["tradelist_id"],
                            "room_id" => $data["room_id"],
                            "log" => $res,
                            "errcode" => $ret["errcode"],
                            "add_time" => time(),
                            "type" => $type,
                        ];
                        $this->DB->insert("sz_queue_log", $log);


                    }
                }
            }

        }

    }
}


$obj = new Index();

mysql.php

<?php
/**
 * Mysql.php
 * User: Administrator
 * Date: 2019/4/4
 * Time: 13:19
 */

namespace Mysql;


class Mysql
{
    public $DB;
    //构造函数,获取Access Token
    public function __construct()
    {
        $dbms = 'mysql';     //数据库类型
        $host = '127.0.0.1'; //数据库主机名
        $dbName = '127.0.0.1';    //使用的数据库
        $user = 'root';      //数据库连接用户名
        $pass = '123456';          //对应的密码
        $dsn = "$dbms:host=$host;dbname=$dbName";
        return self::initConnect($dsn, $user, $pass);
    }
    protected function initConnect($dsn, $user, $pass){
        if ( !$this->DB ) $this->DB = $this->connect($dsn, $user, $pass);
        return $this->DB;
    }
    public function connect($dsn, $user, $pass){
        $this->DB = new \PDO($dsn, $user, $pass, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
        try
        {
            $this->DB->query("SELECT 1");
            echo "ok";
        }
        catch (\PDOException $e){
            $this->DB = new \PDO($dsn, $user, $pass, array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
        }
        return $this->DB;
    }

    /**
     * 插入数据
     * @param $table 数据表
     * @param $data 数据数组
     * @return mixed 插入ID
     */
    public function insert($table, $data)
    {
        foreach ($data as $key => $value) {
            $data[$key] = $value;
        }
        $keys = '`' . implode('`,`', array_keys($data)) . '`';
        $values = '\'' . implode("','", array_values($data)) . '\'';
        $sql = "INSERT INTO {$table}( {$keys} )VALUES( {$values} )";
        $this->DB->query($sql);
        return $this->mysqli->insert_id;
    }

}

Wxapi.php

<?php
/**
 *Wxapi.php.
 * User: Administrator
 * Date: 2019/4/4
 * Time: 10:15
 */

namespace Weixin;

class Wxapi
{
    public $appid  ;
    public $appsecret ;
    public $WxData;
    //构造函数,获取Access Token
    public function __construct($Appid = NULL, $Appsecret = NULL)
    {


        if($Appid && $Appsecret){
            $this->appid = $Appid;
            $this->appsecret = $Appsecret;
            // echo  $this->appid ."[]".  $this->appsecret ;
            //3. 本地写入
            $res = file_get_contents('/www/Queue/Weixin/json/'.$Appid.'.json');
            $result = json_decode($res, true);
            $this->expires_time = $result["expires_time"];
            $this->access_token = $result["access_token"];
            if (time() > ($this->expires_time + 7000)){
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
                // file_put_contents('./url.php',$url);
                $res = $this->http_request($url);
                $result = json_decode($res, true);

                $this->access_token = $result["access_token"];
                $this->expires_time = time();
                file_put_contents('/www/Queue/Weixin/json/'.$Appid.'.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->expires_time.'}');
            }
        }
    }
    //发送模版消息
    public function send_template_message($touser,$template_id,$data,$url){
        $msg = array('touser' =>$touser);
        $msg["template_id"] = $template_id;
        $msg["topcolor"] ="#FF0000";
        $msg["data"] = $data;
        $msg["url"] = $url;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
        return $this->http_request($url, urldecode(json_encode($msg)));
    }
    //发送客服消息
    public function send_custom_message($touser,  $data)
    {
        $msg = ['touser' =>$touser,
                'msgtype' => "news",
                'news'    => [
                    "articles" => [$data],
                ]
        ];

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
        return $this->http_request($url, urldecode(json_encode($msg,320)));
    }
    //HTTP请求(支持HTTP/HTTPS,支持GET/POST)
    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

PHP原生socket与Websocket握手、解码、加码
« 上一篇 04-01
价值1200元的抖音“矩阵营销”课程(持续更新)
下一篇 » 04-10

发表评论

1 条回复
  1. 文章不错非常喜欢