上篇文章咱們分享瞭如何使用純的雲函數開發的榛子短信短信(http://smsow.zhenzikj.com)SDK,因爲微信對於未付費雲函數個數的限制,這種方法存在缺陷,通過改進,使用tcb-router做爲路由,這樣只須要整合到一個雲函數中就行
下載sdk和demo: http://smsow.zhenzikj.com/sdk...html
目前SDK中包含三個功能: send(發送短信)、balance(查詢餘額)、findSmsByMessageId(查詢單條短信)json
SDK源碼api
// 雲函數入口文件 const cloud = require('wx-server-sdk') const TcbRouter = require('tcb-router') const rq = require('request') const baseUrl = 'https://smsdeveloper.zhenzikj.com' cloud.init() // 雲函數入口函數 exports.main = async (event, context) => { const app = new TcbRouter({ event }); app.router('send', async (ctx) => { ctx.body = new Promise(resolve => { rq({ url: baseUrl + '/sms/send.html', method: "POST", json: true, form: { apiUrl: event.apiUrl, appId: event.appId, appSecret: event.appSecret, message: event.message, number: event.number, messageId: event.messageId, } }, function (error, response, body) { resolve({ body: body, error: error }) }); // setTimeout(() => { // resolve('male'); // }, 500); }); }); app.router('balance', async (ctx) => { ctx.body = new Promise(resolve => { rq({ url: baseUrl + '/sms/balance.html', method: "POST", json: true, form: { apiUrl: event.apiUrl, appId: event.appId, appSecret: event.appSecret } }, function (error, response, body) { resolve({ body: body, error: error }) }); }); }); app.router('findSmsByMessageId', async (ctx) => { ctx.body = new Promise(resolve => { rq({ url: baseUrl + '/sms/findSmsByMessageId.html', method: "POST", json: true, form: { apiUrl: event.apiUrl, appId: event.appId, appSecret: event.appSecret, messageId: event.messageId } }, function (error, response, body) { resolve({ body: body, error: error }) }); }); }); return app.serve(); }
如何使用SDK微信
//index.js const app = getApp() Page({ data: { }, onLoad: function() { }, // 發送短信 send: function () { wx.cloud.callFunction({ name: 'zhenzisms', data: { $url: 'send', apiUrl: 'https://sms_developer.zhenzikj.com', appId: '你的appId', appSecret: '你的appSecret', message: '你的驗證碼爲:3333', number: '15811111111', messageId: '' } }).then((res) => { console.log(res.result.body); }).catch((e) => { //console.log(e); }); }, // 查詢餘額 balance: function () { wx.cloud.callFunction({ name: 'zhenzisms', data: { $url: 'balance', apiUrl: 'https://sms_developer.zhenzikj.com', appId: '你的appId', appSecret: '你的appSecret' } }).then((res) => { console.log(res.result.body); }).catch((e) => { //console.log(e); }); }, // 查詢單條信息 findSmsByMessageId: function () { wx.cloud.callFunction({ name: 'zhenzisms', data: { $url: 'findSmsByMessageId', apiUrl: 'https://sms_developer.zhenzikj.com', appId: '你的appId', appSecret: '你的appSecret', messageId: 'aaaabbbbba' } }).then((res) => { console.log(res.result.body); }).catch((e) => { //console.log(e); }); } })