微信公眾號開發接入

2023-05-26 12:01:12

微信公眾號開發

準備工作

你要有一個微信公眾號,一個內網穿透工具

相關網站

需要資料

  • 伺服器設定:設定與開發-->基本設定-->伺服器設定
  • token:3-32字元,自己生成設定到伺服器設定
  • 公網 IP:雲伺服器一般都有公網IP
  • 內網穿透工具:本地測試需要穿透,否則無法對接。花生殼、natapp 等自行百度

注意事項

  1. 請求URL超時,說明內網穿透有問題
  2. 微信驗證訊息和推播訊息事件介面是同一地址,驗證訊息是GET請求 ,事件推播訊息是POST
  3. 驗證成功介面需要給微信原樣返回隨機字串(echostr)內容,否則設定失敗
  4. 響應型別(Content-Type) 一定要是 text/plan
  5. 切記自己對接的系統要是有權鑑,一定要放行微信訊息驗證介面

程式碼範例

訊息驗證

public void pushGet(HttpServletRequest request, HttpServletResponse response) {
    String signature = request.getParameter("signature"); // 簽名
    String echostr = request.getParameter("echostr"); // 隨機字串
    String timestamp = request.getParameter("timestamp"); // 時間戳
    String nonce = request.getParameter("nonce"); // 亂數
    log.debug("signature:{}", signature);
    log.debug("echostr:{}", echostr);
    log.debug("timestamp:{}", timestamp);
    log.debug("nonce:{}", nonce);
    System.out.println("signature:" + signature);
    String sha1 = getSHA1(token, timestamp, nonce);
    System.out.println("sha1:" + sha1);
    if (sha1.equals(signature)) {
        log.debug("成功");
        this.responseText(echostr, response);
    }
}

事件推播

public void pushPost(HttpServletRequest request, HttpServletResponse response) {
    String signature = request.getParameter("signature"); // 簽名
    String timestamp = request.getParameter("timestamp"); // 時間戳
    String nonce = request.getParameter("nonce"); // 亂數
    String sha1 = getSHA1(token, timestamp, nonce);
    if (sha1.equals(signature)) {
        Map<String, Object> map = null;
        try {
            map = XmlUtil.parseXMLToMap(request.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("事件訊息體:{}", map);

        this.responseText("", response); // 回覆空串,微信伺服器不會對此作任何處理
    }

}

完整程式碼

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.*;

/**
 * @description: 微信設定
 * @author: Mr.Fang
 * @create: 2023-05-26
 **/
@Api(tags = "微信設定")
@Slf4j
@RestController
@RequestMapping("/wx/")
public class WxController {

    String token="78******23";

    @ApiOperation(value = "微信 token URL 驗證")
    @GetMapping(value = "push")
    public void pushGet(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature"); // 簽名
        String echostr = request.getParameter("echostr"); // 隨機字串
        String timestamp = request.getParameter("timestamp"); // 時間戳
        String nonce = request.getParameter("nonce"); // 亂數
        log.debug("signature:{}", signature);
        log.debug("echostr:{}", echostr);
        log.debug("timestamp:{}", timestamp);
        log.debug("nonce:{}", nonce);
        System.out.println("signature:" + signature);
        String sha1 = getSHA1(token, timestamp, nonce);
        System.out.println("sha1:" + sha1);
        if (sha1.equals(signature)) {
            log.debug("成功");
            this.responseText(echostr, response);
        }
    }

    @ApiOperation(value = "接收微信事件")
    @PostMapping(value = "push")
    public void pushPost(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature"); // 簽名
        String timestamp = request.getParameter("timestamp"); // 時間戳
        String nonce = request.getParameter("nonce"); // 亂數
        String sha1 = getSHA1(token, timestamp, nonce);
        if (sha1.equals(signature)) {
            Map<String, Object> map = null;
            try {
                // input 流返回是 xml 格式 這裡轉 map 了
                map = XmlUtil.parseXMLToMap(request.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.debug("事件訊息體:{}", map);

            this.responseText("", response); // 回覆空串,微信伺服器不會對此作任何處理
        }

    }

    /**
     * 返回響應結果
     *
     * @param text     響應內容
     * @param response
     */
    public void responseText(String text, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plan;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(text);
        writer.flush();
        writer.close();
    }

    /**
     * 用SHA1演演算法生成安全簽名
     *
     * @param token     票據
     * @param timestamp 時間戳
     * @param nonce     隨機字串
     * @return 安全簽名
     */
    public String getSHA1(String token, String timestamp, String nonce) {
        try {
            String[] array = new String[]{token, timestamp, nonce};
            StringBuffer sb = new StringBuffer();
            // 字串排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1簽名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

響應結果

訊息驗證

signature:207e05105427e1203e769245b3860212c0ffcc56
echostr:5692172970033782203
timestamp:1685068850
nonce:499790541
signature:207e05105427e1203e769245b3860212c0ffcc56
sha1:207e05105427e1203e769245b3860212c0ffcc56
成功

事件推播

開啟公眾號傳送訊息,介面就可以獲取到推播事件訊息內容了

{"Content":"嘻嘻嘻","CreateTime":"1685068967","ToUserName":"gh_2121212a95","FromUserName":"333333333nSg8OlaSuB0d-f8FKZo","MsgType":"text","MsgId":"24124387253374797"}

其他資訊

公眾號設定

內網穿透