手把手教您開發JAVA微信SDK-新手接入

很高興大家繼續我們的微信開發,相信大家已經迫不及待了吧!

下面直入正題!

首先如果你已經看過微信的公衆平臺開發文檔,如果沒看過建議還是先看一下

http://mp.weixin.qq.com/wiki/index.php?title=首頁

如果你已經註冊了訂閱號或者服務號,那麼你在高級功能,開發者模式 申請成爲開發者裏會讓你填寫


好了,我們就從這裏開始吧!

操作步驟我按順序標記了,其他的爲輔助說明。

1.首先我們新建一個Java開發包WeiXinSDK

2.包路徑:com.ansitech.weixin.sdk

測試的前提條件:

假如我的公衆賬號微信號爲:vzhanqun 

我的服務器地址爲:http://www.vzhanqun.com/

下面我們需要新建一個URL的請求地址

我們新建一個Servlet來驗證URL的真實性,具體接口參考

http://mp.weixin.qq.com/wiki/index.php?title=接入指南

3.新建com.ansitech.weixin.sdk.WeixinUrlFilter.java

這裏我們主要是獲取微信服務器法師的驗證信息,具體驗證代碼如下

package com.ansitech.weixin.sdk;

import com.ansitech.weixin.sdk.util.SHA1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WeixinUrlFilter implements Filter {

    //這個Token是給微信開發者接入時填的
    //可以是任意英文字母或數字,長度爲3-32字符
    private static String Token = "vzhanqun1234567890";

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("WeixinUrlFilter啓動成功!");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //微信服務器將發送GET請求到填寫的URL上,這裏需要判定是否爲GET請求
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        System.out.println("獲得微信請求:" + request.getMethod() + " 方式");
        if (isGet) {
            //驗證URL真實性
            String signature = request.getParameter("signature");// 微信加密簽名
            String timestamp = request.getParameter("timestamp");// 時間戳
            String nonce = request.getParameter("nonce");// 隨機數
            String echostr = request.getParameter("echostr");//隨機字符串
            List<String> params = new ArrayList<String>();
            params.add(Token);
            params.add(timestamp);
            params.add(nonce);
            //1. 將token、timestamp、nonce三個參數進行字典序排序
            Collections.sort(params, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });
            //2. 將三個參數字符串拼接成一個字符串進行sha1加密
            String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
            if (temp.equals(signature)) {
                response.getWriter().write(echostr);
            }
        } else {
            //處理接收消息
        }
    }

    @Override
    public void destroy() {
        
    }
}
好了,不過這裏有個SHA1算法,我這裏也把SHA1算法的源碼給貼出來吧!

4.新建com.ansitech.weixin.sdk.util.SHA1.java

/*
 * 微信公衆平臺(JAVA) SDK
 *
 * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
 * http://www.ansitech.com/weixin/sdk/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ansitech.weixin.sdk.util;

import java.security.MessageDigest;

/**
 * <p>Title: SHA1算法</p>
 *
 * @author qsyang<[email protected]>
 */
public final class SHA1 {

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
                           '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文轉換成十六進制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String encode(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
5.把這個Servlet配置到web.xml中
    <filter>
        <description>微信消息接入接口</description>
        <filter-name>WeixinUrlFilter</filter-name>
        <filter-class>com.ansitech.weixin.sdk.WeixinUrlFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>WeixinUrlFilter</filter-name>
        <url-pattern>/api/vzhanqun</url-pattern>
    </filter-mapping>
好了,接入的開發代碼已經完成。

6.下面就把地址URL和密鑰Token填入到微信申請成爲開發者模式中吧。

URL:http://www.vzhanqun.com/api/vzhanqun

Token:vzhanqun1234567890

假如你服務已經啓動了,那麼應該驗證成功,成爲開發者了。

如有疑問,請留言。

你可以微信關注我的訂閱號:vzhanqun 微站管家

更多相關內容請移步:http://www.weixin4j.org




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