由于近期刚开始学习微信开发,在网上查询整理了php与java两个版本的微信接口对接代码。
以下是php版本
define("TOKEN", "token");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
public function valid()
{
//随机字符串
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
private function checkSignature()
{
//微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
$signature = $_GET["signature"];
//时间戳
$timestamp = $_GET["timestamp"];
//随机数
$nonce = $_GET["nonce"];
$token =TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
//将token、timestamp、nonce三个参数进行字典排序
sort($tmpArr);
$tmpStr = implode( $tmpArr );
//sha1加密
$tmpStr = sha1( $tmpStr );
//将加密后的字符串比较,验证接口
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
java版(SSM框架)
@RequestMapping(method = RequestMethod.GET)
public void get(HttpServletRequest request, HttpServletResponse response) {
//微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
String signature = request.getParameter("signature");
//时间戳
String timestamp = request.getParameter("timestamp");
//随机数
String nonce = request.getParameter("nonce");
//随机字符串
String echostr = request.getParameter("echostr");
PrintWriter out = null;
try {
out = response.getWriter();
//验证签名
if (SignUtil.checkSignture(signature, timestamp, nonce)) {
out.print(echostr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
out = null;
}
}
SignUtil.java
public static boolean checkSignture(String signature, String timestamp, String nonce) {
String[] arr = new String[]{Constant.TOKEN, timestamp, nonce};
//将token、timestamp、nonce三个参数进行字典排序
Arrays.sort(arr);
StringBuilder conntent = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
conntent.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(conntent.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
conntent = null;
//将sha1加密后的字符串与signature对比
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}