Nodejs自有阿里云如何对接微信的imgSecCheck?

Nodejs这类的语言,一行代码就能实现很多功能,很省事。但当你要实现一个功能,百度一下午,都不知道咋写的时候,就很怀念使用C/C++的日子了。

同样的代码用Java实现也不复杂,因为Java是同步的,可偏偏nodejs又是异步的。nodejs用得少,你不知道它都有些什么神奇的函数,有什么神奇的写法。

需求:从一个私有云中下载图片,上传到微信后台进行校验。

结果,网上没一个人写的能直接copy;经过无数次尝试,最终使用下面的函数成功。

const queryWeixinCheck = async(param) => {
  return new Promise((resolve, reject)=>{
    request({
        url: 'https://api.weixin.qq.com/wxa/img_sec_check?access_token=' + param.access_token,
        method: "POST",
        formData: {
            buffer: {
                value:  request(param.url),
                options: {
                    filename: param.filename,
                    contentType: 'image/' + param.extname
                }
            },
        },
    },(error, response, body) => {
          error ? reject(error) : resolve(JSON.parse(body));
    })
  });
}

参考文档:

https://www.runoob.com/nodejs/nodejs-stream.html

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html

下面这个链接,有个哥们跟我想的一样,直接用

curl -F media=@test.jpg 'https://api.weixin.qq.com/wxa/img_sec_check?access_token=ACCESS_TOKEN'

请求之后抓包,再用nodejs拼接出一个报文也实现了,但代码不太美观,不选他的。

https://developers.weixin.qq.com/community/develop/doc/000486c0fbc558719d89a281c51800?_at=1577033510988

附:抓包的结果是这样的

POST /photo/api/mangement/getAccessToken HTTP/1.1
User-Agent: curl/7.29.0
Host: 112.74.68.252:8091
Accept: */*
Content-Length: 98934
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------fa0769e47e5c

HTTP/1.1 100 Continue

------------------------------fa0769e47e5c
Content-Disposition: form-data; name="media"; filename="zf.png"
Content-Type: application/octet-stream

.PNG
.
...
IHDR...b...
.....AQuq....sRGB.........gAMA..(省略一张图片的大小)....a......(6.E..PG....HTTP/1.1 404 Not Found
X-Served-By: Koa
Content-Type: text/plain; charset=utf-8
Content-Length: 9
Date: Wed, 08 Apr 2020 01:43:35 GMT
Connection: keep-alive

Not Found

笔记:

nodejs下载图片

request(img_url).pipe(fs.createWriteStream(temp_file.path));

nodejs读取图片

fs.readFileSync(temp_file.path)