微信公眾號token介面springboot
阿新 • • 發佈:2018-12-14
需要微信公眾號測試號、natapp(這個是可以讓外網訪問你本地的東西,免費的)、springboot.
首先是測試號要配置伺服器資訊:
在沒配置好之前提交是失敗的!!!為什麼會失敗,是因為提交相當於發起一次請求,你沒配置好發的請求就不懂去哪裡了。
所有先配置好其它東西才可以提交。
natapp(這個是可以讓外網訪問你本地的東西,免費的),可以看相關教程很簡單的幾步,natapp官網:https://natapp.cn/
配置好用80埠,不用80的話就用nginx反向代理80埠(測試就不用nginx)
下面是controller和一個介面類,String token = "xxx";這裡的xxx要和微信公眾號測試的Token一樣
WxUrlRequest:
import com.yifan.Service.WeChatService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 微信介面Token * */ @RestController @RequestMapping("/wx") public class WxUrlRequest { private final static Logger LOG = LoggerFactory.getLogger(WxUrlRequest.class); /** * 接入微信服務 * @param request * @param response */ @Autowired private WeChatService wechatservice; @RequestMapping(value="/urlR",method= RequestMethod.GET) public void index(HttpServletRequest request, HttpServletResponse response){ LOG.info("微信接入伺服器"); String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String token = "xxx"; String echostr = request.getParameter("echostr"); if (wechatservice.verifyInfo(signature, timestamp, nonce, token)) { LOG.info("echostr為:{}", echostr); if (echostr != null) { try { response.getWriter().write(echostr); } catch (IOException e) { e.printStackTrace(); } } } else { LOG.info("signature為:{}", signature); LOG.info("timestamp為:{}", timestamp); LOG.info("nonce為:{}", nonce); LOG.info("token為:{}", token); } } }
WeChatService:
import org.apache.commons.codec.digest.DigestUtils; import org.springframework.stereotype.Service; import java.util.TreeSet; @Service public class WeChatService { public Boolean verifyInfo(String signature, String timestamp, String nonce, String token) { TreeSet<String> set = new TreeSet<String>(); set.add(token); set.add(timestamp); set.add(nonce); StringBuilder sBuilder = new StringBuilder(); for (String item : set) { sBuilder.append(item); } String sign = DigestUtils.sha1Hex(sBuilder.toString()); return signature.equalsIgnoreCase(sign); } }
別忘了springboot的tomcat埠改為80;
啟動好natapp和springboot就可以到微信測試號那裡提交域名了