otpm/miniprogram-example/services/otp.js
“xHuPo” 44500afd3f beta
2025-05-23 19:09:06 +08:00

119 lines
No EOL
3.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// otp.js - OTP相关服务
import request from '../utils/request';
/**
* 创建新的OTP
* @param {Object} params - 创建OTP的参数
* @param {string} params.name - OTP名称
* @param {string} params.issuer - 发行方
* @param {string} params.secret - 密钥
* @param {string} params.algorithm - 算法默认为SHA1
* @param {number} params.digits - 位数默认为6
* @param {number} params.period - 周期默认为30秒
* @returns {Promise} - 返回创建结果
*/
export const createOTP = (params) => {
if (!params || !params.secret) {
return Promise.reject(new Error('缺少必要的参数: secret'));
}
return request({
url: '/otp',
method: 'POST',
data: {
name: params.name || '',
issuer: params.issuer || '',
secret: params.secret,
algorithm: params.algorithm || 'SHA1',
digits: params.digits || 6,
period: params.period || 30
}
}).catch(err => {
console.error('创建OTP失败:', err);
throw new Error('创建OTP失败: ' + (err.message || '未知错误'));
});
};
/**
* 获取用户所有OTP列表
* @returns {Promise} - 返回OTP列表
*/
export const getOTPList = () => {
return request({
url: '/otp',
method: 'GET'
}).catch(err => {
console.error('获取OTP列表失败:', err);
throw new Error('获取OTP列表失败: ' + (err.message || '未知错误'));
});
};
/**
* 获取指定OTP的当前验证码
* @param {string} id - OTP的ID
* @returns {Promise} - 返回当前验证码
*/
export const getOTPCode = (id) => {
if (!id) {
return Promise.reject(new Error('缺少必要的参数: id'));
}
return request({
url: `/otp/${id}/code`,
method: 'GET'
}).catch(err => {
console.error('获取OTP代码失败:', err);
throw new Error('获取OTP代码失败: ' + (err.message || '未知错误'));
});
};
/**
* 验证OTP
* @param {string} id - OTP的ID
* @param {string} code - 用户输入的验证码
* @returns {Promise} - 返回验证结果
*/
export const verifyOTP = (id, code) => {
if (!id || !code) {
return Promise.reject(new Error('缺少必要的参数: id或code'));
}
return request({
url: `/otp/${id}/verify`,
method: 'POST',
data: { code }
}).catch(err => {
console.error('验证OTP失败:', err);
throw new Error('验证OTP失败: ' + (err.message || '未知错误'));
});
};
/**
* 更新OTP信息
* @param {string} id - OTP的ID
* @param {Object} params - 更新的参数
* @returns {Promise} - 返回更新结果
*/
export const updateOTP = (id, params) => {
if (!id || !params) {
return Promise.reject(new Error('缺少必要的参数: id或params'));
}
return request({
url: `/otp/${id}`,
method: 'PUT',
data: params
}).catch(err => {
console.error('更新OTP失败:', err);
throw new Error('更新OTP失败: ' + (err.message || '未知错误'));
});
};
/**
* 删除OTP
* @param {string} id - OTP的ID
* @returns {Promise} - 返回删除结果
*/
export const deleteOTP = (id) => {
return request({
url: `/otp/${id}`,
method: 'DELETE'
});
};