1-config.js
module.exports = {
AppID: '15930922',
APIKey: 'wbChBX7Qa2g6OqUxC6gpSodE',
SecretKey: 'i6MZTStrFL95PVB2py8VghKU5KKOSD74'
2-百度对接的js,这里我用到了redis缓存数据
const config = require('./config')
const https = require('https')
var request = require('request');
const moment = require("moment")
const qs = require('querystring')
var fs = require("fs")
const redis = require('then-redis')
const db = redis.createClient('tcp://localhost:6379')
function getAccessToken(){
return new Promise((resolve, reject)=>{
db.hgetall('AccessToken').then((res)=>{
if(res){
if(res.enddate <= moment().format("YYYY-MM-DD")){
var data = {
'grant_type': 'client_credentials',
'client_id': config.APIKey,
'client_secret': config.SecretKey
};//这是需要提交的数据
var content = querystring.stringify(data);
var options = {
hostname: 'aip.baidubce.com',
path: '/oauth/2.0/token?' + content,
method: 'GET'
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk)
var obj = {
value: chunk.access_token,
enddate: moment().add(29, 'days').format("YYYY-MM-DD")
}
db.hmset("AccessToken", obj)
resolve(obj);
});
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.end()
}else{
resolve(res)
}
}else{
var data = {
'grant_type': 'client_credentials',
'client_id': config.APIKey,
'client_secret': config.SecretKey
};//这是需要提交的数据
var content = qs.stringify(data);
var options = {
hostname: 'aip.baidubce.com',
path: '/oauth/2.0/token?' + content,
method: 'GET'
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk)
var obj = {
value: chunk.access_token,
enddate: moment().add(29, 'days').format("YYYY-MM-DD")
}
db.hmset("AccessToken", obj)
resolve(obj);
});
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.end()
}
}).catch((err)=>{
reject(err)
})
})
}
function getVoiveCode(access_token){
return new Promise((resolve, reject)=>{
var data = {
'appid': config.AppID
};
var content = qs.stringify(data);
var options = {
host: 'aip.baidubce.com',
path: '/rest/2.0/face/v1/faceliveness/sessioncode?access_token="'+access_token+'"',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
let body = ""
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function(){
chunk = JSON.parse(body)
if(chunk.err_no == 0){
resolve(JSON.stringify({
session_id: chunk.result.session_id,
code: chunk.result.code
}));
}else{
reject(JSON.stringify(chunk))
}
})
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.write(content)
req.end()
})
}
function verify(access_token, p_session_id, p_video_base64){
return new Promise((resolve, reject)=>{
var data = {
'session_id': p_session_id,
'video_base64': p_video_base64
};
var content = qs.stringify(data);
var options = {
host: 'aip.baidubce.com',
path: '/rest/2.0/face/v1/faceliveness/verify?access_token="'+access_token+'"',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}//
};
var req = https.request(options, function(res){
res.setEncoding('utf8');
let body = ""
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function(){
let chunk = JSON.parse(body)
if(chunk.err_no == 0){
let imgData = chunk.result.pic_list[0].pic
var currBase = imgData.replace(/^data:image\/\w+;base64,/, "");
let img1 = fs.readFileSync("1.jpg"); // 对比文件的路径
let imgData1 = new Buffer(img1).toString("base64")
var base64Data = imgData1.replace(/^data:image\/\w+;base64,/, "")
var match_data = [
{
"image": currBase,
"image_type": "BASE64"
},
{
"image": base64Data,
"image_type": "BASE64"
}
];
var match_options = {
host: 'aip.baidubce.com',
path: '/rest/2.0/face/v3/match?access_token="'+access_token+'"',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}//
};
var match_req = https.request(match_options, function(m_res){
m_res.setEncoding('utf8');
let m_body = ""
m_res.on('data', function (chunk) {
m_body += chunk;
});
m_res.on('end', function(){
let m_chunk = JSON.parse(m_body)
console.log(m_chunk)
if(m_chunk.error_code == 0){
resolve(JSON.stringify(m_chunk))
}else{
reject(JSON.stringify(m_chunk))
}
})
})
match_req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
match_req.write(JSON.stringify(match_data))
match_req.end()
}else{
reject(JSON.stringify(chunk))
}
})
})
req.on('error', function (e) {
reject('problem with request: ' + e.message);
});
req.write(content)
req.end()
})
}
function match(access_token){
let img2 = fs.readFileSync("image.png");
let imgData2 = new Buffer(img2).toString("base64")
var base64Data2 = imgData2.replace(/^data:image\/\w+;base64,/, "")
var imgdata = imgData1 + "," + imgData2
// request({
// url: `https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="${access_token}"`,
// method: "POST",
// json: true,
// headers: {
// "content-type": "application/json",
// },
// body: data
// }, function(error, response, body) {
// if (!error && response.statusCode == 200) {
// }
// });
}
module.exports.getAccessToken = getAccessToken;
module.exports.getVoiveCode = getVoiveCode;
module.exports.verify = verify;
module.exports.match = match;
3-启动文件app.js
const baidu = require('./baidu')
var express = require('express')
var moment = require("moment")
const fs = require("fs")
var app = express();
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({limit: "50mb", extended: true })
// 设置body最大长度
app.use(bodyParser.json({limit: "50mb"}))
//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
//Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
app.get('/match', function(){
baidu.getAccessToken().then((access)=>{
if(access.value){
baidu.match(access.value);
}
})
})
app.post('/VoiceCode', urlencodedParser,function(req, res){
baidu.getAccessToken().then((access)=>{
if(access.value){
baidu.getVoiveCode(access.value).then((code)=>{
res.end(code)
}).catch((err)=>{
res.end(err)
})
}
}).catch((err)=>{
res.end(err)
});
})
app.post('/Verify', urlencodedParser,function(req, res){
let msg = req.body;
baidu.getAccessToken().then((access)=>{
if(access.value){
baidu.verify(access.value, msg.session_id, msg.video_base64).then((code)=>{
res.end(code)
}).catch((err)=>{
res.end(err)
})
}
}).catch((err)=>{
res.end(err)
});
})
var server = app.listen(7890, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
process.on('uncaughtException', function (err) {
//打印出错误
console.log(err);
//打印出错误的调用栈方便调试
console.log(err.stack)
});