微信小程序接入deepseek

先上效果

话不多说,直接上代码(本人用的hbuilder X+uniapp)

javascript 复制代码
<template>
  <view class="container">
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-list" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
    >
      <view 
        v-for="(item, index) in chatList" 
        :key="index" 
        class="chat-item"
        :class="item.role === 'user' ? 'user' : 'assistant'"
      >
        <view class="content-box">
          <text class="content">{{ item.content }}</text>
          <text class="time">{{ item.time }}</text>
        </view>
        <view v-if="item.loading" class="loading">
          <view class="dot"></view>
          <view class="dot"></view>
          <view class="dot"></view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <input 
        class="input" 
        v-model="inputMessage" 
        placeholder="请输入问题..."
        @confirm="sendMessage"
        :disabled="isSending"
        placeholder-class="placeholder"
      />
      <button 
        class="send-btn" 
        @tap="sendMessage"
        :disabled="isSending || !inputMessage"
      >
        {{ isSending ? '发送中...' : '发送' }}
      </button>
    </view>
  </view>
</template>

<script>
const API_URL = 'https://api.deepseek.com/v1/chat/completions' // 替换为实际API地址
const API_KEY = 'sk-' // 替换为你的API密钥

export default {
  data() {
    return {
      chatList: [],
      inputMessage: '',
      isSending: false,
      scrollTop: 0
    }
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isSending) return
      
      const userMessage = {
        role: 'user',
        content: this.inputMessage,
        time: this.getCurrentTime(),
        loading: false
      }
      
      // 添加用户消息
	  console.log(userMessage)
      this.chatList.push(userMessage)
      this.inputMessage = ''
      
      // 添加AI的loading状态
      const assistantMessage = {
        role: 'assistant',
        content: '',
        time: '',
        loading: true
      }
      this.chatList.push(assistantMessage)
      
      this.isSending = true
      this.scrollToBottom()
      
      try {
        const res = await uni.request({
          url: API_URL,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
          },
          data: {
            model: 'deepseek-chat', // 模型
            messages: this.chatList
              .filter(item => !item.loading)
              .map(item => ({
                role: item.role,
                content: item.content
              }))
          }
        })
        
        // 更新AI消息
        const lastIndex = this.chatList.length - 1
        this.chatList[lastIndex] = {
          role: 'assistant',
          content: res.data.choices[0].message.content,
          time: this.getCurrentTime(),
          loading: false
        }
        
        this.$forceUpdate()
      } catch (error) {
        console.error('API请求失败:', error)
        uni.showToast({
          title: '请求失败,请重试',
          icon: 'none'
        })
        this.chatList.pop() // 移除loading状态的消息
      } finally {
        this.isSending = false
        this.scrollToBottom()
      }
    },
    
    getCurrentTime() {
      const date = new Date()
      return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = Math.random() * 1000000 // 通过随机数强制滚动到底部
      })
    }
  }
}
</script>

<style scoped>
/* 新增修改的样式 */
.container {
  padding-bottom: 120rpx; /* 给输入框留出空间 */
}

.chat-list {
  padding: 20rpx 20rpx 160rpx; /* 底部留白防止遮挡 */
}

.chat-item {
  margin: 30rpx 0;
}

.content-box {
  max-width: 75%;
  padding: 20rpx 28rpx;
  border-radius: 16rpx;
  margin: 0 20rpx;
  position: relative;
}

.user .content-box {
  background: #1989fa;
  color: white;
  margin-left: auto; /* 右对齐关键属性 */
}

.assistant .content-box {
  background: #f8f8f8;
  color: #333;
  margin-right: auto; /* 左对齐关键属性 */
}

.time {
  font-size: 24rpx;
  color: #999;
  position: absolute;
  bottom: -40rpx;
  white-space: nowrap;
}

/* 新版加载动画 */
.loading {
  display: flex;
  align-items: center;
  padding: 20rpx;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  background: #ddd;
  border-radius: 50%;
  margin: 0 4rpx;
  animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 80%, 100% { 
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10rpx);
  }
}

/* 输入区域样式优化 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.05);
}

.input {
  flex: 1;
  height: 80rpx;
  padding: 0 28rpx;
  background: #e9e9e9;
  border-radius: 40rpx;
  font-size: 28rpx;
  color: #333;
  border: none;
}

.placeholder {
  color: #999;
}

.send-btn {
  width: 140rpx;
  height: 80rpx;
  line-height: 80rpx;
  margin-left: 20rpx;
  background: #1989fa;
  color: white;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.send-btn[disabled] {
	opacity: 0.6;
	background: blue;
    color: white;
}
</style>

注:
1、修改你的密钥
2、需要在微信公众平台里面配置服务器域名(在开发管理里面)

javascript 复制代码
https://api.deepseek.com

3、如果接口中有返回数据,但页面中没有数据展示,同时还提示API请求失败,打开接口返回的地址,与下面这段代码一一对应,看路径有没有问题

javascript 复制代码
content: res.data.choices[0].message.content
相关推荐
Ai-_Man1 小时前
您您这可以把Google AI Studio的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。AI导出鸭
javascript·人工智能·ai·小程序·电脑
m0_5873830014 小时前
深度解析24小时自助健身房系统开发:从架构设计到落地部署
人工智能·小程序·数据挖掘·系统架构·需求分析
张晓宇 .17 小时前
Codex 使用教程(2026年9月 0.158 最新版):安装、国内接入 DeepSeek / GPT-6、config.toml 配置与报错排查
gpt·大模型·openai·ai编程·codex·deepseek
小马92620 小时前
KV Cache 瘦身 437 倍:DeepSeek V4.1-Flash 的推理效率革命
大模型·moe·kv cache·deepseek·推理优化·ai基础设施
镭封1 天前
基于微信小程序的移动端AI配音工作流设计
人工智能·小程序·媒体
FX1317887KP_1 天前
PET口语备考攻略:发音、语法、表达,三个问题怎么同时解决
小程序·ket口语·pet口语·fce备考·剑桥英语
地球@+jdhb441 天前
企业私域运营新趋势:快手短视频平台跳转小程序企微卡片链路搭建成为商家运营重点
小程序·企业微信
程序鉴定师1 天前
2026年深圳小程序/App开发公司技术选型指南:从架构设计到交付标准全维度评估
java·小程序·uni-app·php·objective-c
章鱼哥19711 天前
DeepSeek Harness 插件开发新手教程
后端·deepseek
Q26433650231 天前
【有源码】基于uni-app的旅游行程规划小程序-基于微信小程序的智慧文旅综合服务平台
java·微信小程序·小程序·uni-app·毕业设计·springboot·源代码