使用nodejs調用微信發送紅包

    前置條件:申請微信發送紅包的帳戶及其權限javascript

    依賴 blueimg-md5和 xmlreader 庫java

 

   

/common/weixin.js 源碼json

/**
 * Created by chent696 on 2015/2/7.
/common/weixin.js */ /* 拼接微信紅包xml串 */ /* serverConfig.json 文件內容 "clientIp":"222.73.202.251", "showName":"i8小時", " luckyMoneyWishing":"恭喜發財", "mch_id":"", // "wxkey":"", // "wxappid":"" // */ var serverConfig = require('../config/serverConfig.json'); var xmlreader = require('xmlreader'); //須要安裝 xmlreader包 var fs = require('fs'); var https = require('https'); var MD5=require('blueimp-md5').md5; var fnCreateXml = function(json){ var _xml = ''; for(var key in json) { _xml+= '<'+key+'>'+json[key]+'</'+key+'>'; } return _xml; } /* 生成url串用於微信md5校驗 */ var fnCreateUrlParam = function(json){ var _str = ''; var _arr = [] for(var key in json){ _arr.push(key+'='+json[key]); } return _arr.join('&'); } /* 生成微信紅包數據 */ var fnGetWeixinBonus = function(option){ var _option = option || {}; var _min_value = _option.min_value ||100, //紅包最小金額 _max_value = _option.max_value || 100, //紅包最大金額 _total_amount = _option.total_amount || 100, //紅包總金額 _re_openid = _option.re_openid || 'omNdNuCzOuYOm5aBr1-B5hhUS1JI', //紅包發送的目標用戶 _total_num = _option.total_num || 1; //紅包個數 var _now = new Date(); var _showName = serverConfig.showName; var _clientIp = serverConfig.clientIp; var _wishing = serverConfig.luckyMoneyWishing; var _mch_id = serverConfig.mch_id; var _wxappid = serverConfig.wxappid, _wxkey = serverConfig.wxkey; var _date_time = _now.getFullYear()+''+(_now.getMonth()+1)+''+_now.getDate(); var _date_no = (_now.getTime() +'').substr(-8); //生成8爲日期數據,精確到毫秒 var _random_no = Math.floor(Math.random()*99); if(_random_no<10){ //生成位數爲2的隨機碼 _random_no = '0'+_random_no; } var _muc_id = _mch_id;//'1230184802'; var _xmlTemplate = '<xml>{content}</xml>'; var _contentJson = {}; _contentJson.act_name = _showName;// '新年紅包'; _contentJson.client_ip = _clientIp; _contentJson.max_value = _max_value;//'100'; _contentJson.mch_billno =_muc_id +_date_time+ _date_no+_random_no; //訂單號爲 mch_id + yyyymmdd+10位一天內不能重複的數字; //+201502041234567893'; _contentJson.mch_id =_muc_id; //_contentJson.logo_imgurl = ''; _contentJson.min_value = _min_value;// '100'; _contentJson.nick_name = _showName; _contentJson.nonce_str = '50780e0cca98c8c8e814883e5caa672e'; _contentJson.re_openid = _re_openid;// 'omNdNuCzOuYOm5aBr1-B5hhUS1JI'; //濤子的openid // 'onqOjjmM1tad-3ROpncN-yUfa6uI'; _contentJson.remark = _wishing; _contentJson.send_name =_showName;// //_contentJson.share_content = ''; //_contentJson.share_share_url = ''; //_contentJson.share_share_imageurl = ''; _contentJson.total_amount = _total_amount;// '100'; _contentJson.total_num = _total_num ;//1; _contentJson.wishing = _wishing;//'恭喜發財'; _contentJson.wxappid = _wxappid;// 'wxbfca079a0b9058d3'; _contentJson.key = _wxkey; var _contentStr = fnCreateUrlParam(_contentJson); console.log('content='+_contentStr); _contentJson.sign = MD5(_contentStr).toUpperCase(); //刪除 key (key不參與簽名) delete _contentJson.key; var _xmlData = fnCreateXml(_contentJson); var _sendData = '<xml>'+_xmlData+'</xml>'; //_xmlTemplate.replace(/{content}/) return _sendData; console.log('xml='+_sendData); } var fnSendMoney = function(req,res,data,callback){ var _host = 'api.mch.weixin.qq.com'; var _path = '/mmpaymkttransfers/sendredpack'; var opt = { host:_host, port:'443', method:'POST', path:_path, key: fs.readFileSync('cert/apiclient_key.pem'), //將微信生成的證書放入 cert目錄下 cert: fs.readFileSync('cert/apiclient_cert.pem') } var body = ''; opt.agent = new https.Agent(opt); var req = https.request(opt, function(res) { console.log("Got response: " + res.statusCode); res.on('data',function(d){ body += d; }).on('end', function(){ //console.log(res.headers); console.log('微信返回消息'); console.log(body); var ret = fnParseReceivedXML(body); //若是回調存在就執行回調函數 if(typeof callback == 'function'){ callback(ret); } }); }).on('error', function(e) { console.log("Got error: " + e.message); }); var _sendData = fnGetWeixinBonus({}); req.write(_sendData); req.end(); } /* 解析微信傳回來得消息 */ var fnParseReceivedXML = function(xmlData){ try { xmlreader.read(xmlData, function (errors, response) { if (null !== errors) { console.log(errors); return; } // console.log( response.xml ); if(response && response.xml && response.xml.return_code) { if((response.xml.return_code.text()||'').toLowerCase() == 'sucess'){ return true; } return false; } return false; }); }catch(e){ console.log('weixin sendmoney error'+ e.message); } } exports.sendLuckyMoney = fnSendMoney;



  

調用方式api

    var common = require('../common/weixin.js');
var _data = {},
_callback = function(ret){

};


common.sendLuckyMoney(_data,_callback);

源碼注:源碼中的證書 appid,商戶id已經刪除,請自行申請
相關文章
相關標籤/搜索