swoole结合微信公众号号做微信扫码登录

微信公众号的账号申请和设置

申请测试账号

点击这里

file

设置路由和token验证

路由

这里一定要设置成any方式

Route::any('/wechat', 'WeChatController@serve')->name('wx.serve');

安装"overtrue/laravel-wechat": "~4.0"扩展包,并设置

/*
 * 公众号
 */
 // config/wechat.php
'official_account' => [
    'default' => [
        'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', 'your-app-id'),         // AppID
        'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', 'your-app-secret'),    // AppSecret
        'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN', 'your-token'),           // Token
        'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY', ''),  

//设置.env中
WECHAT_OFFICIAL_ACCOUNT_APPID=xxxx
WECHAT_OFFICIAL_ACCOUNT_SECRET=xxxx
WECHAT_OFFICIAL_ACCOUNT_TOKEN=xxxx

token验证代码点这里看公众平台申请测试账号提交token验证

swoole设置

创建websocket服务,点这里查看artisan命令启动服务

这里我用的是laravel的artisan启动的

$this->server = new swoole_websocket_server("0.0.0.0", 10003);

$handle = app()->make(WeChatController::class);

$this->server->on('open',array($handle,'onOpen'));
$this->server->on('message',array($handle,'onMessage'));
$this->server->on('close',array($handle,'onClose'));
$this->server->start();

onOpen事件代码

public function onOpen ($server, $request)
{
    $fd = $request->fd;
    //生成日志,大家可以不用管
    $this->logObj = (new LogHandle())->setPath(storage_path('logs/barrage'))->setName('barrage');
    //实例化微信
    $app = Factory::officialAccount(config('wechat.official_account.default'));
    //设置一个过期时间,一个二维码120秒过期
    $result = $app->qrcode->temporary($fd, 120);
    //获得二维码url
    $url = $app->qrcode->url($result['ticket']);
    //给当前客户端推送消息
    $server->push($fd, json_encode([
        'type' => 'qrcode_url',
        'url'  => $url
    ]));
}

启动websocket

php artisan swoole:wx_scan_login start

如果你想常驻可以两种方法

  • 设置swoole常驻

    $this->server->set([
    'daemonize' => 1
    ]);
  • 使用supervisor

nginx配置

nginx设置upstream

我们上面是设置的10003端口,所以就转发到10003

upstream wx_login {
    server 127.0.0.1:10003;
}
//.............
location = /ws/wx_login {  
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_redirect off;
        proxy_read_timeout 300s;
        #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #proxy_set_header Host $http_host;
        proxy_pass http://wx_login;
} 

重启nginx

nginx -s reload

登录页面链接socket


<script>
        $(function () {
            connect()
            // send('{"key":100}');
        })

        // 连接服务端
        function connect() {
            // 创建websocket
            ws = new WebSocket("wss://iluoy.com/ws/wx_login");
            // ws.onopen = onopen;
            ws.onmessage = onmessage;
            ws.onclose = function () {
                console.log("连接关闭,定时重连");
                connect();
            };
            ws.onerror = function () {
                console.log("出现错误");
            };
        }

        /**
         * socket服务器有消息来时
         */
        function onmessage(response) {
            var data = eval("(" + response.data + ")");
            if (data.type == 'qrcode_url') {
                $('#qrcode_url').attr('src', data.url)
            }
            if (data.type == 'scan_success') {
                console.log(data)
                self.location = data.redirect_url;
            }
        }
</script>

设置微信回调代码

设置addListener监听

登录时给设置的addListener监听发送消息

生成登录跳转路由,完成自动登录