在做微信小程序垃圾分类功能时,有用到拍照识别语音识别和文字识别,文字识别直接传参,语音识别需要将语音转化成文字,图片识别需要将图片转化成base64格式传参,通过调用京东云的接口来返回垃圾信息。具体实现我用了云函数来实现,具体步骤如下(无坑一步一步跟着走绝对能运行)
一、构建云函数
// 云函数入口文件 const cloud = require('wx-server-sdk') const TcbRouter = require('tcb-router'); const axios = require('axios'); const { Context, Signer } = require('jdcloud-sdk-signer') cloud.init({ env: "" }) let db = cloud.database() const _ = db.command /** * 因为京东neuhub平台服务器崩溃,所以改用京东云垃圾分类API */ /** * 京东API配置 * 垃圾分类api * * 申请地址:https://www.jdcloud.com/cn/products/garbage-classification */ let jdaiyuncofig = { accessKeyId: 'JDC_F0904F0F3B595D5B7221FEAw3802CF8', secretAccessKey: 'DEA78F8481A2C51112337F2F89BD3BA9F0B' //这里需要自己去京东云申请自己的密钥,上面的密钥是假的 } function getAuthorization() { let ctx = new Context('nativecontainer.internal.cn-north-1.jdcloud-api.com', '/jdai/*', 'POST', null, '', 'cn-north-1') ctx.buildNonce() let signer = new Signer(ctx, jdaiyuncofig) let auth = signer.sign(new Date()) return auth } // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() let { APPID, OPENID } = wxContext const app = new TcbRouter({ event }) //提供通过文本进行垃圾分类查询的能力 app.router('garbageTextSearch', async (ctx, next) => { let { text, devIntegral } = event let auth = getAuthorization() ctx.body = axios.post(`https://aiapi.jdcloud.com/jdai/garbageTextSearch`, { text: text, cityId: '310000' }, { headers: { 'Content-Type': 'application/json', 'Authorization': auth } }).then(res => { return res.data }) }) //获取用户openID app.router('openId', async (ctx, next) => { ctx.body = { openId: OPENID } }) return app.serve() }
构建云函数时相应的插件如下,保存后通过工具=》构建npm来进行构建
{ "name": "api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "axios": "^0.20.0", "debug": "^4.3.1", "jdcloud-sdk-signer": "^2.0.2", "md5-node": "^1.0.1", "qs": "^6.9.4", "tcb-router": "^1.1.2", "wx-server-sdk": "~2.5.3" } }