說明:
為昂昂溪等地區(qū)用戶提供了全套網(wǎng)頁設計制作服務,及昂昂溪網(wǎng)站建設行業(yè)解決方案。主營業(yè)務為網(wǎng)站設計制作、成都做網(wǎng)站、昂昂溪網(wǎng)站設計,以傳統(tǒng)方式定制建設網(wǎng)站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
本次的教程主要是對微信公眾平臺開發(fā)者模式的講解,網(wǎng)絡上很多類似文章,但很多都讓初學微信開發(fā)的人一頭霧水,所以總結自己的微信開發(fā)經(jīng)驗,將微信開發(fā)的整個過程系統(tǒng)的列出,并對主要代碼進行講解分析,讓初學者盡快上手。
在閱讀本文之前,應對微信公眾平臺的官方開發(fā)文檔有所了解,知道接收和發(fā)送的都是xml格式的數(shù)據(jù)。另外,在做內容回復時用到了圖靈機器人的api接口,這是一個自然語言解析的開放平臺,可以幫我們解決整個微信開發(fā)過程中最困難的問題,此處不多講,下面會有其詳細的調用方式。
1.1 在登錄微信官方平臺之后,開啟開發(fā)者模式,此時需要我們填寫url和token,所謂url就是我們自己服務器的接口,用WechatServlet.java來實現(xiàn),相關解釋已經(jīng)在注釋中說明,代碼如下:
[java]?view plain?copy
package?demo.servlet;
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStream;
import?java.io.InputStreamReader;
import?java.io.OutputStream;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
import?demo.process.WechatProcess;
/**
*?微信服務端收發(fā)消息接口
*
*?@author?pamchen-1
*
*/
public?class?WechatServlet?extends?HttpServlet?{
/**
*?The?doGet?method?of?the?servlet.?br
*
*?This?method?is?called?when?a?form?has?its?tag?value?method?equals?to?get.
*
*?@param?request
*????????????the?request?send?by?the?client?to?the?server
*?@param?response
*????????????the?response?send?by?the?server?to?the?client
*?@throws?ServletException
*?????????????if?an?error?occurred
*?@throws?IOException
*?????????????if?an?error?occurred
*/
public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
/**?讀取接收到的xml消息?*/
StringBuffer?sb?=?new?StringBuffer();
InputStream?is?=?request.getInputStream();
InputStreamReader?isr?=?new?InputStreamReader(is,?"UTF-8");
BufferedReader?br?=?new?BufferedReader(isr);
String?s?=?"";
while?((s?=?br.readLine())?!=?null)?{
sb.append(s);
}
String?xml?=?sb.toString();?//次即為接收到微信端發(fā)送過來的xml數(shù)據(jù)
String?result?=?"";
/**?判斷是否是微信接入激活驗證,只有首次接入驗證時才會收到echostr參數(shù),此時需要把它直接返回?*/
String?echostr?=?request.getParameter("echostr");
if?(echostr?!=?null??echostr.length()??1)?{
result?=?echostr;
}?else?{
//正常的微信處理流程
result?=?new?WechatProcess().processWechatMag(xml);
}
try?{
OutputStream?os?=?response.getOutputStream();
os.write(result.getBytes("UTF-8"));
os.flush();
os.close();
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
/**
*?The?doPost?method?of?the?servlet.?br
*
*?This?method?is?called?when?a?form?has?its?tag?value?method?equals?to
*?post.
*
*?@param?request
*????????????the?request?send?by?the?client?to?the?server
*?@param?response
*????????????the?response?send?by?the?server?to?the?client
*?@throws?ServletException
*?????????????if?an?error?occurred
*?@throws?IOException
*?????????????if?an?error?occurred
*/
public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
doGet(request,?response);
}
}
1.2 相應的web.xml配置信息如下,在生成WechatServlet.java的同時,可自動生成web.xml中的配置。前面所提到的url處可以填寫例如:http;//服務器地址/項目名/wechat.do
[html]?view plain?copy
?xml?version="1.0"?encoding="UTF-8"?
web-app?version="2.5"
xmlns=""
xmlns:xsi=""
xsi:schemaLocation="
"
servlet
descriptionThis?is?the?description?of?my?J2EE?component/description
display-nameThis?is?the?display?name?of?my?J2EE?component/display-name
servlet-nameWechatServlet/servlet-name
servlet-classdemo.servlet.WechatServlet/servlet-class
/servlet
servlet-mapping
servlet-nameWechatServlet/servlet-name
url-pattern/wechat.do/url-pattern
/servlet-mapping
welcome-file-list
welcome-fileindex.jsp/welcome-file
/welcome-file-list
/web-app
1.3 通過以上代碼,我們已經(jīng)實現(xiàn)了微信公眾平臺開發(fā)的框架,即開通開發(fā)者模式并成功接入、接收消息和發(fā)送消息這三個步驟。
下面就講解其核心部分——解析接收到的xml數(shù)據(jù),并以文本類消息為例,通過圖靈機器人api接口實現(xiàn)智能回復。
2.1 首先看一下整體流程處理代碼,包括:xml數(shù)據(jù)處理、調用圖靈api、封裝返回的xml數(shù)據(jù)。
[java]?view plain?copy
package?demo.process;
import?java.util.Date;
import?demo.entity.ReceiveXmlEntity;
/**
*?微信xml消息處理流程邏輯類
*?@author?pamchen-1
*
*/
public?class?WechatProcess?{
/**
*?解析處理xml、獲取智能回復結果(通過圖靈機器人api接口)
*?@param?xml?接收到的微信數(shù)據(jù)
*?@return??最終的解析結果(xml格式數(shù)據(jù))
*/
public?String?processWechatMag(String?xml){
/**?解析xml數(shù)據(jù)?*/
ReceiveXmlEntity?xmlEntity?=?new?ReceiveXmlProcess().getMsgEntity(xml);
/**?以文本消息為例,調用圖靈機器人api接口,獲取回復內容?*/
String?result?=?"";
if("text".endsWith(xmlEntity.getMsgType())){
result?=?new?TulingApiProcess().getTulingResult(xmlEntity.getContent());
}
/**?此時,如果用戶輸入的是“你好”,在經(jīng)過上面的過程之后,result為“你也好”類似的內容
*??因為最終回復給微信的也是xml格式的數(shù)據(jù),所有需要將其封裝為文本類型返回消息
*?*/
result?=?new?FormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(),?xmlEntity.getToUserName(),?result);
return?result;
}
}
2.2 解析接收到的xml數(shù)據(jù),此處有兩個類,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通過反射的機制動態(tài)調用實體類中的set方法,可以避免很多重復的判斷,提高代碼效率,代碼如下:
[java]?view plain?copy
package?demo.entity;
/**
*?接收到的微信xml實體類
*?@author?pamchen-1
*
*/
public?class?ReceiveXmlEntity?{
private?String?ToUserName="";
private?String?FromUserName="";
private?String?CreateTime="";
private?String?MsgType="";
private?String?MsgId="";
private?String?Event="";
private?String?EventKey="";
private?String?Ticket="";
private?String?Latitude="";
private?String?Longitude="";
private?String?Precision="";
private?String?PicUrl="";
private?String?MediaId="";
private?String?Title="";
private?String?Description="";
private?String?Url="";
private?String?Location_X="";
private?String?Location_Y="";
private?String?Scale="";
private?String?Label="";
private?String?Content="";
private?String?Format="";
private?String?Recognition="";
public?String?getRecognition()?{
return?Recognition;
}
public?void?setRecognition(String?recognition)?{
Recognition?=?recognition;
}
public?String?getFormat()?{
return?Format;
}
public?void?setFormat(String?format)?{
Format?=?format;
}
public?String?getContent()?{
return?Content;
}
public?void?setContent(String?content)?{
Content?=?content;
}
public?String?getLocation_X()?{
return?Location_X;
}
public?void?setLocation_X(String?locationX)?{
Location_X?=?locationX;
}
public?String?getLocation_Y()?{
return?Location_Y;
}
public?void?setLocation_Y(String?locationY)?{
Location_Y?=?locationY;
}
public?String?getScale()?{
return?Scale;
}
public?void?setScale(String?scale)?{
Scale?=?scale;
}
public?String?getLabel()?{
return?Label;
}
public?void?setLabel(String?label)?{
Label?=?label;
}
public?String?getTitle()?{
return?Title;
}
public?void?setTitle(String?title)?{
Title?=?title;
}
public?String?getDescription()?{
return?Description;
}
public?void?setDescription(String?description)?{
Description?=?description;
}
public?String?getUrl()?{
return?Url;
}
public?void?setUrl(String?url)?{
Url?=?url;
}
public?String?getPicUrl()?{
return?PicUrl;
}
public?void?setPicUrl(String?picUrl)?{
PicUrl?=?picUrl;
}
public?String?getMediaId()?{
return?MediaId;
}
public?void?setMediaId(String?mediaId)?{
MediaId?=?mediaId;
}
public?String?getEventKey()?{
return?EventKey;
}
public?void?setEventKey(String?eventKey)?{
EventKey?=?eventKey;
}
public?String?getTicket()?{
return?Ticket;
}
public?void?setTicket(String?ticket)?{
Ticket?=?ticket;
}
public?String?getLatitude()?{
return?Latitude;
}
public?void?setLatitude(String?latitude)?{
Latitude?=?latitude;
}
public?String?getLongitude()?{
return?Longitude;
}
public?void?setLongitude(String?longitude)?{
Longitude?=?longitude;
}
public?String?getPrecision()?{
return?Precision;
}
public?void?setPrecision(String?precision)?{
Precision?=?precision;
}
public?String?getEvent()?{
return?Event;
}
public?void?setEvent(String?event)?{
Event?=?event;
}
public?String?getMsgId()?{
return?MsgId;
}
public?void?setMsgId(String?msgId)?{
MsgId?=?msgId;
}
public?String?getToUserName()?{
return?ToUserName;
}
public?void?setToUserName(String?toUserName)?{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 將請求、響應的編碼均設置為UTF-8(防止中文亂碼)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 接收參數(shù)微信加密簽名、 時間戳、隨機數(shù)
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
PrintWriter out = response.getWriter();
// 請求校驗
boolean checkSignature = SignUtil.checkSignature(signature, timestamp, nonce);
if (checkSignature) {
// 調用核心服務類接收處理請求
String respXml = processRequest(request);
out.print(respXml);
}
out.close();
out = null;
}
1.首先我們新建一個Java開發(fā)包WeiXinSDK
2.包路徑:com.ansitech.weixin.sdk
測試的前提條件:
假如我的公眾賬號微信號為:vzhanqun
我的服務器地址為:
下面我們需要新建一個URL的請求地址
我們新建一個Servlet來驗證URL的真實性,具體接口參考
接入指南
3.新建com.ansitech.weixin.sdk.WeixinUrlFilter.java
這里我們主要是獲取微信服務器法師的驗證信息,具體驗證代碼如下
[java] view plain copy print?
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是給微信開發(fā)者接入時填的
//可以是任意英文字母或數(shù)字,長度為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;
//微信服務器將發(fā)送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");// 隨機數(shù)
String echostr = request.getParameter("echostr");//隨機字符串
ListString params = new ArrayListString();
params.add(Token);
params.add(timestamp);
params.add(nonce);
//1. 將token、timestamp、nonce三個參數(shù)進行字典序排序
Collections.sort(params, new ComparatorString() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
//2. 將三個參數(shù)字符串拼接成一個字符串進行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] view plain copy print?
/*
* 微信公眾平臺(JAVA) SDK
*
* Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
*
*
* 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
*
*
*
* 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;
/**
* pTitle: SHA1算法/p
*
* @author qsyangyangqisheng274@163.com
*/
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中
[html] view plain copy print?
filter
description微信消息接入接口/description
filter-nameWeixinUrlFilter/filter-name
filter-classcom.ansitech.weixin.sdk.WeixinUrlFilter/filter-class
/filter
filter-mapping
filter-nameWeixinUrlFilter/filter-name
url-pattern/api/vzhanqun/url-pattern
/filter-mapping
好了,接入的開發(fā)代碼已經(jīng)完成。
6.下面就把地址URL和密鑰Token填入到微信申請成為開發(fā)者模式中吧。
/**
*?文件上傳到微信服務器
*?@param?fileType?文件類型
*?@param?filePath?文件路徑
*?@return?JSONObject
*?@throws?Exception
*/
public?static?JSONObject?send(String?fileType,?String?filePath)?throws?Exception?{??
String?result?=?null;??
File?file?=?new?File(filePath);??
if?(!file.exists()?||?!file.isFile())?{??
throw?new?IOException("文件不存在");??
}??
/**?
*?第一部分?
*/??
URL?urlObj?=?new?URL(""+?getAccess_token()?+?"type="+fileType+"");??
HttpURLConnection?con?=?(HttpURLConnection)?urlObj.openConnection();??
con.setRequestMethod("POST");?//?以Post方式提交表單,默認get方式??
con.setDoInput(true);??
con.setDoOutput(true);??
con.setUseCaches(false);?//?post方式不能使用緩存??
//?設置請求頭信息??
con.setRequestProperty("Connection",?"Keep-Alive");??
con.setRequestProperty("Charset",?"UTF-8");??
//?設置邊界??
String?BOUNDARY?=?"----------"?+?System.currentTimeMillis();??
con.setRequestProperty("Content-Type",?"multipart/form-data;?boundary="+?BOUNDARY);??
//?請求正文信息??
//?第一部分:??
StringBuilder?sb?=?new?StringBuilder();??
sb.append("--");?//?必須多兩道線??
sb.append(BOUNDARY);??
sb.append("\r\n");??
sb.append("Content-Disposition:?form-data;name=\"file\";filename=\""+?file.getName()?+?"\"\r\n");??
sb.append("Content-Type:application/octet-stream\r\n\r\n");??
byte[]?head?=?sb.toString().getBytes("utf-8");??
//?獲得輸出流??
OutputStream?out?=?new?DataOutputStream(con.getOutputStream());??
//?輸出表頭??
out.write(head);??
//?文件正文部分??
//?把文件已流文件的方式?推入到url中??
DataInputStream?in?=?new?DataInputStream(new?FileInputStream(file));??
int?bytes?=?0;??
byte[]?bufferOut?=?new?byte[1024];??
while?((bytes?=?in.read(bufferOut))?!=?-1)?{??
out.write(bufferOut,?0,?bytes);??
}??
in.close();??
//?結尾部分??
byte[]?foot?=?("\r\n--"?+?BOUNDARY?+?"--\r\n").getBytes("utf-8");//?定義最后數(shù)據(jù)分隔線??
out.write(foot);??
out.flush();??
out.close();??
StringBuffer?buffer?=?new?StringBuffer();??
BufferedReader?reader?=?null;??
try?{??
//?定義BufferedReader輸入流來讀取URL的響應??
reader?=?new?BufferedReader(new?InputStreamReader(con.getInputStream()));??
String?line?=?null;??
while?((line?=?reader.readLine())?!=?null)?{??
//System.out.println(line);??
buffer.append(line);??
}??
if(result==null){??
result?=?buffer.toString();??
}??
}?catch?(IOException?e)?{??
System.out.println("發(fā)送POST請求出現(xiàn)異常!"?+?e);??
e.printStackTrace();??
throw?new?IOException("數(shù)據(jù)讀取異常");??
}?finally?{??
if(reader!=null){??
reader.close();??
}??
}??
JSONObject?jsonObj?=new?JSONObject(result);??
return?jsonObj;??
}
其實還蠻簡單的,可以說一搜一大把,下面說下兩種方式。
自行開發(fā)
主要就是通過小程序端直接請求登錄獲取到code(登錄憑證)、如果需要獲取用戶手機號則需要再次授權需要iv和encryptedData,注意這里授權兩次,也可以作為一次處理。
(1) 后端接收到小程序端請求的code,進行解密,可以參考微信小程序開發(fā)文檔,拿到openId和session_key,這一步如果是已經(jīng)注冊的用戶可以直接將后臺分配的token一起組成對象存儲到redis中,期限7-30天皆可,先從redis判定這個openId是否已經(jīng)解析過且已存儲為正式用戶,是則直接返回系統(tǒng)的登錄憑證完成登錄。如果不是就需要走第二步。
(2)通過iv和encryptedData解析獲取用戶的手機號,完成解析后將用戶信息存儲,并一樣存儲到數(shù)據(jù)庫和redis中,返回憑證。
2. 使用已經(jīng)集成好的sdk,使用maven項目直接引入對象的jar即可。
舉個栗子?weixin-java-miniapp 可以看下對應的文檔說明,使用已經(jīng)集成好的方法即可。
您好,這樣的:
1)圖文消息的個數(shù)限制為10,也就是圖中ArticleCount的值(圖文消息的個數(shù),限制在10條以內);
2)對于多圖文消息,第一條圖文的圖片顯示為大圖,其他圖文的圖片顯示為小圖;
3)第一條圖文的圖片大小建議為640*320,其他圖文的圖片大小建議為80*80;
下面是實例代碼:
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
// 接收用戶發(fā)送的文本消息內容
String content = requestMap.get("Content");
// 創(chuàng)建圖文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
ListArticle articleList = new ArrayListArticle();
// 單圖文消息
if ("1".equals(content)) {
Article article = new Article();
article.setTitle("微信公眾帳號開發(fā)教程Java版");
article.setDescription("柳峰,80后,微信公眾帳號開發(fā)經(jīng)驗4個月。為幫助初學者入門,特推出此系列教程,也希望借此機會認識更多同行!");
article.setPicUrl("");
article.setUrl("");
articleList.add(article);
// 設置圖文消息個數(shù)
newsMessage.setArticleCount(articleList.size());
// 設置圖文消息包含的圖文集合
newsMessage.setArticles(articleList);
// 將圖文消息對象轉換成xml字符串
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}
文章標題:java微信開發(fā)代碼 微信開發(fā)代碼全部
當前URL:http://chinadenli.net/article12/dodcpgc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、企業(yè)建站、網(wǎng)站設計公司、外貿網(wǎng)站建設、虛擬主機、小程序開發(fā)
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)