微信公眾平臺開發接入指南

ez1078 8年前發布 | 9K 次閱讀 加密解密

在進行微信公眾平臺開發之前,需要先接入微信公眾平臺。具體的步驟在 公眾平臺開發者文檔-接入指南 已有詳細介紹,文檔中也提供了驗證服務器的 PHP 示例代碼。

本文主要提供了 Node.js 版本的驗證代碼,同時把步驟細化,讓開發者更方便地了解整個接入過程,對初學者更友好。

TL;DR

在微信公眾平臺后臺的 開發者中心/填寫服務器配置 頁面,配置好 URL 和 Token 后,復制下面的代碼,修改 Token,在服務器運行,然后再在頁面上點擊提交即可進行接入驗證。

// checkSignature.js
/**
 * 整個驗證步驟分為三步
 *    1. 將token、timestamp、nonce三個參數進行字典序排序
 *    2. 將三個參數字符串拼接成一個字符串進行sha1加密
 *    3. 開發者獲得加密后的字符串可與signature對比,標識該請求來源于微信
 */


const http = require('http');
const url = require('url');
const crypto = require('crypto');


// Web 服務器端口
const port = 3333;
// 微信公眾平臺服務器配置中的 Token
const token = 'token';


/**
 *  對字符串進行sha1加密
 * @param  {string} str 需要加密的字符串
 * @return {string}     加密后的字符串
 */
function sha1(str) {
  const md5sum = crypto.createHash('sha1');
  md5sum.update(str);
  const ciphertext = md5sum.digest('hex');
  return ciphertext;
}

/**
 * 驗證服務器的有效性
 * @param  {object} req http 請求
 * @param  {object} res http 響應
 * @return {object}     驗證結果
 */
function checkSignature(req, res) {
  const query = url.parse(req.url, true).query;
  console.log('Request URL: ', req.url);
  const signature = query.signature;
  const timestamp = query.timestamp;
  const nonce = query.nonce;
  const echostr = query.echostr;
  console.log('timestamp: ', timestamp);
  console.log('nonce: ', nonce);
  console.log('signature: ', signature);
  // 將 token/timestamp/nonce 三個參數進行字典序排序
  const tmpArr = [token, timestamp, nonce];
  const tmpStr = sha1(tmpArr.sort().join(''));
  console.log('Sha1 String: ', tmpStr);
  // 驗證排序并加密后的字符串與 signature 是否相等
  if (tmpStr === signature) {
    // 原樣返回echostr參數內容
    res.end(echostr);
    console.log('Check Success');
  } else {
    res.end('failed');
    console.log('Check Failed');
  }
}


const server = http.createServer(checkSignature)
server.listen(port, () => {
  console.log(`Server is runnig ar port ${port}`);
  console.log('Start Checking...');
});

填寫服務器配置

登錄進入微信公眾平臺后臺管理頁面

然后進入 基本配置 頁面

再然后選擇 修改配置 ,進入到 填寫服務器配置 子頁面

  • URL 為已經解析到你的服務器的域名,這里以 http://wechat.nodejh.com 這個二級域名為例

  • Token 隨意填寫即可

驗證服務器地址的有效性

驗證服務器地址的有效性,需要在域名對應的服務器上運行一段驗證程序。該程序會接收上個步驟中的域名所發送的 HTTP 請求。

官方文檔提供了 PHP 的示例程序,下面是 Node.js 版本:

// checkSignature.js
/**
 * 整個驗證步驟分為三步
 *    1. 將token、timestamp、nonce三個參數進行字典序排序
 *    2. 將三個參數字符串拼接成一個字符串進行sha1加密
 *    3. 開發者獲得加密后的字符串可與signature對比,標識該請求來源于微信
 */


const http = require('http');
const url = require('url');
const crypto = require('crypto');


// Web 服務器端口
const port = 3333;
// 微信公眾平臺服務器配置中的 Token
const token = 'token';


/**
 *  對字符串進行sha1加密
 * @param  {string} str 需要加密的字符串
 * @return {string}     加密后的字符串
 */
function sha1(str) {
  const md5sum = crypto.createHash('sha1');
  md5sum.update(str);
  const ciphertext = md5sum.digest('hex');
  return ciphertext;
}

/**
 * 驗證服務器的有效性
 * @param  {object} req http 請求
 * @param  {object} res http 響應
 * @return {object}     驗證結果
 */
function checkSignature(req, res) {
  const query = url.parse(req.url, true).query;
  console.log('Request URL: ', req.url);
  const signature = query.signature;
  const timestamp = query.timestamp;
  const nonce = query.nonce;
  const echostr = query.echostr;
  console.log('timestamp: ', timestamp);
  console.log('nonce: ', nonce);
  console.log('signature: ', signature);
  // 將 token/timestamp/nonce 三個參數進行字典序排序
  const tmpArr = [token, timestamp, nonce];
  const tmpStr = sha1(tmpArr.sort().join(''));
  console.log('Sha1 String: ', tmpStr);
  // 驗證排序并加密后的字符串與 signature 是否相等
  if (tmpStr === signature) {
    // 原樣返回echostr參數內容
    res.end(echostr);
    console.log('Check Success');
  } else {
    res.end('failed');
    console.log('Check Failed');
  }
}


const server = http.createServer(checkSignature)
server.listen(port, () => {
  console.log(`Server is runnig ar port ${port}`);
  console.log('Start Checking...');
});

因為驗證要使用 80(HTTP) 端口或 443(HTTPS) 端口,而 Node.js 一般不直接監聽 80 端口,所以需要使用 Nginx 或其他程序將來自 http://wechat.nodejh.com 的請求轉發到 Node.js 程序端口如上面的 3333。

這里也順便給出該程序的 Nginx 配置

upstream nodejs {
    server 127.0.0.1:3333;
    keepalive 64;
}

server {
    listen 80;
    server_name wechat.nodejh.com;
    # 日志
    access_log /var/log/nginx/wechat.nodejh.com.log;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host  $http_host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_set_header Connection "";
        proxy_pass http://nodejs;
    }
}

配置就緒之后,啟動驗證程序

$ node checkSignature.js
Server is runnig ar port 3333
Start Checking...

這樣, checkSignature.js 就會創建一個 3333 端口的服務。訪問 http://wechat.nodejh.com 這個域名的時候,Nginx 就會將請求轉發到 3333 端口。

在微信公眾平臺后臺管理的服務器配置頁面,點擊提交按鈕,就會填寫的 URL (這里是 http://wechat.nodejh.com )發送一個 HTTP 請求,并帶上 signature,timestamp,nonce,echostr 這四個參數。

啟動 checkSignature.js 后,在服務器配置頁面,點擊提交按鈕,就會開啟驗證。

服務器端出現下面的結果,就說明驗證成功。驗證成功后,微信公眾平臺后臺會自動跳轉到 基本配置 頁面。

# 服務端響應...
signature:  8fffb8f011d64819ec61105415114694bb03d392
Sha1 String:  8fffb8f011d64819ec61105415114694bb03d392
Check Success

然后就可以依據接口文檔實現業務邏輯了。

 

 

來自:https://segmentfault.com/a/1190000007701020

 

 本文由用戶 ez1078 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!