前兩天在發布小程序版本的時候,審核被拒絕,原因是用戶在發表內容的時候,沒有對內容做安全檢測,例如國家領導人姓名之類的。
后來了解到小程序官方文檔上有提供相關檢測接口,包括文本及圖片檢測,這里我只用到了文本檢測
使用msgSecCheck接口檢測文本
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html
請求接口地址是 https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN
,為POST請求,請求參數為:
- access_token 接口調用憑證
- content 要檢測的文本內容,長度不超過 500KB
let content = params.content;
let access_token = await this.app.redis.get('access_token');
let url = `https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${access_token}`;
let data = {
content: content
}
let checkResult = await proxy(url, {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(data)
});
checkResult = JSON.parse(checkResult);
if (checkResult.errcode == 87014) {
// 內容含有違法違規內容
response = this.ResultResponse.createByErrorMsg('內容含有違法違規內容');
}
定時刷新access_token憑證
access_token是接口調用憑證,通過getAccessToken接口獲取
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
接口請求地址是 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
,為GET請求,請求參數為:
- grant_type 填寫 client_credential
- appid 小程序唯一憑證,即 AppID
- secret 小程序唯一憑證密鑰,即 AppSecret
接口返回數據除了access_token還有expires_in過期時間 ,這里有效期是7200s,也就是2小時候該憑證失效,所以我們需要通過定時器定時刷新獲取access_token,然后存到redis里面
/////////get_access_token.js文件
const Subscription = require('egg').Subscription;
/**
* 獲取微信accessToken定時任務 90(5400s)分鍾刷新一次
*/
class GetAceessToken extends Subscription {
// 通過 schedule 屬性來設置定時任務的執行間隔等配置
static get schedule() {
return {
interval: '5400s', // 1 分鍾間隔 隔單位 m 分 、 s 秒、 ms 毫秒
type: 'all', // all 指定所有的 worker 都需要執行 worker 每台機器上只有一個 worker 會執行這個定時任務
immediate: true, //配置了該參數為 true 時,這個定時任務會在應用啟動並 ready 后立刻執行一次這個定時任務。
disable: false//配置該參數為 true 時,這個定時任務不會被啟動。
};
}
// subscribe 是真正定時任務執行時被運行的函數
async subscribe() {
let ctx = this.ctx;
ctx.logger.info('-----getAccessToken start----');
try {
await ctx.service.userService.getAccessToken();
} catch (error) {
console.log('獲取access token失敗', error)
}
ctx.logger.info('-----getAccessToken end----');
}
}
module.exports = GetAceessToken;
/////////userService.js文件
/**
* 獲取AccessToken,存儲到redis里面,用於安全內容檢查 每90分鍾刷新一次
*/
async getAccessToken() {
let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.key.appid}&secret=${config.key.secret}`;
let result = await proxy(url, {
method: 'GET'
});
result = JSON.parse(result);
console.log('getAccessToken result', result)
await this.app.redis.set('access_token', result.access_token);
await this.app.redis.set('expires_in', result.expires_in);//目前有效期7200s 2小時
}