直接上代码
微信开发者工具-调试器-终端-新建终端 进行依赖安装
npm install base-64
npm install crypto-js
然后顶部工具栏依次点击 工具-构建npm
// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const Base64 = require('base-64');
const CryptoJS = require('crypto-js')
let socket = ""
Page({
data: {
APPID: "",//从开放平台控制台中获取
APIKEY: "",//从开放平台控制台中获取
APISecret: "",//从开放平台控制台中获取
motto: 'Hello World',
historyTextList: [],
userInfo: {
avatarU服务器托管网rl: defaultAvatarUrl,
nickName: '',
},
hasUserInfo: false,
canIUseGetUserProfile: wx.canIUse('getUserProfile'),
canIUseNicknameComp: wx.canIUse('input.type.nickname'),
TEXT: '你好,我的名字叫大王',
sparkResult: '',
tempRes: '' // 临时答复保存
},
bindViewTap() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad() {
this.connectWebsocket()
},
getWebsocketUrl() {
var _this2 = this;
var url = "wss://spark-api.xf-yun.com/v3.5/chat";
var host = "spark-api.xf-yun.com";
var apiKeyName = 'api_key';
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = "host: "
.concat(host, "ndate: ")
.concat(date, "nGET /v3.5/chat HTTP/1.1");
var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, _this2.data.APISecret);
var signature = CryptoJS.enc.Base64.stringify(signatureSha);
var authorizationOrigin = "".concat(apiKeyName, "="")
.concat(_this2.data.APIKEY, "",algorithm="")
.concat(algorithm, "",headers="")
.concat(headers, "",signature="")
.concat(signature, """);
var authorization = Base64.encode(authorizationOrigin);
url = "".concat(url, "?authorization=")
.concat(authorization, "&date=")
.concat(encodeURI(date), "&host=")//进行|不进行URRLENCODE均没报错
.concat(host);
return url;
},
connectWebsocket() {
var url = this.getWebsocketUrl();
socket = wx.connectSocket({
url: url,
success(res) {
console.log('WebSocket 连接成功: ', res)
},
fail(err) {
console.log('WebSocket 连接失败: ', err)
}
})
// onOpen
socket.onOpen((res) => {
var _this = this;
console.log('WebSocket 已连接',res)
_this.data.historyTextList.push({
"role": "user",
"content": _this.data.TEXT
});
var params = {
"header": {
"app_id": _this.data.APPID,
"uid": "123456789"
},
"parameter": {
"chat": {
"domain": "generalv3.5",
"random_threshold": 0,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": _this.data.historyTextList
}
}
};
_this.sparkResult = _this.sparkResult + "rn我:" + _this.TEXT + "rn";
_this.sparkResult = _this.sparkResult + "大模型:";
console.log("发送第一帧...", JSON.stringify(params));
socket.send({
data:JSON.stringify(params),
fail(err) {
console.log('WebSocket 消息发送失败', err)
}
})
})
// onError
socket.onError((err) => {
console.log('WebSocket 连接失败:', err)
})
// onClose
socket.onClose((ret) => {
console.log('断开 WebSocket 连接', ret)
})
//监听接收到的消息
socket.onMes服务器托管网sage((res) => {
let msg = res.data
console.info("接收到的服务器消息--原始:")
console.info(res)
if (typeof msg === "string" && msg.startsWith("{")) {
msg = JSON.parse(msg)
}
console.log("接收到的服务器消息", msg)
})
},
})
控制台输出
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net