coding
最代码官方的gravatar头像
最代码官方2015-01-07 16:58:38

springmvc开发微信公众平台验证token接口教程及其java源代码分享

今天研究了下微信公众平台的接入机制,给大家分享下相关的经验和代码。

首先需要在微信公众平台的后台修改开发者中心的配置:

如下图

springmvc开发微信公众平台验证token接口教程及其java源代码分享

步骤2

springmvc开发微信公众平台验证token接口教程及其java源代码分享

点击提交后会带验证参数请求你填写的URL,如下nginx会接受到类似请求:

springmvc开发微信公众平台验证token接口教程及其java源代码分享

springmvc实现代码如下:

WeixinController.java

package com.javaniu.www.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.javaniu.core.constants.GlobalConstants;
import com.javaniu.core.controller.BaseController;

/**
 * *@author zuidaima 2015-01-07 22:27:22
 */

@Controller
@RequestMapping("weixin")
public class WeixinController extends BaseController {

	@RequestMapping(value = { "signature" }, method = RequestMethod.GET)
	public void signature(
			@RequestParam(value = "signature", required = true) String signature,
			@RequestParam(value = "timestamp", required = true) String timestamp,
			@RequestParam(value = "nonce", required = true) String nonce,
			@RequestParam(value = "echostr", required = true) String echostr,
			HttpServletResponse response) throws IOException {
		String[] values = { GlobalConstants.WEIXIN_TOKEN, timestamp, nonce };
		Arrays.sort(values); // 字典序排序
		String value = values[0] + values[1] + values[2];
		String sign = DigestUtils.shaHex(value);
		PrintWriter writer = response.getWriter();
		if (signature.equals(sign)) {// 验证成功返回ehcostr
			writer.print(echostr);
		} else {
			writer.print("error");
		}
		writer.flush();
		writer.close();
	}
}

注意sha1加密算法用的是apache的commons codec,需要在maven中加入依赖:(其他springmvc的maven依赖请参考我分享过的其他项目)

<dependency>  
        <groupId>commons-codec</groupId>  
        <artifactId>commons-codec</artifactId>  
        <version>1.10</version>  
</dependency>  

或者通过http://www.findjar.com搜索


打赏

已有3人打赏

章鱼哥的gravatar头像静吟秋的gravatar头像junenv的gravatar头像

顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友