新手初學node.js進行微信開發,在申請接入微信公衆平臺開發測試號時,因爲官方給出的樣例只針對PHP與java等其它方式代碼,而node初學者看不太明白,在提交接口測試URL時,每每不成功,提示「配置失敗」,這裏給出申請微信測試號,接口配置信息的node.js代碼實現,申請域名、解析、開通主機,申請SSL證書等過程,網上教程開發文檔有詳細說明,不在贅述。java
一、點擊申請測試號,得到appID與appsecret信息,填寫服務器配置
二、編寫node.js驗證代碼以下,引用的koa sha1等包文件,提早npm install安裝好:node
npm install --save koa koa-sslify sha1 fs
/* 微信公衆號 Node.js Koa + SSL 測試接口接入驗證 token: 你的 TOKEN signature: 微信加密簽名校驗內容,sha1([token,timestamp,nonce].sort()) nonce: 隨機數 timestamp: 時間戳 ecostr: 隨機字符串 sha: 你的校驗簽名,計算結果須要與 signature 一致 */ const Koa = require("koa"); const http = require("http"); const https = require("https"); const fs = require("fs"); const sha1 = require('sha1') const { default: enforceHttps } = require("koa-sslify"); const config = { wechat: { appID: "wxbxxxxx........", appSecret: "a95xxxxx...........", token: "segmentfault........." } }; // 生成服務器實例 const app = new Koa(); // Force HTTPS using default resolver // 使用默認解析強制使用 HTTPS app.use( enforceHttps({ port: 443 }) ); // index page 加載微信驗證認證中間件 // ctx 是 Koa 的應用上下文 // next 就是串聯中間件的鉤子函數 app.use(async (ctx, next) => { const { signature, timestamp, nonce, echostr } = ctx.query const token = config.wechat.token // 進行字典排序加密 let str = [token, timestamp, nonce].sort().join(""); let sha = sha1(str) // 校驗微信加密簽名,返回echostr內容 if (sha === signature) { ctx.body = echostr } else { ctx.body = "wrong" } // ctx.body = "hello world from " + ctx.request.url; }); // SSL options var options = { key: fs.readFileSync("./ssl/privkey.pem"), // SSL私鑰 cert: fs.readFileSync("./ssl/fullchain.pem"), // SSL證書 requestCert: false, //是否請求客戶端證書 rejectUnauthorized: false //是否拒絕無信任CA頒發的證書的客戶端鏈接請求 }; // start the server http.createServer(app.callback()).listen(80); https.createServer(options, app.callback()).listen(443); console.log("WechatCheck Server Start => HTTP:80 => HTTPS:443......");
三、提交配置信息,驗證消息的確來自你的微信服務器npm
相關說明,能夠參考微信開發文檔的接入指南。segmentfault