安装与配置
环境准备
在开始之前,请确保您的开发环境满足以下要求:
系统要求
- Node.js >= 12.0.0
- npm 或 yarn 包管理器
- uni-app 开发环境
开发工具
- HBuilderX(推荐)或任意代码编辑器
- 微信开发者工具(如需开发微信小程序)
安装步骤
方式一:通过 uni_modules 安装(推荐)
- 将 SDK 文件夹复制到项目的
uni_modules目录下:
your-project/
├── uni_modules/
│ └── ddiot-ui/
│ └── js_sdk/
│ ├── index.js
│ ├── websocket/
│ │ └── ddiot_websocket.js
│ ├── http/
│ ├── libs/
│ └── api/
- 在项目中直接引用:
import ddiot from '@/uni_modules/ddiot-ui/js_sdk/index.js'
方式二:直接复制文件
- 创建 SDK 目录:
src/
└── utils/
└── ddiot-sdk/
├── index.js
├── websocket/
│ └── ddiot_websocket.js
└── ...
- 在项目中引用:
import ddiot from '@/utils/ddiot-sdk/index.js'
基础配置
1. 修改 main.js
在项目的入口文件 main.js 中引入并配置 SDK:
import App from './App'
import ddiot from '@/uni_modules/ddiot-ui/js_sdk/index.js'
import config from './config.js'
// #ifdef VUE3
import { createSSRApp } from 'vue'
import { createPinia } from 'pinia'
export function createApp() {
const app = createSSRApp(App)
const pinia = createPinia()
app.use(pinia)
// 全局挂载
app.config.globalProperties.$ddiot = ddiot
app.config.globalProperties.$wxapp_id = config.wxapp_id
// 初始化 SDK
app.use(ddiot, {
websocketConf: {
// WebSocket 服务器配置
url: config.websocketUrl, // addons 服务器
authUrl: config.authWebsocketUrl, // 认证服务器
heartRateType: 'heart', // 心跳类型
heartRate: 20000, // 心跳间隔(毫秒)
app_id: config.app_id, // 应用ID
app_secret: config.app_secret, // 应用密钥
},
http: {
successCode: 200, // API 成功状态码
apiConfig: {
// HTTP 请求配置
bloc_id: config.bloc_id,
store_id: config.store_id,
baseUrl: config.apiUrl, // API 基础地址
siteUrl: config.siteUrl, // 站点地址
uploadImgUrl: config.apiUrl + '/upload/images',
imgBaseUrl: config.siteUrl + '/attachment/',
headerFunc: (config) => {
// 自定义请求头
return {
'bloc-id': uni.getStorageSync('bloc-id') || config.bloc_id,
'store-id': uni.getStorageSync('store-id') || config.store_id,
'access-token': uni.getStorageSync('access_token') || ''
}
},
beforRequest: (config) => {
// 请求前处理
const token = uni.getStorageSync('access_token')
const whiteList = ['/wechat/decrypt/msg', '/wechat/basics/signup']
if (whiteList.some(path => config.url.includes(path))) {
return config
}
if (!token) {
uni.reLaunch({
url: '/pages/login/index'
})
return Promise.reject(config)
}
return config
},
getToken: () => uni.getStorageSync('access_token'),
getRefToken: () => uni.getStorageSync('refresh_token'),
refTokenCallBack: (res) => {
// 刷新令牌回调
uni.setStorageSync('access_token', res.data.access_token)
uni.setStorageSync('refresh_token', res.data.refresh_token)
}
},
responseSuccessCallBack: (res) => {
// 响应成功处理
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const currentRoute = currentPage.route
if (res && (res.code === 403 || res.code === 402)) {
uni.removeStorageSync('access_token')
uni.reLaunch({
url: '/pages/login/index'
})
} else if (res.code !== 200) {
uni.showModal({
title: '提示',
content: res.message,
showCancel: false
})
}
}
}
})
return { app }
}
// #endif
2. 创建配置文件
创建 config.js 文件:
export default {
// 应用配置
wxapp_id: 'your_wxapp_id', // 微信小程序ID
app_id: 'your_app_id', // 应用ID
app_secret: 'your_app_secret', // 应用密钥
// 服务器配置
apiUrl: 'https://api.your-domain.com', // API 服务器地址
siteUrl: 'https://your-domain.com', // 站点地址
websocketUrl: 'wss://ws.your-domain.com/addons', // WebSocket 服务器
authWebsocketUrl: 'wss://ws.your-domain.com/auth', // 认证服务器
// 业务配置
bloc_id: 1, // 区域ID
store_id: 1, // 商店ID
project_sn: 'your_project_sn' // 项目标识
}
平台配置
H5 平台
在 manifest.json 中配置:
{
"h5": {
"devServer": {
"disableHostCheck": true
},
"router": {
"mode": "history"
}
}
}
小程序平台
确保在各小程序平台的后台配置了合法域名:
- request 合法域名:
https://api.your-domain.com - socket 合法域名:
wss://ws.your-domain.com
App 平台
在 manifest.json 中配置网络权限:
{
"app-plus": {
"distribute": {
"splashscreen": {
"waiting": true
}
},
"network": {
"timeout": 60000
}
}
}
权限配置
根据需要配置相应权限,在 pages.json 中添加:
{
"permission": {
"scope.userLocation": {
"desc": "您的位置信息将用于设备定位"
}
}
}
完成配置
配置完成后,您就可以在项目中使用 SDK 了:
// 在组件中使用
import { getCurrentInstance } from 'vue'
export default {
setup() {
const { proxy } = getCurrentInstance()
const $ddiot = proxy.$ddiot
// 使用 SDK 功能
const fetchDeviceData = async () => {
const response = await $ddiot.request('/device/data', 'GET', {})
return response.data
}
return {
fetchDeviceData
}
}
}
常见问题
Q: 配置后无法使用?
A: 检查配置项是否正确,特别是服务器地址、app_id、app_secret 等关键信息。
Q: WebSocket 连接失败?
A: 确认 WebSocket 服务器地址是否正确,服务器是否正常运行,防火墙是否开放了相应端口。
Q: 请求 API 失败?
A: 检查 API 地址是否正确,请求头是否包含必要的认证信息。
验证安装
安装配置完成后,可以通过以下代码验证 SDK 是否正常工作:
// 验证 HTTP 请求
const testHttpRequest = async () => {
try {
const response = await $ddiot.request('/test', 'GET', {})
console.log('HTTP 请求成功:', response)
} catch (error) {
console.error('HTTP 请求失败:', error)
}
}
// 验证 WebSocket 连接
const testWebSocket = async () => {
try {
const ws = await $ddiot.createSocket('addons')
console.log('WebSocket 连接成功:', ws)
} catch (error) {
console.error('WebSocket 连接失败:', error)
}
}
如果以上验证都能正常工作,说明 SDK 已成功安装并配置!
