如何利用微信小程序和php實(shí)現(xiàn)即時(shí)通訊聊天功能
一、PHP7安裝Swoole擴(kuò)展
PHP swoole 擴(kuò)展下載地址
Github:https://github.com/swoole/swoole-src/tags
php官方擴(kuò)展庫(kù):http://pecl.php.net/package/swoole
開(kāi)源中國(guó):http://git.oschina.net/swoole/swoole/tags
1、自定義安裝
# 下載 wget https://pecl.php.net/get/swoole-4.3.3.tgz # 解壓 tar zxf swoole-4.3.3.tgz # 編譯安裝擴(kuò)展 # 進(jìn)入目錄 cd swoole-4.3.3 # 執(zhí)行phpize命令,產(chǎn)生出configure可執(zhí)行文件 # 如果不知道phpize路徑在哪里 可以使用which phpize查看相應(yīng)路徑 /usr/bin/phpize # 進(jìn)行配置 如果不知道php-config路徑在哪里 可以使用which php-config 查看相應(yīng)路徑 ./configure --with-php-config=/usr/bin/php-config # 編譯和安裝 make && make install vi /etc/php.ini 復(fù)制如下代碼 extension=swoole.so 放到你所打開(kāi)或新建的文件中即可,無(wú)需重啟任何服務(wù) # 查看擴(kuò)展是否安裝成功 php -m|grep swoole
2、寶塔面板安裝PHP swoole擴(kuò)展
如果感覺(jué)上述安裝較為復(fù)雜,可以使用寶塔面板實(shí)現(xiàn)一鍵安裝
二、配置nginx反向代理
1、使用xshell連接遠(yuǎn)程阿里云服務(wù)器
2、使用命令(find / -name nginx.conf)查找nginx.conf所在的配置文件
3、使用命令(vim /etc/nginx/nginx.conf)查找進(jìn)入到vim編輯器
查看到可以引入/etc/nginx/conf.d/下的配置文件信息
4、使用命令(cd /etc/nginx/conf.d/)進(jìn)入到該路徑下,并新建配置文件:study.lishuo.net.conf
5、配置nginx反向代理,實(shí)現(xiàn)訪問(wèn)study.lishuo.net域名轉(zhuǎn)發(fā)端口號(hào)到127.0.0.1:9511也就是轉(zhuǎn)發(fā)到webscoket運(yùn)行的端口號(hào)
# 反向代理的規(guī)則 study 這個(gè)名字自己隨便起 upstream study{ server 127.0.0.1:9511; } server { listen 80; server_name study.lishuo.net; error_page 404 /404.html; location = /404.html { } location / { index index.php index.html index.htm; if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; } #wss配置 client_max_body_size 100m; proxy_redirect off; proxy_set_header Host $host;# http請(qǐng)求的主機(jī)域名 proxy_set_header X-Real-IP $remote_addr;# 遠(yuǎn)程真實(shí)IP地址 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#反向代理之后轉(zhuǎn)發(fā)之前的IP地址 proxy_read_timeout 604800s;#websocket心跳時(shí)間,默認(rèn)是60s proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_pass http://study; } error_page 500 502 503 504 /50x.html; location = /50x.html { } #添加下列信息,配置Nginx通過(guò)fastcgi方式處理您的PHP請(qǐng)求。 location ~ .php$ { fastcgi_pass 127.0.0.1:9001; #Nginx通過(guò)本機(jī)的9000端口將PHP請(qǐng)求轉(zhuǎn)發(fā)給PHP-FPM進(jìn)行處理。 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; #Nginx調(diào)用fastcgi接口處理PHP請(qǐng)求。 } }
三、微信小程序socket合法域名配置
1、登錄到微信開(kāi)放平臺(tái)https://mp.weixin.qq.com/
2、開(kāi)發(fā)=>開(kāi)發(fā)管理=>開(kāi)發(fā)設(shè)置,完成合法域名設(shè)置
3、到此配置已經(jīng)完成了,接下來(lái)就是功能實(shí)現(xiàn)了,微信小程序+PHP代碼
四、效果演示和代碼
1、小程序端代碼
小程序頁(yè)面代碼所在路徑 /pages/contact/contact.wxml
<!--pages/contact/contact.wxml--> <view> <scroll-view scroll-y scroll-into-view='{{toView}}' style='height: {{scrollHeight}};'> <!-- <view class='scrollMsg'> --> <block wx:key wx:for='{{msgList}}' wx:for-index="index"> <!-- 單個(gè)消息1 客服發(fā)出(左) --> <view wx:if='{{item.speaker=="server"}}' id='msg-{{index}}' style='display: flex; padding: 2vw 11vw 2vw 2vw;'> <view style='width: 11vw; height: 11vw;'> <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://cdn.pixabay.com/photo/2020/02/10/12/47/girl-4836394__340.jpg'></image> </view> <view style='width: 4vw; height: 11vw; margin-left: 0.5vw; display: flex; align-items: center; z-index: 9;'> <view class="triangle_border_left"></view> </view> <view class='leftMsg'>{{item.content}}</view> </view> <!-- 單個(gè)消息2 用戶(hù)發(fā)出(右) --> <view wx:else id='msg-{{index}}' style='display: flex; justify-content: flex-end; padding: 2vw 2vw 2vw 11vw;'> <view class='rightMsg'>{{item.content}}</view> <view style='width: 4vw; height: 11vw; margin-right: 0.5vw; display: flex; align-items: center; z-index: 9;'> <view class="triangle_border_right"></view> </view> <view style='width: 11vw; height: 11vw;'> <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://cdn.pixabay.com/photo/2021/09/24/10/00/chick-6652163__340.jpg'></image> </view> </view> </block> <!-- </view> --> <!-- 占位 --> <view style='width: 100%; height: 18vw;'></view> </scroll-view> <view class='inputRoom' style='bottom: {{inputBottom}}'> <image style='width: 7vw; margin-left: 3.2vw;' src='https://img95.699pic.com/element/40030/6429.png_300.png' mode='widthFix'></image> <input bindconfirm='sendClick' adjust-position='{{false}}' value='{{inputVal}}' confirm-type='send' bindfocus='focus' bindblur='blur'></input> </view> </view>
2、小程序頁(yè)面樣式代碼所在路徑 /pages/contact/contact.wxss
/* pages/contact/contact.wxss */ page { background-color: #f1f1f1; } .inputRoom { width: 100vw; height: 16vw; border-top: 1px solid #cdcdcd; background-color: #f1f1f1; position: fixed; bottom: 0; display: flex; align-items: center; z-index: 20; } input { width: 76vw; height: 9.33vw; background-color: #fff; border-radius: 40rpx; margin-left: 2vw; padding: 0 3vw; font-size: 28rpx; color: #444; } .leftMsg { font-size: 35rpx; color: #444; line-height: 7vw; padding: 2vw 2.5vw; background-color: #fff; margin-left: -1.6vw; border-radius: 10rpx; z-index: 10; } .rightMsg { font-size: 35rpx; color: #444; line-height: 7vw; padding: 2vw 2.5vw; background-color: #96EB6A; margin-right: -1.6vw; border-radius: 10rpx; z-index: 10; } /*向左*/ .triangle_border_left { width: 0; height: 0; border-width: 10px 30px 30px 0; border-style: solid; border-color: transparent #fff transparent transparent; /*透明 黃 透明 透明 */ margin: 40px auto; position: relative; } /*向右*/ .triangle_border_right { width: 0; height: 0; border-width: 0px 30px 20px 13px; border-style: solid; border-color: transparent transparent transparent #96EB6A; /*透明 透明 透明 黃*/ margin: 40px auto; position: relative; }
小程序配置文件代碼所在路徑 /pages/contact/contact.json
{ "navigationBarTitleText":"柯作客服", "usingComponents": { } }
小程序業(yè)務(wù)邏輯代碼所在路徑 /pages/contact/contact.js
// pages/contact/contact.js const app = getApp(); var inputVal = ''; var msgList = []; var windowWidth = wx.getSystemInfoSync().windowWidth; var windowHeight = wx.getSystemInfoSync().windowHeight; var keyHeight = 0; /** * 初始化數(shù)據(jù) */ function initData(that) { //輸入框的內(nèi)容 inputVal = ''; //消息列表,包含客服和用戶(hù)的聊天內(nèi)容 msgList = [{ speaker: 'server', contentType: 'text', content: 'Hi,親愛(ài)的小主,終于等到您啦!歡迎來(lái)到柯作店鋪,很榮幸為您服務(wù)。' }, { speaker: 'customer', contentType: 'text', content: '你高興的太早了' } ] that.setData({ msgList, inputVal }) } Page({ /** * 頁(yè)面的初始數(shù)據(jù) */ data: { scrollHeight: '100vh', inputBottom: 0 }, /** * 生命周期函數(shù)--監(jiān)聽(tīng)頁(yè)面加載 */ onLoad: function(options) { //初始化websocket連接 this.chat(); //監(jiān)聽(tīng)心跳的方法 this.webSocketXin(); //聊天方法 initData(this); //監(jiān)聽(tīng)消息 wx.onSocketMessage(res=>{ //追加到消息列表里 msgList.push(JSON.parse(res.data)) inputVal = ''; this.setData({ msgList, inputVal }); }) }, //頁(yè)面卸載時(shí)間 onUnload(){ wx.closeSocket(); }, /** * 獲取聚焦 */ focus: function(e) { keyHeight = e.detail.height; this.setData({ scrollHeight: (windowHeight - keyHeight) + 'px' }); this.setData({ toView: 'msg-' + (msgList.length - 1), inputBottom: keyHeight + 'px' }) //計(jì)算msg高度 // calScrollHeight(this, keyHeight); }, //失去聚焦(軟鍵盤(pán)消失) blur: function(e) { this.setData({ scrollHeight: '100vh', inputBottom: 0 }) this.setData({ toView: 'msg-' + (msgList.length - 1) }) }, /** * 發(fā)送點(diǎn)擊監(jiān)聽(tīng) */ sendClick: function(e) { //客戶(hù)發(fā)的信息 let customerMsg = { uid: 10, speaker: 'customer', contentType: 'text', content: e.detail.value }; //關(guān)閉心跳包 this.webSocketXin(60000, false) //發(fā)送給websocket wx.sendSocketMessage({ data: JSON.stringify(customerMsg), success:res=>{ //重啟心跳包 this.webSocketXin(40000, true) } }) //追加到消息列表里 msgList.push(customerMsg) inputVal = ''; this.setData({ msgList, inputVal }); }, /** * 退回上一頁(yè) */ toBackClick: function() { wx.navigateBack({}) }, /** * websocket */ chat(){ //進(jìn)行連接php的socket wx.connectSocket({ //wss 協(xié)議相當(dāng)于你要有一個(gè)ssl證書(shū),https //ws 就相當(dāng)于不實(shí)用證書(shū) http url: 'ws://study.lishuo.net', success: function () { console.log('websocket連接成功~') }, fail: function () { console.log('websocket連接失敗~') } }) }, /** * 監(jiān)聽(tīng)websocket心跳連接的方法 */ webSocketXin(time=60000,status=true){ var timing; if(status == true){ timing = setInterval(function () { console.log("當(dāng)前心跳已重新連接"); //循環(huán)執(zhí)行代碼 wx.sendSocketMessage({ data: JSON.stringify({ type: 'active' }), fail(res) { //關(guān)閉連接 wx.closeSocket(); //提示 wx.showToast({ title: '當(dāng)前聊天已斷開(kāi)', icon:'none' }) clearInterval(timing); console.log("當(dāng)前心跳已關(guān)閉"); } }); }, time) //循環(huán)時(shí)間,注意不要超過(guò)1分鐘 } else { //關(guān)閉定時(shí)器 clearInterval(timing); console.log("當(dāng)前心跳已關(guān)閉"); } } })
2、服務(wù)端代碼(PHP代碼)
wechat_websocket.php
<?php //創(chuàng)建WebSocket Server對(duì)象,監(jiān)聽(tīng)0.0.0.0:9502端口 $ws = new Swoole\WebSocket\Server('0.0.0.0', 9511); //監(jiān)聽(tīng)WebSocket連接打開(kāi)事件 $ws->on('Open', function ($ws, $request) { echo $request->fd . '我連接上了'; }); //監(jiān)聽(tīng)WebSocket消息事件 $ws->on('Message', function ($ws, $frame) { //把前臺(tái)傳過(guò)來(lái)的json字符串轉(zhuǎn)成數(shù)組 $params = json_decode($frame->data, true); //判斷是否是心跳消息,如果是心跳消息 if (isset($params['type']) && isset($params['type'])=='active'){ echo '這是心跳監(jiān)聽(tīng)消息'; }else{ //先判斷當(dāng)前用戶(hù)有沒(méi)有正在連接 if (isset($params['uid']) && !empty($params['uid'] == 666)) { //去用戶(hù)表查詢(xún)當(dāng)前用戶(hù) fd $fd = 2; } else { $fd = 1; } //客服id $ws->push($fd, json_encode($params, JSON_UNESCAPED_UNICODE)); } }); //監(jiān)聽(tīng)WebSocket連接關(guān)閉事件 $ws->on('Close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start();
五、代碼已經(jīng)編寫(xiě)完了
1、把服務(wù)端代碼上傳到Linux操作系統(tǒng)里
2、然后切到該目錄下進(jìn)行運(yùn)行php wechat_websocket.php
總結(jié)
到此這篇關(guān)于如何利用微信小程序和php實(shí)現(xiàn)即時(shí)通訊聊天功能的文章就介紹到這了,更多相關(guān)微信小程序 php即時(shí)通訊聊天內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python實(shí)現(xiàn)簡(jiǎn)單的聊天小程序
- 微信小程序?qū)崿F(xiàn)聊天室功能
- 微信小程序?qū)崿F(xiàn)聊天室
- 小程序?qū)崿F(xiàn)簡(jiǎn)單語(yǔ)音聊天的示例代碼
- 微信小程序聊天功能的示例代碼
- 微信小程序websocket實(shí)現(xiàn)即時(shí)聊天功能
- 微信小程序視頻彈幕發(fā)送功能的實(shí)現(xiàn)
- 微信小程序?qū)崿F(xiàn)發(fā)送模板消息功能示例【通過(guò)openid推送消息給用戶(hù)】
- 微信小程序發(fā)送短信驗(yàn)證碼完整實(shí)例
- 微信小程序?qū)崿F(xiàn)聊天界面發(fā)送功能(示例代碼)
相關(guān)文章
TP5(thinkPHP5)框架基于ajax與后臺(tái)數(shù)據(jù)交互操作簡(jiǎn)單示例
這篇文章主要介紹了TP5(thinkPHP5)框架基于ajax與后臺(tái)數(shù)據(jù)交互操作,結(jié)合實(shí)例形式分析了thinkPHP5前端基于jQuery的ajax數(shù)據(jù)提交及后臺(tái)數(shù)據(jù)接收、處理相關(guān)操作技巧,需要的朋友可以參考下2018-09-09laravel5.4利用163郵箱發(fā)送郵件的步驟詳解
發(fā)送郵件是我們?nèi)粘T陂_(kāi)發(fā)中必不可少會(huì)遇到的一個(gè)需求,下面這篇文章主要給大家介紹了關(guān)于laravel5.4利用163郵箱發(fā)送郵件的步驟,文中通過(guò)示例代碼和圖片介紹的非常詳細(xì),需要的朋友可以參考下。2017-09-09談?wù)勀銓?duì)Zend SAPIs(Zend SAPI Internals)的理解
這篇文章主要介紹了談?wù)勀銓?duì)Zend SAPIs(Zend SAPI Internals)的理解的相關(guān)資料,需要的朋友可以參考下2015-11-11php設(shè)計(jì)模式之抽象工廠模式分析【星際爭(zhēng)霸游戲案例】
這篇文章主要介紹了php設(shè)計(jì)模式之抽象工廠模式,結(jié)合星際爭(zhēng)霸游戲案例形式分析了PHP抽象工廠模式的具體原理、使用技巧與相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2020-01-01CI(CodeIgniter)框架實(shí)現(xiàn)圖片上傳的方法
這篇文章主要介紹了CI(CodeIgniter)框架實(shí)現(xiàn)圖片上傳的方法,結(jié)合實(shí)例形式分析了基于CodeIgniter調(diào)用文件上傳類(lèi)實(shí)現(xiàn)圖片上傳功能的相關(guān)操作技巧,需要的朋友可以參考下2017-03-03php實(shí)現(xiàn)12306余票查詢(xún)、價(jià)格查詢(xún)示例
這篇文章主要介紹了php實(shí)現(xiàn)12306余票查詢(xún)、價(jià)格查詢(xún)示例的相關(guān)資料2014-04-04