您的位置:首页 > 移动开发 > 微信开发

如何验证成为微信开发者

2017-11-05 23:03 1006 查看

1.填写服务器配置

    主要填写URL、Token。

2.验证消息的确来自微信服务器

    微信公众平台开发者文档内容如下:

    如果提交第一步的信息,微信服务器将发送GET请求到填写的服务器地址URL上。

    GET请求携带参数如下表所示:

    signature:微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。

    timestamp:时间戳

    nonce:随机数

    echostr:随机字符串

    开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:

    1)将token、timestamp、nonce三个参数进行字典序排序

    2)将三个参数字符串拼接成一个字符串进行sha1加密

    3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

    代码实现如下:

    首先,我们添加一个工具类,然后在工具类中我们编写一个用于检验signature的方法。

public class CheckUtil {

private static final String token="xiaoma1hao";
public static Boolean checkSignature(String signature,String timestamp,String nonce){

String[] arr=new String[]{token,timestamp,nonce};

//排序
Arrays.sort(arr);

//生成字符串
StringBuilder content=new StringBuilder();
for(int i=0;i<arr.length;i++){
content.append(arr[i]);
}

//sha1加密
String temp=SHA1(content.toString());//这个方法去网上下载一个

return temp.equals(signature);
}

/**
* SHA1加密
*/
public final static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}


    然后,在我们填写的服务器url对应的servlet里,我们重写一下doGet()方法。

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
String signature=request.getParameter("signature");
String timestamp=request.getParameter("timestamp");
String nonce=request.getParameter("nonce");
String echostr=request.getParameter("echostr");

PrintWriter out=response.getWriter();
if(CheckUtil.checkSignature(signature,timestamp,nonce)){
out.write(echostr);
}
}


    这样,java代码实现就完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: