nodejs正确版 图片上传/v3/merchant/media/upload
主要问题在理解request模块multipart/form-data处理方式 不是拼接BODYconst mchid ='商户id' const serial_no='证书编号' const nonce_str=random_str(32) const method='POST' const api_path='/v3/merchant/media/upload' const fs = require('fs') var header_txt='WECHATPAY2-SHA256-RSA2048' var timestamp=Date.now().toString() var timestamp=timestamp.substr(0,10) var pic_buffer = fs.readFileSync('ad2.jpg') var pic_sign=pic2_sha256(pic_buffer) var fileinfo={}//meta信息 fileinfo.filename='ad2.jpg' fileinfo.sha256=pic_sign var parm_string=method+'\n'+api_path+'\n'+timestamp+'\n'+nonce_str+'\n'+JSON.stringify(fileinfo)+'\n' var parm_sign=rsasha256(parm_string) header_txt=header_txt+' mchid=\"'+mchid+'\",nonce_str=\"'+nonce_str+'\",timestamp=\"'+timestamp+'\",serial_no=\"'+serial_no+'\",signature=\"'+parm_sign+'\"' const formData = { //body内容 'meta':JSON.stringify(fileinfo), 'file': { value: pic_buffer, options: { filename: 'ad2.jpg', contentType: 'image/jpg' } } } var request = require('request') var options = { method: 'POST', url: 'https://api.mch.weixin.qq.com/v3/merchant/media/upload', headers: { 'Charsert':'UTF-8', 'Accept':'application/json', 'Content-Type':'multipart/form-data; boundary=boundary123', 'Authorization': header_txt, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36' }, formData:formData }; request(options, function (error, response) { if (error) throw new Error(error); console.log(response.body); }); function wx2_sha256(str){ const crypto = require('crypto'); var fs = require('fs') var prvKey = fs.readFileSync('apiclient_key.pem','utf-8'); let enc_by_prv = crypto.privateEncrypt(prvKey, Buffer.from(str, 'utf8')); return enc_by_prv.toString('base64') } function pic2_sha256(pic_buffer){ const crypto=require('crypto') var obj=crypto.createHash('sha256') obj.update(pic_buffer) var str=obj.digest('hex') return str } function random_str(length) { var str = Math.random().toString(36).substr(2); if (str.length>=length) { return str.substr(0, length); } str = str+random_str(length-str.length); return str; } 结果: [图片]