微信公衆平臺開發教程Java版(二)接口配置

微信公衆賬號申請完成後,默認開啓的是編輯模式。

我們需要修改爲開發模式。

 

登陸微信公衆平臺》功能》高級功能

先關閉 編輯模式,再開啓 開發模式。

 

申請成爲開發者,如果是服務號,需要則會有開發者憑證信息

如圖


 

如果是訂閱號,則只顯示服務器配置。

 

下一步就是配置接口服務器了。

在公衆平臺網站的高級功能 – 開發模式頁,點擊“成爲開發者”按鈕,填寫URL和Token,其中URL是開發者用來接收微信服務器數據的接口URL。(這就是我們開發的程序,並部署到公網上了)

Token 官網描述:可由開發者任意填寫,用作生成簽名(該Token會和接口URL中包含的Token進行比對,從而驗證安全性)。

總之就是你的程序裏面寫的token和這裏填入的token要一致。

 



 

 還沒有url和token?

 

首先需要新建一個java web工程。

 

 接下來就要看看驗證url和token了。

 下面是官網的描述,已經寫的很清楚了



 核心實現方式就是將三個參數排序,拼接成字符串進行sha1加密,然後與signature比較

 官網也給了實例,是php的,我們只需要裝換成java就可以了。

private function checkSignature()
{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
	$token = TOKEN;
	$tmpArr = array($token, $timestamp, $nonce);
	sort($tmpArr);
	$tmpStr = implode( $tmpArr );
	$tmpStr = sha1( $tmpStr );
	
	if( $tmpStr == $signature ){
		return true;
	}else{
		return false;
	}
}



 

 

java代碼 我的 WeixinController 類

    我的項目架構是基於spring3.0的,用到了註解。當get請求的時候會執行get方法,post請求的時候會執行post方法,分別來處理不同的請求,各位也可用servlet等去實現,原理都一樣

package com.ifp.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ifp.weixin.biz.core.CoreService;
import com.ifp.weixin.util.SignUtil;

@Controller
@RequestMapping("/weixinCore")
public class WeixinController {

	@Resource(name="coreService")
	private CoreService coreService;
	
	@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();
			// 通過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,否則接入失敗
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
			out = null;
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void post(HttpServletRequest request, HttpServletResponse response) {
		//暫時空着,在這裏可處理用戶請求
	}

}
 

 上面類中用到了SignUtil 類

package com.ifp.weixin.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.ifp.weixin.constant.Constant;
/**
 * 驗證簽名
 *
 */
public class SignUtil {
	

	/**
	 * 驗證簽名
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arr = new String[] { Constant.TOKEN, timestamp, nonce };
		// 將token、timestamp、nonce三個參數進行字典排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 將三個參數字符串拼接成一個字符串進行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		// 將sha1加密後的字符串可與signature對比
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 將字節數組轉換爲十六進制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 將字節轉換爲十六進制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
}

 
 我們看到 checkSignature 這個方法裏使用到了Constant.TOKEN ,這個token,我聲明的一個常量。

 

 要與微信配置接口裏面的token值一樣

/**
* 與接口配置信息中的Token要一致
*/
public static String TOKEN = "infopower";

也貼上web.xml的配置,我的後綴是.html 的請求都交給DispatcherServlet了。

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name>weixinHelp</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/applicationContext.xml</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:/properties/log4j.properties</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
		<description>spring 容器的監聽器</description>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

  

 

 我們的代碼已經寫完了,訪問請求地址試試



 

什麼都沒有顯示,看看後臺



 

報空指針異常

 

別擔心,我們的代碼沒問題。

因爲直接訪問地址,默認是get請求,而什麼參數都沒有傳給後臺,當然會報空指針

前臺沒有異常,是因爲我做了異常處理。

ok

 

接下來就是把代碼打成war包發佈到外網。

然後填入相應的url和token,接口的配置就完成了。

 

注意1:一定要發佈war包到外網,配置外網的url,有些開發者配置的是ip是localhost,那肯定是不行的啦。

           如果沒有外網環境,請看我的第一篇,環境準備,裏面有介紹可以使用百度bae

           http://tuposky.iteye.com/blog/2008583

  注意2:開發模式一定要開啓,不然配置了url和token也沒用,我犯過這個錯,嘿嘿。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章