PHP+Swoole實現微信小程式客服即時通訊聊天功能
一、PHP7安裝Swoole擴充套件
PHP swoole 擴充套件下載地址
Github:https://github.com/swoole/swoole-src/tags
php官方擴充套件庫:http://pecl.php.net/package/swoole
開源中國: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
# 編譯安裝擴充套件
# 進入目錄
cd swoole-4.3.3
# 執行phpize命令,產生出configure可執行檔案
# 如果不知道phpize路徑在哪裡 可以使用which phpize檢視相應路徑
/usr/bin/phpize
# 進行配置 如果不知道php-config路徑在哪裡 可以使用which php-config 檢視相應路徑
./configure --with-php-config=/usr/bin/php-config
# 編譯和安裝
make && make install
vi /etc/php.ini
複製如下程式碼
extension=swoole.so
放到你所開啟或新建的檔案中即可,無需重啟任何服務
# 檢視擴充套件是否安裝成功
php -m|grep swoole
二、配置nginx反向代理
1、使用xshell連線遠端阿里雲伺服器
2、使用命令(find / -name nginx.conf)查詢nginx.conf所在的配置檔案
3、使用命令(vim /etc/nginx/nginx.conf)查詢進入到vim編輯器
檢視到可以引入/etc/nginx/conf.d/
下的配置檔案資訊
4、使用命令(cd /etc/nginx/conf.d/)進入到該路徑下,並新建配置檔案:study.lishuo.net.conf
5、配置nginx反向代理,實現訪問study.lishuo.net
域名轉發埠號到127.0.0.1:9511
也就是轉發到webscoket執行的埠號
# 反向代理的規則 study 這個名字自己隨便起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請求的主機域名 proxy_set_header X-Real-IP $remote_addr;# 遠端真實IP地址 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#反向代理之後轉發之前的IP地址 proxy_read_timeout 604800s;#websocket心跳時間,預設是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通過fastcgi方式處理您的PHP請求。 location ~ .php$ { fastcgi_pass 127.0.0.1:9001; #Nginx通過本機的9000埠將PHP請求轉發給PHP-FPM進行處理。 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; #Nginx呼叫fastcgi介面處理PHP請求。 } }
三、微信小程式socket合法域名配置
1、登入到微信開放平臺https://mp.weixin.qq.com/
2、開發=>開發管理=>開發設定,完成合法域名設定
3、到此配置已經完成了,接下來就是功能實現了,微信小程式+PHP程式碼
四、效果演示和程式碼
1、小程式端程式碼
小程式頁面程式碼所在路徑 /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"> <!-- 單個訊息1 客服發出(左) --> <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> <!-- 單個訊息2 使用者發出(右) --> <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>
小程式頁面樣式程式碼所在路徑 /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": { } }
小程式業務邏輯程式碼所在路徑 /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; /** * 初始化資料 */ function initData(that) { //輸入框的內容 inputVal = ''; //訊息列表,包含客服和使用者的聊天內容 msgList = [{ speaker: 'server', contentType: 'text', content: 'Hi,親愛的小主,終於等到您啦!歡迎來到柯作店鋪,很榮幸為您服務。' }, { speaker: 'customer', contentType: 'text', content: '你高興的太早了' } ] that.setData({ msgList, inputVal }) } Page({ /** * 頁面的初始資料 */ data: { scrollHeight: '100vh', inputBottom: 0 }, /** * 生命週期函式--監聽頁面載入 */ onLoad: function(options) { //初始化websocket連線 this.chat(); //監聽心跳的方法 this.webSocketXin(); //聊天方法 initData(this); //監聽訊息 wx.onSocketMessage(res=>{ //追加到訊息列表裡 msgList.push(JSON.parse(res.data)) inputVal = ''; this.setData({ msgList, inputVal }); }) }, //頁面解除安裝時間 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' }) //計算msg高度 // calScrollHeight(this, keyHeight); }, //失去聚焦(軟鍵盤消失) blur: function(e) { this.setData({ scrollHeight: '100vh', inputBottom: 0 }) this.setData({ toView: 'msg-' + (msgList.length - 1) }) }, /** * 傳送點選監聽 */ sendClick: function(e) { //客戶發的資訊 let customerMsg = { uid: 10, speaker: 'customer', contentType: 'text', content: e.detail.value }; //關閉心跳包 this.webSocketXin(60000, false) //傳送給websocket wx.sendSocketMessage({ data: JSON.stringify(customerMsg), success:res=>{ //重啟心跳包 this.webSocketXin(40000, true) } }) //追加到訊息列表裡 msgList.push(customerMsg) inputVal = ''; this.setData({ msgList, inputVal }); }, /** * 退回上一頁 */ toBackClick: function() { wx.navigateBack({}) }, /** * websocket */ chat(){ //進行連線php的socket wx.connectSocket({ //wss 協議相當於你要有一個ssl證書,https //ws 就相當於不實用證書 http url: 'ws://study.lishuo.net', success: function () { console.log('websocket連線成功~') }, fail: function () { console.log('websocket連線失敗~') } }) }, /** * 監聽websocket心跳連線的方法 */ webSocketXin(time=60000,status=true){ var timing; if(status == true){ timing = setInterval(function () { console.log("當前心跳已重新連線"); //迴圈執行程式碼 wx.sendSocketMessage({ data: JSON.stringify({ type: 'active' }), fail(res) { //關閉連線 wx.closeSocket(); //提示 wx.showToast({ title: '當前聊天已斷開', icon:'none' }) clearInterval(timing); console.log("當前心跳已關閉"); } }); }, time) //迴圈時間,注意不要超過1分鐘 } else { //關閉定時器 clearInterval(timing); console.log("當前心跳已關閉"); } } })
2、服務端程式碼(PHP程式碼)
wechat_websocket.php
<?php //建立WebSocket Server物件,監聽0.0.0.0:9502埠 $ws = new Swoole\WebSocket\Server('0.0.0.0', 9511); //監聽WebSocket連線開啟事件 $ws->on('Open', function ($ws, $request) { echo $request->fd . '我連線上了'; }); //監聽WebSocket訊息事件 $ws->on('Message', function ($ws, $frame) { //把前臺傳過來的json字串轉成陣列 $params = json_decode($frame->data, true); //判斷是否是心跳訊息,如果是心跳訊息 if (isset($params['type']) && isset($params['type'])=='active'){ echo '這是心跳監聽訊息'; }else{ //先判斷當前使用者有沒有正在連線 if (isset($params['uid']) && !empty($params['uid'] == 666)) { //去使用者表查詢當前使用者 fd $fd = 2; } else { $fd = 1; } //客服id $ws->push($fd, json_encode($params, JSON_UNESCAPED_UNICODE)); } }); //監聽WebSocket連線關閉事件 $ws->on('Close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start();
五、程式碼已經編寫完了
1、把服務端程式碼上傳到Linux作業系統裡
2、然後切到該目錄下進行執行php wechat_websocket.php
一、PHP7安裝Swoole擴充套件
PHP swoole 擴充套件下載地址
Github:https://github.com/swoole/swoole-src/tags
php官方擴充套件庫:http://pecl.php.net/package/swoole
開源中國: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
# 編譯安裝擴充套件
# 進入目錄
cd swoole-4.3.3
# 執行phpize命令,產生出configure可執行檔案
# 如果不知道phpize路徑在哪裡 可以使用which phpize檢視相應路徑
/usr/bin/phpize
# 進行配置 如果不知道php-config路徑在哪裡 可以使用which php-config 檢視相應路徑
./configure --with-php-config=/usr/bin/php-config
# 編譯和安裝
make && make install
vi /etc/php.ini
複製如下程式碼
extension=swoole.so
放到你所開啟或新建的檔案中即可,無需重啟任何服務
# 檢視擴充套件是否安裝成功
php -m|grep swoole
2、寶塔面板安裝PHP swoole擴充套件
如果感覺上述安裝較為複雜,可以使用寶塔面板實現一鍵安裝
二、配置nginx反向代理
1、使用xshell連線遠端阿里雲伺服器
2、使用命令(find / -name nginx.conf)查詢nginx.conf所在的配置檔案
3、使用命令(vim /etc/nginx/nginx.conf)查詢進入到vim編輯器
檢視到可以引入/etc/nginx/conf.d/
下的配置檔案資訊
4、使用命令(cd /etc/nginx/conf.d/)進入到該路徑下,並新建配置檔案:study.lishuo.net.conf
5、配置nginx反向代理,實現訪問study.lishuo.net
域名轉發埠號到127.0.0.1:9511
也就是轉發到webscoket執行的埠號
# 反向代理的規則 study 這個名字自己隨便起
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請求的主機域名
proxy_set_header X-Real-IP $remote_addr;# 遠端真實IP地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#反向代理之後轉發之前的IP地址
proxy_read_timeout 604800s;#websocket心跳時間,預設是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通過fastcgi方式處理您的PHP請求。
location ~ .php$ {
fastcgi_pass 127.0.0.1:9001; #Nginx通過本機的9000埠將PHP請求轉發給PHP-FPM進行處理。
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; #Nginx呼叫fastcgi介面處理PHP請求。
}
}
三、微信小程式socket合法域名配置
1、登入到微信開放平臺https://mp.weixin.qq.com/
2、開發=>開發管理=>開發設定,完成合法域名設定
3、到此配置已經完成了,接下來就是功能實現了,微信小程式+PHP程式碼
四、效果演示和程式碼
1、小程式端程式碼
小程式頁面程式碼所在路徑 /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">
<!-- 單個訊息1 客服發出(左) -->
<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>
<!-- 單個訊息2 使用者發出(右) -->
<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>
小程式頁面樣式程式碼所在路徑 /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": {
}
}
小程式業務邏輯程式碼所在路徑 /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;
/**
* 初始化資料
*/
function initData(that) {
//輸入框的內容
inputVal = '';
//訊息列表,包含客服和使用者的聊天內容
msgList = [{
speaker: 'server',
contentType: 'text',
content: 'Hi,親愛的小主,終於等到您啦!歡迎來到柯作店鋪,很榮幸為您服務。'
},
{
speaker: 'customer',
contentType: 'text',
content: '你高興的太早了'
}
]
that.setData({
msgList,
inputVal
})
}
Page({
/**
* 頁面的初始資料
*/
data: {
scrollHeight: '100vh',
inputBottom: 0
},
/**
* 生命週期函式--監聽頁面載入
*/
onLoad: function(options) {
//初始化websocket連線
this.chat();
//監聽心跳的方法
this.webSocketXin();
//聊天方法
initData(this);
//監聽訊息
wx.onSocketMessage(res=>{
//追加到訊息列表裡
msgList.push(JSON.parse(res.data))
inputVal = '';
this.setData({
msgList,
inputVal
});
})
},
//頁面解除安裝時間
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'
})
//計算msg高度
// calScrollHeight(this, keyHeight);
},
//失去聚焦(軟鍵盤消失)
blur: function(e) {
this.setData({
scrollHeight: '100vh',
inputBottom: 0
})
this.setData({
toView: 'msg-' + (msgList.length - 1)
})
},
/**
* 傳送點選監聽
*/
sendClick: function(e) {
//客戶發的資訊
let customerMsg = {
uid: 10,
speaker: 'customer',
contentType: 'text',
content: e.detail.value
};
//關閉心跳包
this.webSocketXin(60000, false)
//傳送給websocket
wx.sendSocketMessage({
data: JSON.stringify(customerMsg),
success:res=>{
//重啟心跳包
this.webSocketXin(40000, true)
}
})
//追加到訊息列表裡
msgList.push(customerMsg)
inputVal = '';
this.setData({
msgList,
inputVal
});
},
/**
* 退回上一頁
*/
toBackClick: function() {
wx.navigateBack({})
},
/**
* websocket
*/
chat(){
//進行連線php的socket
wx.connectSocket({
//wss 協議相當於你要有一個ssl證書,https
//ws 就相當於不實用證書 http
url: 'ws://study.lishuo.net',
success: function () {
console.log('websocket連線成功~')
},
fail: function () {
console.log('websocket連線失敗~')
}
})
},
/**
* 監聽websocket心跳連線的方法
*/
webSocketXin(time=60000,status=true){
var timing;
if(status == true){
timing = setInterval(function () {
console.log("當前心跳已重新連線");
//迴圈執行程式碼
wx.sendSocketMessage({
data: JSON.stringify({
type: 'active'
}),
fail(res) {
//關閉連線
wx.closeSocket();
//提示
wx.showToast({
title: '當前聊天已斷開',
icon:'none'
})
clearInterval(timing);
console.log("當前心跳已關閉");
}
});
}, time) //迴圈時間,注意不要超過1分鐘
} else {
//關閉定時器
clearInterval(timing);
console.log("當前心跳已關閉");
}
}
})
2、服務端程式碼(PHP程式碼)
wechat_websocket.php
//建立WebSocket Server物件,監聽0.0.0.0:9502埠
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9511);
//監聽WebSocket連線開啟事件
$ws->on('Open', function ($ws, $request) {
echo $request->fd . '我連線上了';
});
//監聽WebSocket訊息事件
$ws->on('Message', function ($ws, $frame) {
//把前臺傳過來的json字串轉成陣列
$params = json_decode($frame->data, true);
//判斷是否是心跳訊息,如果是心跳訊息
if (isset($params['type']) && isset($params['type'])=='active'){
echo '這是心跳監聽訊息';
}else{
//先判斷當前使用者有沒有正在連線
if (isset($params['uid']) && !empty($params['uid'] == 666)) {
//去使用者表查詢當前使用者 fd
$fd = 2;
} else {
$fd = 1;
}
//客服id
$ws->push($fd, json_encode($params, JSON_UNESCAPED_UNICODE));
}
});
//監聽WebSocket連線關閉事件
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
五、程式碼已經編寫完了
1、把服務端程式碼上傳到Linux作業系統裡
2、然後切到該目錄下進行執行php wechat_websocket.php