The story that Java and Wechat have to say-implementing the connection between the WeChat public platform and the sae Server

Source: Internet
Author: User

A story that must be told between Java and the public platform-implementing the connection between the public platform and the sae server-a story that must be told by sae

I have been decadent for a few days and said that I have been paying attention to it for more than half a year. Now, the easyUI platform of the company has gradually started to understand it. However, there have been too many bugs recently and I have to find time to study, I am bored and have seen java platform development. I feel a little interesting. I will try it myself, but I have to ask the experts in the blog field to study it now.

When I was bored at the beginning, I registered an account on the Sina cloud server to create some applications on the platform. As a result, I established an interface between the public platform and Sina cloud server based on the official example. However, it is officially written in the PHP language (maybe PHP is the best language in the world ). But as a Javaer, you must learn how to write Java. Paste this example first.

  

<?php/**  * wechat php test  *///define your tokendefine("TOKEN", "haojiahongxihuanliyuan");$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)){                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,                   the best way is to check the validity of xml by yourself */                libxml_disable_entity_loader(true);                  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);                $fromUsername = $postObj->FromUserName;                $toUsername = $postObj->ToUserName;                $keyword = trim($postObj->Content);                $time = time();                $textTpl = "<xml>                            <ToUserName><![CDATA[%s]]></ToUserName>                            <FromUserName><![CDATA[%s]]></FromUserName>                            <CreateTime>%s</CreateTime>                            <MsgType><![CDATA[%s]]></MsgType>                            <Content><![CDATA[%s]]></Content>                            <FuncFlag>0</FuncFlag>                            </xml>";                             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()    {        // you must define TOKEN by yourself        if (!defined("TOKEN")) {            throw new Exception('TOKEN is not defined!');        }                $signature = $_GET["signature"];        $timestamp = $_GET["timestamp"];        $nonce = $_GET["nonce"];                        $token = TOKEN;        $tmpArr = array($token, $timestamp, $nonce);        // use SORT_STRING rule        sort($tmpArr, SORT_STRING);        $tmpStr = implode( $tmpArr );        $tmpStr = sha1( $tmpStr );                if( $tmpStr == $signature ){            return true;        }else{            return false;        }    }}?>

This is an officially mentioned interface program.

The following describes Java interface programs.

When a user sends a message to the service through the customer service end, the server will forward the message to our public network server, that is, the sae Sina cloud server mentioned above. The specific business logic is completed on sae. After processing, the result is sent back to the server, and the server sends the result to the user.

It is risky to connect two completely non-edge servers (servers and sae). Therefore, a verification mechanism must exist. The specific verification process is

The Code is as follows:

The public platform requests coreServlet from sae.

Package org. liufeng. course. servlet; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. liufeng. course. service. coreService; import org. liufeng. course. util. signUtil;/*** core class for request processing ** @ author liufeng * @ date 2013-09-29 */public class CoreServlet extends HttpServlet {private static final long serialVersionUID = 4440739483644821986L; /*** request verification (confirm that the request comes from the server) */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// encrypted signature String signature = request. getParameter ("signature"); // timestamp String timestamp = request. getParameter ("timestamp"); // random number String nonce = request. getParameter ("nonce"); // random String echostr = request. getParameter ("echostr"); PrintWriter out = response. getWriter (); // request verification. if the verification succeeds, echostr is returned as is, indicating that the access is successful. Otherwise, the access fails if (SignUtil. checkSignature (signature, timestamp, nonce) {out. print (echostr);} out. close (); out = null;}/*** process the message sent from the server */public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// set request and response encoding to UTF-8 (to prevent Chinese garbled) request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); // call the core business class to receive and process messages String respXml = CoreService. processRequest (request); // response Message PrintWriter out = response. getWriter (); out. print (respXml); out. close ();}}

Message Processing class:

Package org. liufeng. course. util; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import java. util. arrays; /*** request verification tool class ** @ author liufeng * @ date 2013-09-01 */public class SignUtil {// consistent with the Token in the Development Mode Interface Configuration Information private static String token =" weixinCourse "; /*** verify the signature ** @ param signature: Encrypted signature * @ param timestamp * @ param nonce Random Number * @ return */public static boolean CheckSignature (String signature, String timestamp, String nonce) {// sort token, timestamp, and nonce alphabetically String [] paramArr = new String [] {token, timestamp, nonce }; arrays. sort (paramArr); // Concatenates the sorted result into a String content = paramArr [0]. concat (paramArr [1]). concat (paramArr [2]); String ciphertext = null; try {MessageDigest md = MessageDigest. getInstance ("SHA-1"); // encrypted string sha1 byte [] digest = md. di Gest (content. toString (). getBytes (); ciphertext = byteToStr (digest);} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} // compares the string encrypted by sha1 with signature. return ciphertext! = Null? Ciphertext. equals (signature. toUpperCase (): false ;} /*** convert a byte array to a hexadecimal String ** @ param byteArray * @ return */private static String byteToStr (byte [] byteArray) {String strDigest = ""; for (int I = 0; I <byteArray. length; I ++) {strDigest + = byteToHexStr (byteArray [I]);} return strDigest ;} /*** convert bytes to a hexadecimal String ** @ param mByte * @ return */private static String byteToHexStr (byte mByte) {char [] Digit = {'0', '1', '2', '3', '4', '5', '6', '7 ', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F '}; char [] tempArr = new char [2]; tempArr [0] = Digit [(mByte >>> 4) & 0X0F]; tempArr [1] = Digit [mByte & 0X0F]; String s = new String (tempArr); return s ;}}

CoreServlet is configured in web. xml:

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app version = "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-name> coreServlet </servlet-name> <servlet-class> org. liufeng. course. servlet. coreServlet </servlet-class> </servlet> <! --/CoreServlet is used to specify the access path of the Servlet --> <servlet-mapping> <servlet-name> coreServlet </servlet-name> <url-pattern>/coreServlet </url- pattern> </servlet-mapping> <welcome-file-list> <welcome-file> index. jsp </welcome-file> </welcome-file-list> </web-app>

Public platform Configuration:

The Platform prompts that the access is successful.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.