結合百度雲平臺和微信公眾平臺進行開發(一)
套話大話我就不說了,網上一大堆,我們就直接進入正題吧,相信對百度雲平臺和微信公眾平臺沒有了解的也不會關注這篇文章。
上面的標題到底是個什麼意思呢?下面讓我們一步一步來完成一個測試小專案。
兩者是怎樣結合的?
利用百度雲平臺執行我們自己的服務端專案,在平臺上線執行。利用這個專案對應的域名將其配置到微信公眾平臺,並填寫token值。(這裡的token值是我們自定義的一個字串,它配置在服務端專案)在手機微信客戶端搜尋你的微信公眾平臺公眾號(訂閱號),當然通過二維碼會更快速準確,呵呵。
下面我們先重伺服器端開始。
進入百度雲平臺的管理控制檯(請大家進入舊版--右上角):http://developer.baidu.com/dev
出現以下頁面後,點選雲環境:
建立域名,選擇開發語言(我用的是Java),選著版本管理器(我用的是svn),點選確定:
等待後彈出提示建立成功後,點選確定,跳轉到如下頁面---------建立版本:
點選建立版本後,會出現兩種選擇,一種是線上建立專案,然後線上編輯釋出,本人還是覺得第二種順手,上傳war包,即將本地建好的web專案釋出為war包,然後上傳,在上線,我們就以上傳war包方式為例:這裡我們就暫且停下:開始來編輯我們需要的web專案。
在eclipse中心建一個web專案(tomcat伺服器)新建MainServer.java
需要匯入的jar包:
package com.weixin.zfeng.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.weixin.zfeng.utils.Weather;
public class MainServer extends HttpServlet{
//這裡是你定義的token值
private final String TOKEN = "haha";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//取出隨機字串
String echostr=req.getParameter("echostr");
if(null==echostr||echostr.isEmpty()){
responseMsg(req,resp);
}else{
if(this.checkSignature(req)){
resp.getWriter().print(echostr);
}else{
resp.getWriter().print("");
}
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
//回覆
public void responseMsg(HttpServletRequest req,HttpServletResponse resp) throws IOException{
String postStr=null;
try{
postStr=this.readStreamParameter(req.getInputStream());
}catch(Exception e){
e.printStackTrace();
}
//System.out.println(postStr);
if (null!=postStr&&!postStr.isEmpty()){
Document document=null;
try{
document = DocumentHelper.parseText(postStr);
if(null==document){
resp.getWriter().print("");
return;
}
}catch(Exception e){
e.printStackTrace();
}
Element root=document.getRootElement();
String fromUsername = root.elementText("FromUserName");
String toUsername = root.elementText("ToUserName");
String keyword = root.elementTextTrim("Content");
String time = new Date().getTime()+"";
String textTpl = "<xml>"+
"<ToUserName><![CDATA[%1$s]]></ToUserName>"+
"<FromUserName><![CDATA[%2$s]]></FromUserName>"+
"<CreateTime>%3$s</CreateTime>"+
"<MsgType><![CDATA[%4$s]]></MsgType>"+
"<Content><![CDATA[%5$s]]></Content>"+
"<FuncFlag>0</FuncFlag>"+
"</xml>";
//傳送訊息型別
String msgType = "text";
String contentStr = "";
String resultStr="";//返回訊息
//關注訂閱號後,返回的提示
if(null==keyword||keyword.equals("")){
contentStr = "hi,how are you! I'm server and with baiduyun";
}
//微信客戶端傳送time,伺服器解析到後返回當前時間
else if(keyword.equals("time")){
contentStr = new Date().toString();
}
resultStr = String.format(textTpl, fromUsername, toUsername, time, msgType, contentStr+"---zhaofeng");
resp.getWriter().print(resultStr);
}else {
resp.getWriter().print("");
}
resp.getWriter().flush();
resp.getWriter().close();
}
//檢查請求
public boolean checkSignature(HttpServletRequest request){
//這裡是微信進行安全驗證的四個值,由於token為明文,所以前用前三個值進行加密計算後的值與token對比(不具體描述)
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String token=TOKEN;
String[] tmpArr={token,timestamp,nonce};
Arrays.sort(tmpArr);
String tmpStr=this.ArrayToString(tmpArr);
tmpStr=this.SHA1Encode(tmpStr);
if(tmpStr.equalsIgnoreCase(signature)){
return true;
}else{
return false;
}
}
public String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
private String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
//
public String ArrayToString(String [] arr){
StringBuffer bf = new StringBuffer();
for(int i = 0; i < arr.length; i++){
bf.append(arr[i]);
}
return bf.toString();
}
//流中讀取資料
public String readStreamParameter(ServletInputStream in){
StringBuilder buffer = new StringBuilder();
BufferedReader reader=null;
try{
reader = new BufferedReader(new InputStreamReader(in));
String line=null;
while((line = reader.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(null!=reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer.toString();
}
}
這裡是一個最基本的骨架程式碼,大家可以在上面進行跟多豐富的擴充套件。接著我們將專案匯出為war包。接著就是剛剛說到的上傳war包了,這裡就不再講了。上傳成功後點擊上線(哦這裡有個下提示,當然這裡不存在,免費使用者每次只能上傳50M以內哦),等待提示“程式碼已生效”後,出現:
接著我們就應該配置微信公眾平臺了:(申請註冊微信公眾平臺要求比較嚴格,需要稽核幾天到N天不等)。https://mp.weixin.qq.com/
前不久我是借用別個的賬號進行測試的,我的公眾號都幾天了還沒有通過,哎~所以這裡沒法給大家截圖。其實微信裡邊配置很簡單,就是一個訪問專案的域名,和一個token值,填正確這兩個後就可以確定了,(選擇功能---高階功能---開發者模式---成為開發者----填寫---提交(成功)---開啟)
然後就是關注賬號進行測試了。我的上一個測試用的是return這個號,大家關注後傳送time試下效果(相同程式碼)
這裡的域名就是你建立web專案時寫的http://mytestserverforweixin.duapp.com/MainServer注意這裡並不是完全正確的域名,還需要在前面加上你的版本號:http://1.mytestserverforweixin.duapp.com/MainServer。
填寫後並提交成功,然後開啟。
謝謝大家!
mytestserverforweixin.duapp.com mytestserverforweixin.duapp.com