微信福士開放平台開發02-微信公眾平台PHP介面和java介面對比

來源:互聯網
上載者:User
公眾開放平台開發02---公眾平台PHP介面和java介面對比

公眾開放平台開發02---公眾平台PHP介面和java介面對比
技術qq交流群:JavaDream:251572072
-----------------------------------
這一節中的代碼收集於網友的製作
-------------------------------------------
a.java-jsp版
b.PHP的介面代碼:
/**
* wechat php test
*/

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];

//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}

public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

//extract post data
if (!empty($postStr)){

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "
%s
%s
%s
%s
%s
0
";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}

}else {
echo "";
exit;
}
}

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;
}
}
}

?>
--------------------------------------------------
c.java版介面
<[email protected] import="java.util.Date"%>
<[email protected] import="org.dom4j.Element"%>
<[email protected] import="org.dom4j.DocumentHelper"%>
<[email protected] import="org.dom4j.Document"%>
<[email protected] import="java.io.IOException"%>
<[email protected] import="java.io.InputStreamReader"%>
<[email protected] import="java.io.BufferedReader"%>
<[email protected] import="java.io.Reader"%>
<[email protected] import="java.security.MessageDigest"%>
<[email protected] import="java.util.Arrays"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
//WeiXinHandler為內部類不能使用非final類型的對象
final String TOKEN="weixin";
final HttpServletRequest final_request=request;
final HttpServletResponse final_response=response;
%>
<%
class WeiXinHandler{
public void valid(){
String echostr=final_request.getParameter("echostr");
if(null==echostr||echostr.isEmpty()){
responseMsg();
}else{
if(this.checkSignature()){
this.print(echostr);
}else{
this.print("error");
}
}
}
//自動回複內容
public void responseMsg(){
String postStr=null;
try{
postStr=this.readStreamParameter(final_request.getInputStream());
}catch(Exception e){
e.printStackTrace();
}
//System.out.println(postStr);
if (null!=postStr&&!postStr.isEmpty()){
Document document=null;
try{
document = DocumentHelper.parseText(postStr);
}catch(Exception e){
e.printStackTrace();
}
if(null==document){
this.print("");
return;
}
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 = ""+
"%1$s"+
"%2$s"+
"%3$s"+
"%4$s"+
"%5$s"+
"0"+
"";

if(null!=keyword&&!keyword.equals(""))
{
String msgType = "text";
String contentStr = "Welcome to wechat world!";
String resultStr = textTpl.format(textTpl, fromUsername, toUsername, time, msgType, contentStr);
this.print(resultStr);
}else{
this.print("Input something...");
}

}else {
this.print("");
}
}
//介面驗證
public boolean checkSignature(){
String signature = final_request.getParameter("signature");
String timestamp = final_request.getParameter("timestamp");
String nonce = final_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 void print(String content){
try{
final_response.getWriter().print(content);
final_response.getWriter().flush();
final_response.getWriter().close();
}catch(Exception e){

}
}
//數組轉字串
public String ArrayToString(String [] arr){
StringBuffer bf = new StringBuffer();
for(int i = 0; i < arr.length; i++){
bf.append(arr[i]);
}
return bf.toString();
}
//sha1加密
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;
}
public final 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();
}
//從輸入資料流讀取post參數
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();
}
}
%>
<%
WeiXinHandler handler=new WeiXinHandler();
handler.valid();
%>
-----------------------------------------
d.以上就是PHP介面和JSP介面的所有代碼,
現在我們來對一些需要注意的地方做下分析:
首先的從總體看的話,jsp要比PHP繁瑣一些,因為很多函數需要自己寫,
像sha1加密,解析xml字串等都需要自己找第三方的庫。
第一點,我們要擷取公眾平台給jsp發送的post或get參數,正常情況下都是用request.getParameter就可以擷取到,
但是在寫的過程中發現PHP是這樣擷取
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
這時通過查詢一些資料知道這樣擷取的是無法通過$_GET或$_POST函數得到的”未識別 MIME 類型的資料“,原始的 POST 資料
所以這裡使用擷取未經處理資料流的方式來解析post的xml資料
String postStr=null;
try{
postStr=this.readStreamParameter(final_request.getInputStream());
}catch(Exception e){
e.printStackTrace();
}
-----------------------------------------------------
//從輸入資料流讀取post參數
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();
}
--------------------------------------------------------------
第二個,是response訊息返回給平台,我嘗試的用最一般的out.print去做,但是發現沒反應,觀察PHP的代碼寫法
echo "";
exit;
------------------
猜想可能需要有個重新整理的操作才能把訊息response回去,於是找了下response內的一些函數做出以下嘗試
//向請求端發送返回資料
public void print(String content){
try{
final_response.getWriter().print(content);
final_response.getWriter().flush();
final_response.getWriter().close();
}catch(Exception e){

}
}
---------------------------------------
關於公眾平台的訊息介面的詳細介紹,可以參看公眾平台的官方文檔,裡面介紹了訊息的xml的格式和訊息的發送方式等。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.