thinkphp使用easywechat接入微信公众号

一、安装easyWeChat

easyWeChat 文档 : 

https://www.easywechat.com/docs/4.1/overview

使用composer下载

composer require overtrue/wechat:~4.0 -vvv

或者直接下载源码放到 extend下

 二、引入

use EasyWeChat\Factory;

easywechat配置:  根据需要设置

$config=[
            /**
             * Debug 模式,bool 值:true/false
             *
             * 当值为 false 时,所有的日志都不会记录
             */
            'debug'  => false,
            /**
             * 账号基本信息,请从微信公众平台/开放平台获取
             */
            'app_id'  => 'wxc0330dcea9e9a',         // AppID
            'secret'  => 'c96af0236069b',     // AppSecret
            'token'   => 'mytest',          // Token
            'aes_key' => 'i0MbeyhX8lp5tlL7hRCjbLo2GdVNqCD3h7DcmFJmnGU',
            'response_type' => 'array',
            /**
             * 日志配置
             *
             * level: 日志级别, 可选为:
             *         debug/info/notice/warning/error/critical/alert/emergency
             * permission:日志文件权限(可选),默认为null(若为null值,monolog会取0644)
             * file:日志文件位置(绝对路径!!!),要求可写权限
             */
            'log' => [
                'level'      => 'debug',
                'permission' => 0777,
                'file'       => '/tmp/easywechat.log',
            ],
            /**
             * OAuth 配置
             *
             * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
             * callback:OAuth授权完成后的回调页地址
             */
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/user/wechat/oauth_callback',
            ],
            /**
             * 微信支付
             */


            'payment' => [
                'merchant_id'        => '135*****602',
                'key'                => '80b8682*****8fdac7784',
                'cert_path'          => ROOT_PATH . 'public/certs/wechat/apiclient_cert.pem', // XXX: 绝对路径!!!!
                'key_path'           => ROOT_PATH . 'public/certs/wechat/apiclient_key.pem',      // XXX: 绝对路径!!!!
                'notify_url'       => 'http://*******/notify/wxpay',
            ],
            /**
             * Guzzle 全局设置
             *
             * 更多请参考: http://docs.guzzlephp.org/en/latest/request-options.html
             */
            'guzzle' => [
                'timeout' => 3.0, // 超时时间(秒)
                'verify' => false, // 关掉 SSL 认证(强烈不建议!!!)
            ],
        ];
        return $config;
    }

三、接入步骤

1.首次接入验证

此处用数据库保存的token对微信提交的参数进行验签比对,如果不需要验证token验证的话直接原样输出

echostr 即可接入
 //微信首次接入验证
        if (!empty($_GET['echostr']) && $this->checkSignature($_W['config']['token'])) {
            header('content-type:text');
            echo $_GET['echostr'];
            exit;
        }

/*
     * 接入验签
     */
    private function checkSignature($token)
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

2.消息处理

根据消息类型交给不同模块去处理,只回复字符串的话直接return就好,其他类型消息需要进一步装配,详细参见文档。

public function index(Request $request)
    {
        global $_W;
        $app = Factory::officialAccount($_W['config']);

        $app->server->push(function ($message) {
            global $_W;
            $memberModel = new Members();
            $_W['user'] = $memberModel->getInfoByOpenidAndUniacid($message['FromUserName'], $_W['uniacid']);//用户信息
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型:event, text....
            $handler = new MessageHandler($message);
            switch ($message['MsgType']) {
                case 'event':
                    //return '收到事件消息';
                    return $handler->eventHandler($message['FromUserName']);
                    break;
                case 'text':
                    //return '收到文字消息';
                    return $handler->textHandler();
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    //return '收到坐标消息';
                    return $handler->test();
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        $response = $app->server->serve();
        $response->send();
}

messageHandler

  具体处理各种消息,

class MessageHandler
{
    /*
    * 消息对象
    */

    private $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    /*
     * 事件响应函数
     */
    public function eventHandler($openid)
    {
        // $message['FromUserName'] // 用户的 openid
        // $message['MsgType'] // 消息类型:event, text....
        global $_W;
        switch ($this->message['Event']) {
            //关注事件
            case 'subscribe':
                return $this->focusEvent($openid, $_W['auid']);
                break;
            //取消关注事件
            case 'unsubscribe':
                return '取关';
                break;
            //点击事件
            case 'CLICK':
                if ($this->message['EventKey'] == 'sign') {
                    $res = $this->signEvent($openid);
                    $SignModel = new Signs();
                    $SignModel->SignEventFun($openid,$_W['auid']);
                    return $res;
                }
                return '取关';
                break;
            default:
                return '收到其它消息';
                break;
        }
    }
}

发送模板消息

$app = Factory::officialAccount($_W['config']);
        $res = $app->template_message->send([
            'touser' => 'oWsdC5tt9ZXVn8YkK2ZvsHDGw',
            'template_id' => '2ujQBy5j1od8JzKfuvZvhTzX',
            'url' => 'https://easywechat.org',
            'data' => [
                'key1' => 'VALUE',
                'key2' => 'VALUE2',
            ],
        ]);

图文消息

use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
$items = [
                new NewsItem([
                    'title' => $replayInfo->book_name,
                    'description' => $replayInfo->introduction,
                    'url' => $url,
                    'image' => $replayInfo->book_flash,
                ]),
            ];
            return new News($items);

客服消息 

    /**
     * Notes:发送模板消息
     * @author:xxf
     * Date: 2018-06-02
     * Time: 15:11
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function sendTplMessage($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
    {

        $config= $this->config();
        $app = Factory::officialAccount($config);
        $app->template_message->send([
            'touser' => $touser,
            'template_id' => $template_id,
            'topcolor' => $topcolor,
            'url' => $url,
            'data' => $data,
        ]);
            return true;

    }

    /**
     * Notes:发送客服消息
     * @author:xxf
     * Date: 2018-06-04
     * Time: 14:15
     * @param $touser
     * @param $data
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function sendMessage($touser,$msg, $url)
    {

        $config= $this->config();
        $app = Factory::officialAccount($config);
        if (!empty($url)) {
            $msg .= '点击查看详情';
        }
        $message = new Text($msg);
        $app->customer_service->message($message)->to($touser)->send();
        return true;
    }

 

你可能感兴趣的:(微信公众号,php)