Last active
August 16, 2019 11:39
-
-
Save justan/e5cc564365b389ff8ae30862b7cfd8ff to your computer and use it in GitHub Desktop.
第三方平台授权账号上传云函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 仅限第三方平台授权的账号调用 | |
const crypto = require('crypto') | |
const fs = require('fs') | |
const fsPromises = fs.promises | |
const pt = require('path') | |
const fetch = require('node-fetch') | |
/** | |
* @param {String} opts.env 环境名 | |
* @param {String} opts.functionName 函数名 | |
* @param {String} opts.filePath 需要上传的代码 zip 包路径 | |
* @param {String} opts.accessToken 用户 authorizer_access_token | |
*/ | |
async function main(opts = {}) { | |
let { env: Namespace, functionName: FunctionName, handler: Handler = 'index.main', accessToken, filePath } = opts | |
let ZipFile = await fsPromises.readFile(filePath, 'base64') | |
let uploadBody = JSON.stringify({ | |
Handler, | |
FunctionName, | |
Namespace, | |
ZipFile | |
}) | |
let hashed_payload = crypto.createHash('sha256').update(uploadBody).digest('hex').toLowerCase() | |
let headers = (await (await fetch(`https://api.weixin.qq.com/tcb/getuploadsignature?access_token=${accessToken}`, { | |
method: 'post', | |
body: JSON.stringify({ | |
hashed_payload | |
}), | |
headers: { 'Content-Type': 'application/json' } | |
})).json()).headers | |
console.log(headers) | |
headers = headers.split(/\r\n/).reduce((h, hs) => { | |
let [key, value] = hs.split(':') | |
h[key] = value | |
return h | |
}, {}) | |
console.log(headers) | |
let res = (await (await fetch(`https://scf.tencentcloudapi.com`, { | |
method: 'post', | |
body: uploadBody, | |
headers: { 'Content-Type': 'application/json', ...headers } | |
})).json()) | |
console.log(res) | |
return res | |
} | |
let accessToken = 'YOUR_ACCESSTOKEN_HERE' | |
main({ | |
functionName: 'test', | |
env: 'test-68342c', | |
filePath: pt.join(__dirname, './test.zip'), | |
accessToken | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment