當前位置:首頁 » 編程語言 » 微信java介面

微信java介面

發布時間: 2023-06-14 07:30:58

❶ 如何使用微信sdk java

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
這里我們主要是獲取微信伺服器法師的驗證信息,具體驗證代碼如下

[java] view plain 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是給微信開發者接入時填的
//可以是任意英文字母或數字,長度為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] view plain print?
/*
* 微信公眾平台(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 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中

[html] view plain print?
<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填入到微信申請成為開發者模式中吧。

❷ 怎麼用java調用微信支付介面

java調用微信支付介面方法:
RequestHandler requestHandler = new RequestHandler(super.getRequest(),super.getResponse());

//獲取token //兩小時內有效,兩小時後重新獲取

Token = requestHandler.GetToken();

//更新token 到應用中

requestHandler.getTokenReal();

System.out.println("微信支付獲取token=======================:" +Token);

//requestHandler 初始化

requestHandler.init();

requestHandler.init(appid,appsecret, appkey,partnerkey, key);

// --------------------------------本地系統生成訂單-------------------------------------

// 設置package訂單參數

SortedMap<String, String> packageParams = new TreeMap<String, String>();

packageParams.put("bank_type", "WX"); // 支付類型

packageParams.put("body", "xxxx"); // 商品描述

packageParams.put("fee_type", "1"); // 銀行幣種

packageParams.put("input_charset", "UTF-8"); // 字元集

packageParams.put("notify_url", "http://xxxx.com/xxxx/wxcallback"); // 通知地址 這里的通知地址使用外網地址測試,注意80埠是否打開。

packageParams.put("out_trade_no", no); // 商戶訂單號

packageParams.put("partner", partenerid); // 設置商戶號

packageParams.put("spbill_create_ip", super.getRequest().getRemoteHost()); // 訂單生成的機器IP,指用戶瀏覽器端IP

packageParams.put("total_fee", String.valueOf(rstotal)); // 商品總金額,以分為單位

// 設置支付參數

SortedMap<String, String> signParams = new TreeMap<String, String>();

signParams.put("appid", appid);

signParams.put("noncestr", noncestr);

signParams.put("traceid", PropertiesUtils.getOrderNO());

signParams.put("timestamp", timestamp);

signParams.put("package", packageValue);

signParams.put("appkey", this.appkey);

// 生成支付簽名,要採用URLENCODER的原始值進行SHA1演算法!

String sign ="";

try {

sign = Sha1Util.createSHA1Sign(signParams);

} catch (Exception e) {

e.printStackTrace();

}

// 增加非參與簽名的額外參數

signParams.put("sign_method", "sha1");

signParams.put("app_signature", sign);

// api支付拼包結束------------------------------------

//獲取prepayid

String prepayid = requestHandler.sendPrepay(signParams);

System.out.println("prepayid :" + prepayid);

// --------------------------------生成完成---------------------------------------------

//生成預付快訂單完成,返回給android,ios 掉起微信所需要的參數。

SortedMap<String, String> payParams = new TreeMap<String, String>();

payParams.put("appid", appid);

payParams.put("noncestr", noncestr);

payParams.put("package", "Sign=WXPay");

payParams.put("partnerid", partenerid);

payParams.put("prepayid", prepayid);

payParams.put("appkey", this.appkey);

//這里除1000 是因為參數長度限制。

int time = (int) (System.currentTimeMillis() / 1000);

payParams.put("timestamp",String.valueOf(time));

System.out.println("timestamp:" + time);

//簽名

String paysign ="";

try {

paysign = Sha1Util.createSHA1Sign(payParams);

} catch (Exception e) {

e.printStackTrace();

}

payParams.put("sign", paysign);

//拼json 數據返回給客戶端

BasicDBObject backObject = new BasicDBObject();

backObject.put("appid", appid);

backObject.put("noncestr", payParams.get("noncestr"));

backObject.put("package", "Sign=WXPay");

backObject.put("partnerid", payParams.get("partnerid"));

backObject.put("prepayid", payParams.get("prepayid"));

backObject.put("appkey", this.appkey);

backObject.put("timestamp",payParams.get("timestamp"));

backObject.put("sign",payParams.get("sign"));

String backstr = dataObject.toString();

System.out.println("backstr:" + backstr);

return backstr;

====================到此為止,預付款訂單已生成,並且已返回客戶端====================

//坐等微信伺服器通知,通知的地址就是生成預付款訂單的notify_url

ResponseHandler resHandler = new ResponseHandler(request, response);

resHandler.setKey(partnerkey);

//創建請求對象

//RequestHandler queryReq = new RequestHandler(request, response);

//queryReq.init();

if (resHandler.isTenpaySign() == true) {

//商戶訂單號

String out_trade_no = resHandler.getParameter("out_trade_no");

System.out.println("out_trade_no:" + out_trade_no);

//財付通訂單號

String transaction_id = resHandler.getParameter("transaction_id");

System.out.println("transaction_id:" + transaction_id);

//金額,以分為單位

String total_fee = resHandler.getParameter("total_fee");

//如果有使用折扣券,discount有值,total_fee+discount=原請求的total_fee

String discount = resHandler.getParameter("discount");

//支付結果

String trade_state = resHandler.getParameter("trade_state");

//判斷簽名及結果

if ("0".equals(trade_state)) {

//------------------------------

//即時到賬處理業務開始

//------------------------------

System.out.println("----------------業務邏輯執行-----------------");

//——請根據您的業務邏輯來編寫程序(以上代碼僅作參考)——

System.out.println("----------------業務邏輯執行完畢-----------------");

System.out.println("success"); // 請不要修改或刪除

System.out.println("即時到賬支付成功");

//給財付通系統發送成功信息,財付通系統收到此結果後不再進行後續通知

resHandler.sendToCFT("success");

//給微信伺服器返回success 否則30分鍾通知8次

return "success";

}else{

System.out.println("通知簽名驗證失敗");

resHandler.sendToCFT("fail");

response.setCharacterEncoding("utf-8");

}

}else {

System.out.println("fail -Md5 failed");

❸ 怎麼用java調用微信支付介面

java調用微信支付介面方法:x0d=newRequestHandler(super.getRequest(),super.getResponse());x0dx0ax0dx0a//獲取備昌token//兩小時內有效,兩小時後重新獲取x0dx0ax0dx0aToken=requestHandler.GetToken();x0dx0ax0dx0a//更新token到應用中x0dx0ax0dx0arequestHandler.getTokenReal();x0dx0ax0dx0aSystem.out.println("微信支付獲取token=======================:"+Token);x0dx0ax0dx0ax0dx0ax0dx0a//requestHandler初始化x0dx0ax0dx0arequestHandler.init();x0dx0ax0dx0arequestHandler.init(appid,appsecret,appkey,partnerkey,key);x0dx0ax0dx0ax0dx0ax0dx0a//--------------------------------本地系統生成訂單-------------------------------------x0dx0ax0dx0a//設置package訂單參數x0dx0ax0dx0aSortedMappackageParams=newTreeMap();x0dx0ax0dx0apackageParams.put("bank_type","WX");//支付類型x0dx0ax0dx0apackageParams.put("body","xxxx");//商品描述x0dx0ax0dx0apackageParams.put("fee_type","1");//銀行幣種x0dx0ax0dx0apackageParams.put("input_charset","UTF-8");//字元集x0dx0ax0dx0apackageParams.put("notify_url","http://xxxx.com/xxxx/wxcallback");//通知則友地址這里的通知地址使用外網地址測試,注意80埠是否仿盯扒打開。x0dx0ax0dx0apackageParams.put("out_trade_no",no);//商戶訂單號x0dx0ax0dx0apackageParams.put("partner",partenerid);//設置商戶號x0dx0ax0dx0apackageParams.put("spbill_create_ip",super.getRequest().getRemoteHost());//訂單生成的機器IP,指用戶瀏覽器端IPx0dx0ax0dx0apackageParams.put("total_fee",String.valueOf(rstotal));//商品總金額,以分為單位x0dx0ax0dx0ax0dx0ax0dx0a//設置支付參數x0dx0ax0dx0aSortedMapsignParams=newTreeMap();x0dx0ax0dx0asignParams.put("appid",appid);x0dx0ax0dx0asignParams.put("noncestr",noncestr);x0dx0ax0dx0asignParams.put("traceid",PropertiesUtils.getOrderNO());x0dx0ax0dx0asignParams.put("timestamp",timestamp);x0dx0ax0dx0asignParams.put("package",packageValue);x0dx0ax0dx0asignParams.put("appkey",this.appkey);x0dx0ax0dx0ax0dx0ax0dx0a//生成支付簽名,要採用URLENCODER的原始值進行SHA1演算法!x0dx0ax0dx0aStringsign="";x0dx0ax0dx0atry{x0dx0ax0dx0asign=Sha1Util.createSHA1Sign(signParams);x0dx0ax0dx0a}catch(Exceptione){x0dx0ax0dx0ae.printStackTrace();x0dx0ax0dx0a}x0dx0ax0dx0ax0dx0ax0dx0a//增加非參與簽名的額外參數x0dx0ax0dx0asignParams.put("sign_method","sha1");x0dx0ax0dx0asignParams.put("app_signature",sign);//api支付拼包結束------------------------------------x0dx0ax0dx0ax0dx0ax0dx0a//獲取=requestHandler.sendPrepay(signParams);x0dx0ax0dx0aSystem.out.println("prepayid:"+prepayid);x0dx0ax0dx0a//--------------------------------生成完成---------------------------------------------x0dx0ax0dx0ax0dx0ax0dx0a//生成預付快訂單完成,返回給android,ios掉起微信所需要的參數。x0dx0ax0dx0aSortedMappayParams=newTreeMap();x0dx0ax0dx0apayParams.put("appid",appid);x0dx0ax0dx0apayParams.put("noncestr",noncestr);x0dx0ax0dx0apayParams.put("package","Sign=WXPay");x0dx0ax0dx0apayParams.put("partnerid",partenerid);x0dx0ax0dx0apayParams.put("prepayid",prepayid);x0dx0ax0dx0apayParams.put("appkey",this.appkey);x0dx0ax0dx0a//這里除1000是因為參數長度限制。x0dx0ax0dx0ainttime=(int)(System.currentTimeMillis()/1000);x0dx0ax0dx0apayParams.put("timestamp",String.valueOf(time));.out.println("timestamp:"+time);x0dx0ax0dx0ax0dx0ax0dx0a//簽名x0dx0ax0dx0aStringpaysign="";x0dx0ax0dx0atry{x0dx0ax0dx0apaysign=Sha1Util.createSHA1Sign(payParams);x0dx0ax0dx0a}catch(Exceptione){x0dx0ax0dx0ae.printStackTrace();x0dx0ax0dx0a}x0dx0ax0dx0apayParams.put("sign",paysign);x0dx0ax0dx0ax0dx0ax0dx0a//拼json數據返回給客戶端=newBasicDBObject();x0dx0ax0dx0abackObject.put("appid",appid);x0dx0ax0dx0abackObject.put("noncestr",payParams.get("noncestr"));x0dx0ax0dx0abackObject.put("package","Sign=WXPay");x0dx0ax0dx0abackObject.put("partnerid",payParams.get("partnerid"));x0dx0ax0dx0abackObject.put("prepayid",payParams.get("prepayid"));x0dx0ax0dx0abackObject.put("appkey",this.appkey);x0dx0ax0dx0abackObject.put("timestamp",payParams.get("timestamp"));x0dx0ax0dx0abackObject.put("sign",payParams.get("sign"));=dataObject.toString();x0dx0ax0dx0aSystem.out.println("backstr:"+backstr);;x0dx0ax0dx0ax0dx0ax0dx0a====================到此為止,預付款訂單已生成,並且已返回客戶端====================x0dx0ax0dx0ax0dx0ax0dx0a//坐等微信伺服器通知,通知的地址就是生成預付款訂單的notify_=newResponseHandler(request,response);x0dx0ax0dx0aresHandler.setKey(partnerkey);x0dx0ax0dx0a//創建請求對象x0dx0ax0dx0a//RequestHandlerqueryReq=newRequestHandler(request,response);x0dx0ax0dx0a//queryReq.init();x0dx0ax0dx0aif(resHandler.isTenpaySign()==true){x0dx0ax0dx0a//商戶訂單號x0dx0ax0dx0aStringout_trade_no=resHandler.getParameter("out_trade_no");x0dx0ax0dx0aSystem.out.println("out_trade_no:"+out_trade_no);x0dx0ax0dx0a//財付通訂單號x0dx0ax0dx0aStringtransaction_id=resHandler.getParameter("transaction_id");x0dx0ax0dx0aSystem.out.println("transaction_id:"+transaction_id);x0dx0ax0dx0a//金額,以分為單位x0dx0ax0dx0aStringtotal_fee=resHandler.getParameter("total_fee");x0dx0ax0dx0a//如果有使用折扣券,discount有值,total_fee+discount=原請求的total_feex0dx0ax0dx0aStringdiscount=resHandler.getParameter("discount");x0dx0ax0dx0a//支付結果x0dx0ax0dx0aStringtrade_state=resHandler.getParameter("trade_state");x0dx0ax0dx0ax0dx0ax0dx0a//判斷簽名及結果x0dx0ax0dx0aif("0".equals(trade_state)){x0dx0ax0dx0a//------------------------------x0dx0ax0dx0a//即時到賬處理業務開始x0dx0ax0dx0a//------------------------------.out.println("----------------業務邏輯執行-----------------");x0dx0ax0dx0ax0dx0ax0dx0a//——請根據您的業務邏輯來編寫程序(以上代碼僅作參考)——x0dx0ax0dx0aSystem.out.println("----------------業務邏輯執行完畢-----------------");x0dx0ax0dx0aSystem.out.println("success");//請不要修改或刪除.out.println("即時到賬支付成功");x0dx0ax0dx0a//給財付通系統發送成功信息,財付通系統收到此結果後不再進行後續通知x0dx0ax0dx0aresHandler.sendToCFT("success");x0dx0ax0dx0ax0dx0ax0dx0a//給微信伺服器返回success否則30分鍾通知8次x0dx0ax0dx0areturn"success";x0dx0ax0dx0a}else{x0dx0ax0dx0aSystem.out.println("通知簽名驗證失敗");x0dx0ax0dx0aresHandler.sendToCFT("fail");x0dx0ax0dx0aresponse.setCharacterEncoding("utf-8");x0dx0ax0dx0a}x0dx0ax0dx0a}else{x0dx0ax0dx0aSystem.out.println("fail-Md5failed");

❹ 如何用java開發微信

說明:
本次的教程主要是對微信公眾平台開發者模式的講解,網路上很多類似文章,但很多都讓初學微信開發的人一頭霧水,所以總結自己的微信開發經驗,將微信開發的整個過程系統的列出,並對主要代碼進行講解分析,讓初學者盡快上手。

在閱讀本文之前,應對微信公眾平台的官方開發文檔有所了解,知道接收和發送的都是xml格式的數據。另外,在做內容回復時用到了圖靈機器人的api介面,這是一個自然語言解析的開放平台,可以幫我們解決整個微信開發過程中最困難的問題,此處不多講,下面會有其詳細的調用方式。


1.1 在登錄微信官方平台之後,開啟開發者模式,此時需要我們填寫url和token,所謂url就是我們自己伺服器的介面,用WechatServlet.java來實現,相關解釋已經在注釋中說明,代碼如下:

[java]view plain

  • packagedemo.servlet;

  • importjava.io.BufferedReader;

  • importjava.io.IOException;

  • importjava.io.InputStream;

  • importjava.io.InputStreamReader;

  • importjava.io.OutputStream;

  • importjavax.servlet.ServletException;

  • importjavax.servlet.http.HttpServlet;

  • importjavax.servlet.http.HttpServletRequest;

  • importjavax.servlet.http.HttpServletResponse;

  • importdemo.process.WechatProcess;

  • /**

  • *微信服務端收發消息介面

  • *

  • *@authorpamchen-1

  • *

  • */

  • {

  • /**

  • *ThedoGetmethodoftheservlet.<br>

  • *

  • *.

  • *

  • *@paramrequest

  • *

  • *@paramresponse

  • *

  • *@throwsServletException

  • *ifanerroroccurred

  • *@throwsIOException

  • *ifanerroroccurred

  • */

  • publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)

  • throwsServletException,IOException{

  • request.setCharacterEncoding("UTF-8");

  • response.setCharacterEncoding("UTF-8");

  • /**讀取接收到的xml消息*/

  • StringBuffersb=newStringBuffer();

  • InputStreamis=request.getInputStream();

  • InputStreamReaderisr=newInputStreamReader(is,"UTF-8");

  • BufferedReaderbr=newBufferedReader(isr);

  • Strings="";

  • while((s=br.readLine())!=null){

  • sb.append(s);

  • }

  • Stringxml=sb.toString();//次即為接收到微信端發送過來的xml數據

  • Stringresult="";

  • /**判斷是否是微信接入激活驗證,只有首次接入驗證時才會收到echostr參數,此時需要把它直接返回*/

  • Stringechostr=request.getParameter("echostr");

  • if(echostr!=null&&echostr.length()>1){

  • result=echostr;

  • }else{

  • //正常的微信處理流程

  • result=newWechatProcess().processWechatMag(xml);

  • }

  • try{

  • OutputStreamos=response.getOutputStream();

  • os.write(result.getBytes("UTF-8"));

  • os.flush();

  • os.close();

  • }catch(Exceptione){

  • e.printStackTrace();

  • }

  • }

  • /**

  • *ThedoPostmethodoftheservlet.<br>

  • *

  • *

  • *post.

  • *

  • *@paramrequest

  • *

  • *@paramresponse

  • *

  • *@throwsServletException

  • *ifanerroroccurred

  • *@throwsIOException

  • *ifanerroroccurred

  • */

  • publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

  • throwsServletException,IOException{

  • doGet(request,response);

  • }

  • }

  • 1.2 相應的web.xml配置信息如下,在生成WechatServlet.java的同時,可自動生成web.xml中的配置。前面所提到的url處可以填寫例如:http;//伺服器地址/項目名/wechat.do

    [html]view plain

  • <?xmlversion="1.0"encoding="UTF-8"?>

  • <web-appversion="2.5"

  • 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_2_5.xsd">

  • <servlet>

  • <description></description>

  • <display-name></display-name>

  • <servlet-name>WechatServlet</servlet-name>

  • <servlet-class>demo.servlet.WechatServlet</servlet-class>

  • </servlet>

  • <servlet-mapping>

  • <servlet-name>WechatServlet</servlet-name>

  • <url-pattern>/wechat.do</url-pattern>

  • </servlet-mapping>

  • <welcome-file-list>

  • <welcome-file>index.jsp</welcome-file>

  • </welcome-file-list>

  • </web-app>

  • 1.3 通過以上代碼,我們已經實現了微信公眾平台開發的框架,即開通開發者模式並成功接入、接收消息和發送消息這三個步驟。


    下面就講解其核心部分——解析接收到的xml數據,並以文本類消息為例,通過圖靈機器人api介面實現智能回復。


    2.1 首先看一下整體流程處理代碼,包括:xml數據處理、調用圖靈api、封裝返回的xml數據。

    [java]view plain

  • packagedemo.process;

  • importjava.util.Date;

  • importdemo.entity.ReceiveXmlEntity;

  • /**

  • *微信xml消息處理流程邏輯類

  • *@authorpamchen-1

  • *

  • */

  • publicclassWechatProcess{

  • /**

  • *解析處理xml、獲取智能回復結果(通過圖靈機器人api介面)

  • *@paramxml接收到的微信數據

  • *@return最終的解析結果(xml格式數據)

  • */

  • publicStringprocessWechatMag(Stringxml){

  • /**解析xml數據*/

  • ReceiveXmlEntityxmlEntity=newReceiveXmlProcess().getMsgEntity(xml);

  • /**以文本消息為例,調用圖靈機器人api介面,獲取回復內容*/

  • Stringresult="";

  • if("text".endsWith(xmlEntity.getMsgType())){

  • result=newTulingApiProcess().getTulingResult(xmlEntity.getContent());

  • }

  • /**此時,如果用戶輸入的是「你好」,在經過上面的過程之後,result為「你也好」類似的內容

  • *因為最終回復給微信的也是xml格式的數據,所有需要將其封裝為文本類型返回消息

  • **/

  • result=newFormatXmlProcess().formatXmlAnswer(xmlEntity.getFromUserName(),xmlEntity.getToUserName(),result);

  • returnresult;

  • }

  • }

  • 2.2 解析接收到的xml數據,此處有兩個類,ReceiveXmlEntity.java和ReceiveXmlProcess.java,通過反射的機制動態調用實體類中的set方法,可以避免很多重復的判斷,提高代碼效率,代碼如下:

    [java]view plain

  • packagedemo.entity;

  • /**

  • *接收到的微信xml實體類

  • *@authorpamchen-1

  • *

  • */

  • publicclassReceiveXmlEntity{

  • privateStringToUserName="";

  • privateStringFromUserName="";

  • privateStringCreateTime="";

  • privateStringMsgType="";

  • privateStringMsgId="";

  • privateStringEvent="";

  • privateStringEventKey="";

  • privateStringTicket="";

  • privateStringLatitude="";

  • privateStringLongitude="";

  • privateStringPrecision="";

  • privateStringPicUrl="";

  • privateStringMediaId="";

  • privateStringTitle="";

  • privateStringDescription="";

  • privateStringUrl="";

  • privateStringLocation_X="";

  • privateStringLocation_Y="";

  • privateStringScale="";

  • privateStringLabel="";

  • privateStringContent="";

  • privateStringFormat="";

  • privateStringRecognition="";

  • publicStringgetRecognition(){

  • returnRecognition;

  • }

  • publicvoidsetRecognition(Stringrecognition){

  • Recognition=recognition;

  • }

  • publicStringgetFormat(){

  • returnFormat;

  • }

  • publicvoidsetFormat(Stringformat){

  • Format=format;

  • }

  • publicStringgetContent(){

  • returnContent;

  • }

  • publicvoidsetContent(Stringcontent){

  • Content=content;

  • }

  • publicStringgetLocation_X(){

  • returnLocation_X;

  • }

  • publicvoidsetLocation_X(StringlocationX){

  • Location_X=locationX;

  • }

  • publicStringgetLocation_Y(){

  • returnLocation_Y;

  • }

  • publicvoidsetLocation_Y(StringlocationY){

  • Location_Y=locationY;

  • }

  • publicStringgetScale(){

  • returnScale;

  • }

  • publicvoidsetScale(Stringscale){

  • Scale=scale;

  • }

  • publicStringgetLabel(){

  • returnLabel;

  • }

  • publicvoidsetLabel(Stringlabel){

  • Label=label;

  • }

  • publicStringgetTitle(){

  • returnTitle;

  • }

  • publicvoidsetTitle(Stringtitle){

  • Title=title;

  • }

  • publicStringgetDescription(){

  • returnDescription;

  • }

  • publicvoidsetDescription(Stringdescription){

  • Description=description;

  • }

  • publicStringgetUrl(){

  • returnUrl;

  • }

  • publicvoidsetUrl(Stringurl){

  • Url=url;

  • }

  • publicStringgetPicUrl(){

  • returnPicUrl;

  • }

  • publicvoidsetPicUrl(StringpicUrl){

  • PicUrl=picUrl;

  • }

  • publicStringgetMediaId(){

  • returnMediaId;

  • }

  • publicvoidsetMediaId(StringmediaId){

  • MediaId=mediaId;

  • }

  • publicStringgetEventKey(){

  • returnEventKey;

  • }

  • publicvoidsetEventKey(StringeventKey){

  • EventKey=eventKey;

  • }

  • publicStringgetTicket(){

  • returnTicket;

  • }

  • publicvoidsetTicket(Stringticket){

  • Ticket=ticket;

  • }

  • publicStringgetLatitude(){

  • returnLatitude;

  • }

  • publicvoidsetLatitude(Stringlatitude){

  • Latitude=latitude;

  • }

  • publicStringgetLongitude(){

  • returnLongitude;

  • }

  • publicvoidsetLongitude(Stringlongitude){

  • Longitude=longitude;

  • }

  • publicStringgetPrecision(){

  • returnPrecision;

  • }

  • publicvoidsetPrecision(Stringprecision){

  • Precision=precision;

  • }

  • publicStringgetEvent(){

  • returnEvent;

  • }

  • publicvoidsetEvent(Stringevent){

  • Event=event;

  • }

  • publicStringgetMsgId(){

  • returnMsgId;

  • }

  • publicvoidsetMsgId(StringmsgId){

  • MsgId=msgId;

  • }

  • publicStringgetToUserName(){

  • returnToUserName;

  • }

  • publicvoidsetToUserName(StringtoUserName){

熱點內容
安卓怎麼玩地牢獵人 發布:2025-02-12 23:50:25 瀏覽:943
思鄉腳本 發布:2025-02-12 23:43:32 瀏覽:439
java的job 發布:2025-02-12 23:38:43 瀏覽:892
我的世界伺服器授權指令 發布:2025-02-12 23:30:13 瀏覽:596
電腦伺服器號在哪裡找 發布:2025-02-12 23:22:29 瀏覽:12
linux查看系統是32位 發布:2025-02-12 23:17:29 瀏覽:989
從資料庫中隨機取資料庫數據 發布:2025-02-12 23:17:25 瀏覽:878
ftp下載軟體安卓 發布:2025-02-12 23:07:24 瀏覽:567
c搜索演算法 發布:2025-02-12 23:05:47 瀏覽:862
返回伺服器地址 發布:2025-02-12 23:05:45 瀏覽:181