赖老师 發表於 2023-5-26 10:58:00

微信公众号开发接入

<h1 id="微信公众号开发">微信公众号开发</h1>
<h2 id="准备工作">准备工作</h2>
<p>你要有一个微信公众号,一个内网穿透工具</p>
<h2 id="相关网站">相关网站</h2>
<ul>
<li>微信公众号:https://mp.weixin.qq.com/</li>
<li>官网文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html</li>
</ul>
<h2 id="需要资料">需要资料</h2>
<ul>
<li>服务器配置:设置与开发--&gt;基本配置--&gt;服务器配置</li>
<li>token:3-32字符,自己生成配置到服务器配置</li>
<li>公网 IP:云服务器一般都有公网IP</li>
<li>内网穿透工具:本地测试需要穿透,否则无法对接。花生壳、natapp 等自行百度</li>
</ul>
<h2 id="注意事项">注意事项</h2>
<ol>
<li>请求URL超时,说明内网穿透有问题</li>
<li>微信验证消息和推送消息事件接口是同一地址,<strong>验证消息是<code>GET</code>请求 ,事件推送消息是<code>POST</code></strong>。</li>
<li>验证成功接口需要给微信<strong>原样返回随机字符串(echostr)</strong>内容,否则配置失败</li>
<li><strong>响应类型(Content-Type) 一定要是 <code>text/plan</code></strong></li>
<li>切记自己对接的系统要是有权鉴,一定要放行微信消息验证接口</li>
</ol>
<h2 id="代码示例">代码示例</h2>
<h3 id="消息验证">消息验证</h3>
<pre><code class="language-java">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);
    }
}
</code></pre>
<h3 id="事件推送">事件推送</h3>
<pre><code class="language-java">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&lt;String, Object&gt; map = null;
      try {
            map = XmlUtil.parseXMLToMap(request.getInputStream());
      } catch (IOException e) {
            e.printStackTrace();
      }
      log.debug("事件消息体:{}", map);

      this.responseText("", response); // 回复空串,微信服务器不会对此作任何处理
    }

}
</code></pre>
<h3 id="完整代码">完整代码</h3>
<pre><code class="language-java">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&lt;String, Object&gt; 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 &lt; 3; i++) {
                sb.append(array);
            }
            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 &lt; digest.length; i++) {
                shaHex = Integer.toHexString(digest &amp; 0xFF);
                if (shaHex.length() &lt; 2) {
                  hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
      } catch (Exception e) {
            e.printStackTrace();
      }
      return null;
    }

}

</code></pre>
<h2 id="响应结果">响应结果</h2>
<h3 id="消息验证-1">消息验证</h3>
<pre><code class="language-text">signature:207e05105427e1203e769245b3860212c0ffcc56
echostr:5692172970033782203
timestamp:1685068850
nonce:499790541
signature:207e05105427e1203e769245b3860212c0ffcc56
sha1:207e05105427e1203e769245b3860212c0ffcc56
成功
</code></pre>
<h3 id="事件推送-1">事件推送</h3>
<p>打开公众号发送消息,接口就可以获取到推送事件消息内容了</p>
<pre><code class="language-json">{"Content":"嘻嘻嘻","CreateTime":"1685068967","ToUserName":"gh_2121212a95","FromUserName":"333333333nSg8OlaSuB0d-f8FKZo","MsgType":"text","MsgId":"24124387253374797"}
</code></pre>
<h2 id="其他信息">其他信息</h2>
<p>公众号配置<br>
<img src="https://img2023.cnblogs.com/blog/1473548/202305/1473548-20230526105613298-2134293619.png"></p>
<p>内网穿透<br>
<img src="https://img2023.cnblogs.com/blog/1473548/202305/1473548-20230526105710256-707807903.png"></p>


</div>
<div id="MySignature" role="contentinfo">
    哇!又赚了一天人民币<br><br>
来源:https://www.cnblogs.com/bxmm/p/17434191.html
頁: [1]
查看完整版本: 微信公众号开发接入