你的位置:首页 > Java教程

[Java教程]微信公众号开发(一)


现在主流上都用php写微信公众号后台,其实作为后端语言之一的java也可以实现。

这篇文章将对验证服务器地址这一步做出实现。

参考资料:1.慕课网-《初识java微信公众号开发》,2.微信公众号开发者文档http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html

如图,开发者在点击提交后,微信服务器向公众号后台服务器发送了四个参数,咱们把这四个参数封装成一个类,就叫Signature吧

代码都是myeclipse自动生成的(导包代码已省略,由于视图关系丢失了缩进)

public class Signature {
private String signature;
private String timestamp;
private String nonce;
private String echostr;

public Signature() {
super();
// TODO Auto-generated constructor stub
}

public Signature(String signature, String timestamp, String nonce,
String echostr) {
super();
this.signature = signature;
this.timestamp = timestamp;
this.nonce = nonce;
this.echostr = echostr;
}

public String getSignature() {
return signature;
}

public void setSignature(String signature) {
this.signature = signature;
}

public String getTimestamp() {
return timestamp;
}

public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}

public String getNonce() {
return nonce;
}

public void setNonce(String nonce) {
this.nonce = nonce;
}

public String getEchostr() {
return echostr;
}

public void setEchostr(String echostr) {
this.echostr = echostr;
}

@Override
public String toString() {
return "Signature [signature=" + signature + ", timestamp=" + timestamp
+ ", nonce=" + nonce + ", echostr=" + echostr + "]";
}

}

之后编写servlet,对四个参数进行接收,new 一个Signarure对象,

public class WeixinServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

Signature sg = new Signature(req.getParameter("signature"),req.getParameter("timestamp"),
req.getParameter("nonce"),req.getParameter("echostr"));

PrintWriter out = resp.getWriter();
if(CheckUtil.checkSignature(sg)){
out.print(sg.getEchostr());
}

}
}

新建CheckUtil类实现校验逻辑

public class CheckUtil {

private static final String token = "userwang";

public static boolean checkSignature(Signature sg){

String[] arr = new String[]{token,sg.getTimestamp(),sg.getNonce()};
//排序
Arrays.sort(arr);
//生成字符串
StringBuffer content = new StringBuffer();
for(int i=0;i<arr.length;i++){
content.append(arr[i]);
}

//sha1加密
String temp = getSha1(content.toString());
//比较
return temp.equals(sg.getSignature());
}

//加密算法
public static String getSha1(String str){
if(str == null || str.length()==0){
return null;
}

char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
try{
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;

for(int i = 0;i<j;i++){
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}

return new String(buf);
}catch(Exception e){
return null;
}

}
}

 

在web.

另外推荐一个好用的ngrok内网映射工具(站内有使用教程),用于本地调试

www.ngrok.cc