How to Integrate DeepSeek into WeChat Mini Programs? 51

小编 ·

How to Integrate DeepSeek into WeChat Mini Programs?

Step-by-step guide on the environment configuration and code implementation required to integrate DeepSeek AI into WeChat Mini Programs.

How to Integrate DeepSeek into WeChat Mini Programs?

To integrate DeepSeek AI into a WeChat Mini Program, developers need to complete the following environment configuration and code implementation.

First, make sure that your Mini Program base library version is 3.7.1 or above, and that you have enabled Cloud Development for the Mini Program. You can perform the related settings and create the corresponding environment in the WeChat Developer Tools via the [Cloud Development] button on the toolbar.

I. Preparations

Register a WeChat Mini Program account:

  • Visit the WeChat Official Accounts Platform (mp.weixin.qq.com) and register a WeChat Mini Program account.

Create a Mini Program project:

  • Download and install the WeChat Developer Tools.

Update the Mini Program base library:

  • Make sure the WeChat Mini Program base library version you are using is at least 3.7.1 or above.

Enable Cloud Development:

  • In the WeChat Developer Tools, click the "Cloud Development" button on the toolbar, follow the prompts to enable Cloud Development, and create a new environment. First-time users of Cloud Development can receive a one-month free package.

II. Initialize the Cloud Development Environment

Add the following code to your Mini Program code to initialize the Cloud Development environment:

// app.js 文件中
App({
  onLaunch() {
    if (!wx.cloud) {
      console.error('请检查是否已启用 cloud 开发');
      return;
    }
    
    // 初始化云开发环境,默认指向当前项目的默认环境
    wx.cloud.init({
      env: 'your-env-id', // 替换为您的云开发环境ID
      traceUser: true,
    });
  },
});

III. Call the Large Model to Implement Text Generation

  • Suppose we want to implement a text generation feature on a simple page, such as generating a piece of descriptive text.

IV. Write the Front-end Code

Write the logic and display code in the .js and .wxml files of a certain page respectively.

Sample page structure (pages/index/index.wxml)

生成文本

Sample page logic (pages/index/index.js)

Page({
  data: {
    generatedText: '',
  },

  generateText() {
    const that = this;

    wx.showLoading({ title: '正在生成...' });

    wx.cloud.callFunction({
      name: 'callDeepSeek',
      success(res) {
        console.log('[Cloud Function] callDeepSeek result:', res.result);
        that.setData({
          generatedText: res.result.text, // 假设返回结果包含 text 字段
        });
      },
      fail(err) {
        console.error('[Cloud Function] callDeepSeek error:', err);
        wx.showToast({ icon: 'none', title: '请求失败' });
      },
      complete() {
        wx.hideLoading();
      },
    });
  },
});

V. Write the Cloud Function

We need to create a cloud function named callDeepSeek in the Cloud Development console in order to call DeepSeek and return the result.

Create the Cloud Function

1. Log in to the WeChat Cloud Development management console.

2. Navigate to [Cloud Functions] in the left menu and click [New].

3. Enter the name callDeepSeek, then click OK.

Write the Cloud Function Code (Node.js)

Write the following code in index.js:

const axios = require('axios');

exports.main = async (event, context) => {
  try {
    const apiKey = process.env.DEEPSEEK_API_KEY; // 设置环境变量 DEEPSEEK_API_KEY 存储 API Key
    const apiUrl = 'https://api.deepseek.com/v1/generate'; // DeepSeek 文本生成 API 地址
    
    const response = await axios.post(apiUrl, {
      prompt: event.prompt || '请输入您的指令或主题。',
      max_tokens: 150, // 返回的最大 token 数量
    }, {
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      }
    });

    return { 
      code: 0,
      message: 'success',
      text: response.data.choices[0].text.trim(), // 解析返回的数据
    };
  } catch (error) {
    console.error(error);
    return { 
      code: -1,
      message: 'failed to fetch from deepseek api',
      text: ''
    };
  }
};

Add Dependencies

In order to use the Axios library to send HTTP requests, make sure to install the Axios package in the cloud function's root directory. You can install it via npm:

1. Switch to the cloud function directory:

cd functions/callDeepSeek/

2. Install Axios:

npm install axios --save

3. Build Node_modules:

npm run build:npm

(If there is no build:npm script, you can add it manually in package.json)

4. Upload the changes to Cloud Development: Go back to the WeChat Developer Tools, right-click the functions/callDeepSeek/ directory, and select "Upload and Deploy: Cloud-side Installation of Dependencies"

VI. Testing and Verification

After completing the above settings, go back to the preview mode in the WeChat Developer Tools, try to trigger the "Generate Text" button, and observe whether the expected result appears.