import Koa from 'koa';
import KoaRouter from 'koa-router';
import crypto from 'crypto';
import axios from 'axios';
import bodyParser from 'koa-bodyparser';
const app = new Koa();
const router = new KoaRouter();
const accessKey = '云开发 Client ID';
const secretKey = '云开发 Client Secret';
router.post('/login', async (ctx) => {
const { code, nickName, avatarUrl } = ctx.request.body;
const path = `/v1.0/token?code=${code}&grant_type=2`;
const contentHash = crypto.createHash('sha256').update('').digest('hex');
const t = +new Date();
const nonce = '';
const stringToSign = ['GET', contentHash, '', path].join('\n');
const signStr = [accessKey, t, nonce, stringToSign].join('');
const sign = crypto
.createHmac('sha256', secretKey)
.update(signStr, 'utf8')
.digest('hex')
.toUpperCase();
const { data } = await axios({
// 不同的地区需要使用不同的域名地址,这里为中国区地址
url: `https://openapi.tuyacn.com/v1.0/token?code=${code}&grant_type=2`,
method: 'GET',
headers: {
t,
sign,
client_id: accessKey,
sign_method: 'HMAC-SHA256',
Dev_lang: 'Nodejs',
'Signature-Headers': '',
},
});
let responseData;
if (data.success) {
responseData = {
success: true,
result: {
sessionId: '1234567890', // 服务端自己生成一个唯一id,用于管理小程序登录状态
},
};
} else {
responseData = {
success: false,
errMsg: data.msg,
errCode: data.code,
};
}
ctx.body = responseData;
});
app.use(bodyParser()).use(router.allowedMethods()).use(router.routes());
app.listen(3000, () => {
console.log('Server start on http://localhost:3000');
});