UNPKG

@phqb/mcp-server

Version:

PHQB MCP Payment Server - AI-powered payment processing for Claude and other AI assistants

236 lines (225 loc) 9.64 kB
"use strict"; // 退款相关工具实现 Object.defineProperty(exports, "__esModule", { value: true }); exports.RefundTools = void 0; // 使用全局 fetch (Node.js 18+ 内置) const types_1 = require("../types"); class RefundTools { constructor(apiKey, baseURL = 'https://www.phqb.com') { this.apiKey = apiKey; this.baseURL = baseURL; } /** * 创建退款 */ async createRefund(args) { try { // 首先获取原订单信息 const orderResponse = await fetch(`${this.baseURL}/api/orders/${args.order_id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const orderResult = await orderResponse.json(); if (!orderResult.success) { throw new types_1.MCPError(`无法找到订单: ${orderResult.error}`, 'ORDER_NOT_FOUND'); } const order = orderResult.data; // 检查订单状态 if (order.status !== 'paid') { throw new types_1.MCPError(`只能对已支付的订单进行退款。当前订单状态: ${order.status}`, 'INVALID_ORDER_STATUS'); } // 确定退款金额 const refundAmount = args.amount || order.amount; if (refundAmount > order.amount) { throw new types_1.MCPError(`退款金额不能超过原订单金额 $${order.amount.toFixed(2)}`, 'INVALID_REFUND_AMOUNT'); } // 创建退款 const refundResponse = await fetch(`${this.baseURL}/api/refund/create`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, body: JSON.stringify({ order_id: args.order_id, amount: refundAmount, reason: args.reason }) }); const refundResult = await refundResponse.json(); if (refundResult.success) { const refund = refundResult.data; const isPartialRefund = refundAmount < order.amount; return { content: [{ type: "text", text: `✅ ${isPartialRefund ? '部分' : '全额'}退款创建成功! 📋 退款信息: - 退款ID: ${refund.refund_id} - 原订单ID: ${args.order_id} - 原订单金额: $${order.amount.toFixed(2)} USD - 退款金额: $${refundAmount.toFixed(2)} USD - 退款原因: ${args.reason} - 退款状态: 处理中 - 创建时间: ${new Date().toLocaleString('zh-CN')} ⏰ 退款处理时间: - 微信支付: 1-3个工作日 - 支付宝: 1-7个工作日 💡 您可以使用 get_refund_status 工具查询退款处理进度。 ${isPartialRefund ? `⚠️ 这是部分退款,剩余金额 $${(order.amount - refundAmount).toFixed(2)} 仍保留在原订单中。` : ''}` }] }; } else { throw new types_1.MCPError(`创建退款失败: ${refundResult.error}`, 'REFUND_CREATE_ERROR'); } } catch (error) { if (error instanceof types_1.MCPError) throw error; throw new types_1.MCPError(`创建退款时发生错误: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR'); } } /** * 查询退款状态 */ async getRefundStatus(args) { try { const response = await fetch(`${this.baseURL}/api/refund/${args.refund_id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const result = await response.json(); if (result.success) { const refund = result.data; const statusEmoji = this.getRefundStatusEmoji(refund.status); const createdAt = new Date(refund.created_at).toLocaleString('zh-CN'); const completedAt = refund.completed_at ? new Date(refund.completed_at).toLocaleString('zh-CN') : null; return { content: [{ type: "text", text: `📋 退款状态查询 🆔 退款ID: ${refund.refund_id} 🔗 原订单ID: ${refund.order_id} ${statusEmoji} 退款状态: ${this.getRefundStatusDisplay(refund.status)} 💰 退款金额: $${refund.amount.toFixed(2)} USD 📝 退款原因: ${refund.reason} 🕐 申请时间: ${createdAt} ${completedAt ? `✅ 完成时间: ${completedAt}` : ''} ${refund.failure_reason ? `❌ 失败原因: ${refund.failure_reason}` : ''} ${this.getRefundStatusTips(refund.status)}` }] }; } else { throw new types_1.MCPError(`查询退款状态失败: ${result.error}`, 'REFUND_NOT_FOUND'); } } catch (error) { if (error instanceof types_1.MCPError) throw error; throw new types_1.MCPError(`查询退款状态时发生错误: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR'); } } /** * 获取退款历史 */ async getRefundHistory(args) { try { const queryParams = new URLSearchParams(); queryParams.append('limit', args.limit.toString()); if (args.status !== 'all') queryParams.append('status', args.status); const response = await fetch(`${this.baseURL}/api/refund/history?${queryParams}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const result = await response.json(); if (result.success) { const refunds = result.data.refunds; if (refunds.length === 0) { return { content: [{ type: "text", text: `📋 退款历史记录 暂无退款记录。 💡 当您需要为客户退款时,可以使用 create_refund 工具创建退款申请。` }] }; } const refundList = refunds.map((refund, index) => { const statusEmoji = this.getRefundStatusEmoji(refund.status); const createdAt = new Date(refund.created_at).toLocaleDateString('zh-CN'); return `${index + 1}. ${statusEmoji} ${refund.refund_id} 💰 $${refund.amount.toFixed(2)} - ${refund.reason} 🔗 订单: ${refund.order_id} 🕐 ${createdAt}`; }).join('\n\n'); const totalRefunded = refunds .filter((refund) => refund.status === 'completed') .reduce((sum, refund) => sum + refund.amount, 0); const completedCount = refunds.filter((refund) => refund.status === 'completed').length; const processingCount = refunds.filter((refund) => refund.status === 'processing').length; const failedCount = refunds.filter((refund) => refund.status === 'failed').length; return { content: [{ type: "text", text: `📋 退款历史记录 (${refunds.length} 个) ${refundList} 📊 退款统计: - 已完成: ${completedCount} 个 - 处理中: ${processingCount} 个 - 失败: ${failedCount} 个 - 总退款金额: $${totalRefunded.toFixed(2)} - 成功率: ${refunds.length > 0 ? Math.round(completedCount / refunds.length * 100) : 0}% 💡 使用 get_refund_status 获取具体退款的详细状态。` }] }; } else { throw new types_1.MCPError(`获取退款历史失败: ${result.error}`, 'FETCH_ERROR'); } } catch (error) { if (error instanceof types_1.MCPError) throw error; throw new types_1.MCPError(`获取退款历史时发生错误: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR'); } } // 辅助方法 getRefundStatusEmoji(status) { const emojis = { 'processing': '⏳', 'completed': '✅', 'failed': '❌', 'cancelled': '🚫' }; return emojis[status] || '❓'; } getRefundStatusDisplay(status) { const statuses = { 'processing': '处理中', 'completed': '已完成', 'failed': '失败', 'cancelled': '已取消' }; return statuses[status] || status; } getRefundStatusTips(status) { const tips = { 'processing': '⏳ 退款正在处理中,通常在1-7个工作日内完成。请耐心等待。', 'completed': '🎉 退款已成功完成,资金已返还给客户的原支付账户。', 'failed': '⚠️ 退款处理失败,可能是由于账户问题或其他技术原因。请联系客服处理。', 'cancelled': '🚫 退款申请已被取消。如需重新申请退款,请创建新的退款申请。' }; return tips[status] || ''; } } exports.RefundTools = RefundTools; //# sourceMappingURL=refund.js.map