如何利用微信小程序和php實現(xiàn)即時通訊聊天功能
一、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 # 執(zhí)行phpize命令,產(chǎn)生出configure可執(zhí)行文件 # 如果不知道phpize路徑在哪里 可以使用which phpize查看相應(yīng)路徑 /usr/bin/phpize # 進行配置 如果不知道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 放到你所打開或新建的文件中即可,無需重啟任何服務(wù) # 查看擴展是否安裝成功 php -m|grep swoole
2、寶塔面板安裝PHP swoole擴展
如果感覺上述安裝較為復(fù)雜,可以使用寶塔面板實現(xiàn)一鍵安裝

二、配置nginx反向代理
1、使用xshell連接遠程阿里云服務(wù)器
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反向代理,實現(xiàn)訪問study.lishuo.net域名轉(zhuǎn)發(fā)端口號到127.0.0.1:9511也就是轉(zhuǎn)發(fā)到webscoket運行的端口號
# 反向代理的規(guī)則 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;#反向代理之后轉(zhuǎn)發(fā)之前的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請求轉(zhuǎn)發(fā)給PHP-FPM進行處理。
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; #Nginx調(diào)用fastcgi接口處理PHP請求。
}
}三、微信小程序socket合法域名配置
1、登錄到微信開放平臺https://mp.weixin.qq.com/
2、開發(fā)=>開發(fā)管理=>開發(fā)設(shè)置,完成合法域名設(shè)置

3、到此配置已經(jīng)完成了,接下來就是功能實現(xiàn)了,微信小程序+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 客服發(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>
<!-- 單個消息2 用戶發(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、小程序頁面樣式代碼所在路徑 /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 = '';
//消息列表,包含客服和用戶的聊天內(nèi)容
msgList = [{
speaker: 'server',
contentType: 'text',
content: 'Hi,親愛的小主,終于等到您啦!歡迎來到柯作店鋪,很榮幸為您服務(wù)。'
},
{
speaker: 'customer',
contentType: 'text',
content: '你高興的太早了'
}
]
that.setData({
msgList,
inputVal
})
}
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
scrollHeight: '100vh',
inputBottom: 0
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function(options) {
//初始化websocket連接
this.chat();
//監(jiān)聽心跳的方法
this.webSocketXin();
//聊天方法
initData(this);
//監(jiān)聽消息
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)
})
},
/**
* 發(fā)送點擊監(jiān)聽
*/
sendClick: function(e) {
//客戶發(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
});
},
/**
* 退回上一頁
*/
toBackClick: function() {
wx.navigateBack({})
},
/**
* websocket
*/
chat(){
//進行連接php的socket
wx.connectSocket({
//wss 協(xié)議相當于你要有一個ssl證書,https
//ws 就相當于不實用證書 http
url: 'ws://study.lishuo.net',
success: function () {
console.log('websocket連接成功~')
},
fail: function () {
console.log('websocket連接失敗~')
}
})
},
/**
* 監(jiān)聽websocket心跳連接的方法
*/
webSocketXin(time=60000,status=true){
var timing;
if(status == true){
timing = setInterval(function () {
console.log("當前心跳已重新連接");
//循環(huán)執(zhí)行代碼
wx.sendSocketMessage({
data: JSON.stringify({
type: 'active'
}),
fail(res) {
//關(guān)閉連接
wx.closeSocket();
//提示
wx.showToast({
title: '當前聊天已斷開',
icon:'none'
})
clearInterval(timing);
console.log("當前心跳已關(guān)閉");
}
});
}, time) //循環(huán)時間,注意不要超過1分鐘
} else {
//關(guān)閉定時器
clearInterval(timing);
console.log("當前心跳已關(guān)閉");
}
}
})2、服務(wù)端代碼(PHP代碼)
wechat_websocket.php
<?php
//創(chuàng)建WebSocket Server對象,監(jiān)聽0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9511);
//監(jiān)聽WebSocket連接打開事件
$ws->on('Open', function ($ws, $request) {
echo $request->fd . '我連接上了';
});
//監(jiān)聽WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
//把前臺傳過來的json字符串轉(zhuǎn)成數(shù)組
$params = json_decode($frame->data, true);
//判斷是否是心跳消息,如果是心跳消息
if (isset($params['type']) && isset($params['type'])=='active'){
echo '這是心跳監(jiān)聽消息';
}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));
}
});
//監(jiān)聽WebSocket連接關(guān)閉事件
$ws->on('Close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();五、代碼已經(jīng)編寫完了
1、把服務(wù)端代碼上傳到Linux操作系統(tǒng)里
2、然后切到該目錄下進行運行php wechat_websocket.php

總結(jié)
到此這篇關(guān)于如何利用微信小程序和php實現(xiàn)即時通訊聊天功能的文章就介紹到這了,更多相關(guān)微信小程序 php即時通訊聊天內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
thinkPHP框架可添加js事件的分頁類customPage.class.php完整實例
這篇文章主要介紹了thinkPHP框架可添加js事件的分頁類customPage.class.php,以完整實例形式給出了分頁類customPage.class.php的實現(xiàn)代碼并分析了ajax動態(tài)加載數(shù)據(jù),設(shè)置分頁鏈接等功能,需要的朋友可以參考下2017-03-03
Codeigniter控制器controller繼承問題實例分析
這篇文章主要介紹了Codeigniter控制器controller繼承問題,以簡單實例形式分析了CodeIgniter中針對控制器controller繼承的實現(xiàn)與使用方法,需要的朋友可以參考下2016-01-01
thinkPHP5使用Rabc實現(xiàn)權(quán)限管理
這篇文章主要介紹了thinkPHP5使用Rabc實現(xiàn)權(quán)限管理功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08
ThinkPHP5中如何實現(xiàn)模板完全靜態(tài)化詳解
這篇文章主要為大家介紹了ThinkPHP5中如何實現(xiàn)模板完全靜態(tài)化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
淺談使用 PHP 進行手機 APP 開發(fā)(API 接口開發(fā))
做過 API 的人應(yīng)該了解,其實開發(fā) API 比開發(fā) WEB 更簡潔,但可能邏輯更復(fù)雜,因為 API 其實就是數(shù)據(jù)輸出,不用呈現(xiàn)頁面,所以也就不存在 MVC(API 只有 M 和 C),那么我們來探討下,如何使用php進行手機API接口開發(fā)2014-08-08

