Micro-trust public Platform Development Introductory course (SAE Square Times Studio) _android

Source: Internet
Author: User
Tags cdata openid reserved sha1 sha1 encryption sprintf

We will use the micro-credit public account Square Times Studio as a tutorial example, two-dimensional code see bottom.

This series of tutorials will guide you through the following tasks:

Create Sina cloud computing platform application enable micro-credit public platform development Mode basic interface message and event micro-trust platform PHP SDK Micro-Communication public platform development mode principle Development weather forecast function

Chapter One Application server resources

Create the Sina cloud computing application

Application Account

We use the SAE Sina Cloud computing platform as the server resource, and request PHP environment +mysql database as the program running environment.
Application Address: http://sae.sina.com.cn/, use Sina Weibo account can directly login SAE, after the SAE will give 500 free cloud beans.



Create a new application

Click on the top of " My home page " after login

Click on the next side of the creation of new applications, then pop-up prompts, prohibit the placement of illegal content, click to continue to create, pop-up the following window.

Choose an unused AppID, if you always have been used do not know what good, then fill in your QQ number or mobile phone number.

Fill in Level two domain name AppID, application name, verification code, development language selection PHP, application type Select Web Application. Then click Create Application

Application creation succeeded. and automatically jump to the application list, you can see that you have just created the CCTV-7

Create version

Select CCTV-7 to the right of the application management of the following code management ,

Jump to code management

Click on the right side of

The default version number is 1, click Create, after success, as shown in the following image:

Here, the successful creation of a domain name URL for the http://cctv7.sinaapp.com/application.

Upload Code

Copy the following code down to save as index.php. You must use professional development editing software operations, such as notepad++, and do not use Windows ' own Notepad.

Copy Code code as follows:



<?php


/*


Square Times Studio http://www.cnblogs.com/txw1958/


CopyRight 2013 www.doucube.com All Rights Reserved


*/

Define ("TOKEN", "Weixin");
$WECHATOBJ = new Wechatcallbackapitest ();
if (Isset ($_get[' echostr ')) {
$WECHATOBJ->valid ();
}else{
$WECHATOBJ->responsemsg ();
}

Class Wechatcallbackapitest
{
Public Function Valid ()
{
$ECHOSTR = $_get["Echostr"];
if ($this->checksignature ()) {
Echo $echoStr;
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;
}
}

Public Function responsemsg ()
{
$POSTSTR = $GLOBALS ["Http_raw_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 = "<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 ($keyword = = "?" | | $keyword = = "? ")


{


$msgType = "text";


$CONTENTSTR = Date ("Y-m-d h:i:s", Time ());


$RESULTSTR = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR);


Echo $resultStr;


}


}else{


echo "";


Exit


}


}


}


?>


Then compress the index.php file into a zip format, and note that you cannot use the RAR format

This will generate a Index.zip file. or directly download square times already compressed zip file point this download

In the Code management interface, select the action button.

Select the upload code package.

Click Upload file, select just compress good index.zip file, click Upload, upload after success as shown below, if upload has problem, please in the Chrome browser to try again.

Click the Code Editor under the action button,

We can see the index.php has been uploaded successfully, double-click to see the code inside the edit

The creation of the Sina Cloud application was successful.

Chapter II Enabling Development mode

Development mode of micro-credit public platform

Advanced Features

Micro-Credit Public platform address: https://mp.weixin.qq.com

Login Micro-trust public platform background, select Advanced Features, enter after the two modes of view

We need to turn off edit mode first. Click Edit Mode to enter

Slide off

Development mode

into the development model

Click to become a developer

Pop-up URL and token fill box

The URL here is the domain name of the cloud application described in the previous article, and token is defined as Weixin in index.php. Prompt after submitting you have become a developer.

Then slide the upper-right corner to enable the button.

Congratulations, you have successfully enabled development mode.

Automatic reply

In the example above, a send "?" is implemented. will be able to reply to the current time function.
The effect is as follows:

At this point, your micro-trust public platform account has been automatically restored.

Chapter III basic interface messages and events

All accounts after the application, will get the basic interface permissions, the underlying interface would include receiving user messages, reply to the user message, accept the event to push three kinds of services.

Receive user messages

At present, ordinary users can push five kinds of messages to the public account: text (including facial expression), voice, picture, video, location, link.
The following five kinds of detailed details are as follows:

1. Text (including emoticons)
Send text and expressions

2. Picture

Send picture

3. Voice

Send Voice

4. Video

Send video

5. Location

Send Location

6. Link

Send Link

Reply to a message to a user

At present, ordinary public accounts can push six kinds of messages to users: text, graphics, music, pictures, voice, video. The picture and text message including a single message and a number of text messages, display way a little different.

Here are a few separate details as follows: "Pictures, voice, video due to the need to use and advanced interface-related media_id, in this tutorial is not discussed." 】

1. Text Message Format
Reply text

2. Text Message Format

2.1 Single text message
Reply to a single text


2.2 Multi-text message

Reply Multi-text

3. Music News

Reply to music messages

Receive event push

At present, users in the attention and cancellation of attention, and click on the menu will automatically send the event to the public platform push message:

1. Attention to Events

Fourth chapter micro-trust public platform PHP SDK

The Square Times Studio has developed the PHPSDK public platform, integrating all current messages and events to receive and send the code as follows:

Copy Code code as follows:



<?php


/*


Square Times Studio


http://www.cnblogs.com/txw1958/


CopyRight 2014 All Rights Reserved


*/

Define ("TOKEN", "Weixin");

$WECHATOBJ = new Wechatcallbackapitest ();
if (!isset ($_get[' echostr ')) {
$WECHATOBJ->responsemsg ();
}else{
$WECHATOBJ->valid ();
}

Class Wechatcallbackapitest
{
   //Authentication message
    Public Function valid ()
    {
        $echoStr = $_get["Echostr"];
        if ($this->checksignature ()) {
             Echo $echoStr;
            exit;
       }
   }

   /Check signature
    private Function checksignature ()
    {
        $signature = $_get["signature"];
        $timestamp = $_get["timestamp"];
        $nonce = $_get["nonce"];
        $token = token;
        $tmpArr = Array ($token, $timestamp, $nonce);
        Sort ($TMPARR, sort_string);
        $tmpStr = implode ($TMPARR);
        $tmpStr = SHA1 ($TMPSTR);

        if ($tmpStr = = $signature) {
             return true;
       }else{
             return false;
       }
   }

Response message
Public Function responsemsg ()
{
$POSTSTR = $GLOBALS ["Http_raw_post_data"];
if (!empty ($POSTSTR)) {
$this->logger ("R". $postStr);
$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata);
$RX _type = Trim ($postObj->msgtype);

Switch ($RX _type)


{


Case "Event":


$result = $this->receiveevent ($POSTOBJ);


Break


Case "Text":


$result = $this->receivetext ($POSTOBJ);


Break


Case "image":


$result = $this->receiveimage ($POSTOBJ);


Break


Case "Location":


$result = $this->receivelocation ($POSTOBJ);


Break


Case "Voice":


$result = $this->receivevoice ($POSTOBJ);


Break


Case "Video":


$result = $this->receivevideo ($POSTOBJ);


Break


Case "link":


$result = $this->receivelink ($POSTOBJ);


Break


Default


$result = "Unknown msg type:". $RX _type;


Break


}


$this->logger ("T". $result);


echo $result;


}else {


echo "";


Exit


}


}

Receive event messages


Private Function Receiveevent ($object)


{


$content = "";


Switch ($object->event)


{


Case "Subscribe":


$content = "Welcome attention to Square Times Studio";


$content. = (!empty ($object->eventkey))? ("\ n from two-dimensional code scene". Str_replace ("Qrscene_", "", $object->eventkey)): "";


Break


Case "Unsubscribe":


$content = "Cancellation of concern";


Break


Case "SCAN":


$content = "Scan Scene". $object->eventkey;


Break


Case "click":


Switch ($object->eventkey)


{


Case "Company":


$content = "Square times Studios provide Internet-related products and services." ";


Break


Default


$content = "click menu:". $object->eventkey;


Break


}


Break


Case "LOCATION":


$content = "Upload location: Latitude". $object->latitude. " Longitude ". $object->longitude;


Break


Case "VIEW":


$content = "Jump link". $object->eventkey;


Break


Default


$content = "Receive a new event:". $object->event;


Break


}


$result = $this->transmittext ($object, $content);


return $result;


}

Receive text messages


Private Function Receivetext ($object)


{


Switch ($object->content)


{


Case "Text":


$content = "This is a text message";


Break


Case "graphic":


Case "Single graphic":


$content = Array ();


$content [] = Array ("title" => "single caption", "Description" => "single Graphic Content", "Picurl =>" http://discuz.comli.com/weixin/ Weather/icon/cartoon.jpg "," Url "=>" http://m.cnblogs.com/?u=txw1958 ");


Break


Case "multi-text":


$content = Array ();


$content [] = Array ("title" => "multiple graphics and Text 1 titles", "Description" => "", "Picurl =>" http://discuz.comli.com/weixin/ Weather/icon/cartoon.jpg "," Url "=>" http://m.cnblogs.com/?u=txw1958 ");


$content [] = Array ("title" => "multiple graphics and Text 2 titles", "Description" => "", "Picurl =>" http://d.hiphotos.bdimg.com/wisegame/ Pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg "," Url "=>" http://m.cnblogs.com/?u=txw1958 ");


$content [] = Array ("title" => "multiple graphics and Text 3 titles", "Description" => "", "Picurl =>" http://g.hiphotos.bdimg.com/wisegame/ Pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg "," Url "=>" http://m.cnblogs.com/?u=txw1958 ");


Break


Case "Music":


$content = Array ("Title" => "the most dazzling national wind", "Description" => "singer: Phoenix Legend", "Musicurl =>" http://121.199.4.61/music/ Zxmzf.mp3 "," Hqmusicurl "=>" Http://121.199.4.61/music/zxmzf.mp3 ");


Break


Default


$content = Date ("Y-m-d h:i:s", Time ());


Break


}


if (Is_array ($content)) {


if (Isset ($content [0][' Picurl '])) {


$result = $this->transmitnews ($object, $content);


}else if (isset ($content [' Musicurl '])) {


$result = $this->transmitmusic ($object, $content);


}


}else{


$result = $this->transmittext ($object, $content);


}


return $result;


}

Receive picture messages
Private Function Receiveimage ($object)
{
$content = Array ("MediaId" => $object->mediaid);
$result = $this->transmitimage ($object, $content);
return $result;
}

   //Receive Location message
    Private Function ReceiveLocation ($object)
     {
        $content = "You are sending the position, Latitude is:". $object->location_x. " ; The longitude is: ". $object->location_y." ; The zoom level is: ". $object->scale." The location is: ". $object->label;
        $result = $this->transmittext ($object, $content);
        return $result;
   }

Receive voice messages
Private Function Receivevoice ($object)
{
if (Isset ($object->recognition) &&!empty ($object->recognition)) {
$content = "What you have just said is:". $object->recognition;
$result = $this->transmittext ($object, $content);
}else{
$content = Array ("MediaId" => $object->mediaid);
$result = $this->transmitvoice ($object, $content);
}

return $result;
}

Receive video message
Private Function Receivevideo ($object)
{
$content = Array ("MediaId" => $object->mediaid, "Thumbmediaid" => $object->thumbmediaid, "Title" => "", " Description "=>");
$result = $this->transmitvideo ($object, $content);
return $result;
}

Receive link messages
Private Function Receivelink ($object)
{
$content = "You are sending a link with the title:". $object->title. " The content is: ". $object->description." , the link address is: ". $object->url;
$result = $this->transmittext ($object, $content);
return $result;
}

   //Reply text message
    private Function Transmittext ($object, $content)
     {
        $textTpl = <xml>
<tousername><![ Cdata[%s]]></tousername>
<fromusername><![ Cdata[%s]]></fromusername>
<createtime>%s</createtime>
<msgtype><![ Cdata[text]]></msgtype>
<content><![ Cdata[%s]]></content>
</xml>;
        $result = sprintf ($TEXTTPL, $object->fromusername, $object-> Tousername, Time (), $content);
        return $result;
   }

Reply to Picture message
Private Function Transmitimage ($object, $imageArray)
{
$ITEMTPL = "<Image>
<mediaid><! [cdata[%s]]></mediaid>
</Image> ";

$item _str = sprintf ($ITEMTPL, $imageArray [' MediaId ']);

$TEXTTPL = "<xml>
<tousername><! [cdata[%s]]></tousername>
<fromusername><! [cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><! [cdata[image]]></msgtype>
$item _str
</xml> ";

$result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time ());
return $result;
}

Reply to a voice message
Private Function Transmitvoice ($object, $voiceArray)
{
$ITEMTPL = "<Voice>
<mediaid><! [cdata[%s]]></mediaid>
</Voice> ";

$item _str = sprintf ($ITEMTPL, $voiceArray [' MediaId ']);

$TEXTTPL = "<xml>
<tousername><! [cdata[%s]]></tousername>
<fromusername><! [cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><! [cdata[voice]]></msgtype>
$item _str
</xml> ";

$result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time ());
return $result;
}

Reply to video message
Private Function Transmitvideo ($object, $videoArray)
{
$ITEMTPL = "<Video>
<mediaid><! [cdata[%s]]></mediaid>
<thumbmediaid><! [cdata[%s]]></thumbmediaid>
<title><! [cdata[%s]]></title>
<description><! [cdata[%s]]></description>
</Video> ";

$item _str = sprintf ($ITEMTPL, $videoArray [' MediaId '], $videoArray [' Thumbmediaid '], $videoArray [' Title '], $videoArray [' Description ']);

$TEXTTPL = "<xml>
<tousername><! [cdata[%s]]></tousername>
<fromusername><! [cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><! [cdata[video]]></msgtype>
$item _str
</xml> ";

$result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time ());
return $result;
}

Reply to a text message


Private Function Transmitnews ($object, $newsArray)


{


if (!is_array ($newsArray)) {


Return


}


$ITEMTPL = "&lt;item&gt;


&lt;title&gt;&lt;! [cdata[%s]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[%s]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[%s]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[%s]]&gt;&lt;/url&gt;


&lt;/item&gt;


";


$item _str = "";


foreach ($newsArray as $item) {


$item _str. = sprintf ($ITEMTPL, $item [' Title '], $item [' Description '], $item [' Picurl '], $item [' Url ']);


}


$NEWSTPL = "&lt;xml&gt;


&lt;tousername&gt;&lt;! [cdata[%s]]&gt;&lt;/tousername&gt;


&lt;fromusername&gt;&lt;! [cdata[%s]]&gt;&lt;/fromusername&gt;


&lt;CreateTime&gt;%s&lt;/CreateTime&gt;


&lt;msgtype&gt;&lt;! [cdata[news]]&gt;&lt;/msgtype&gt;


&lt;content&gt;&lt;! [cdata[]]&gt;&lt;/content&gt;


&lt;ArticleCount&gt;%s&lt;/ArticleCount&gt;


&lt;Articles&gt;


$item _str&lt;/articles&gt;


&lt;/xml&gt; ";

$result = sprintf ($NEWSTPL, $object->fromusername, $object->tousername, Time (), Count ($newsArray));
return $result;
}

Reply to music messages
Private Function Transmitmusic ($object, $musicArray)
{
$ITEMTPL = "<Music>
<title><! [cdata[%s]]></title>
<description><! [cdata[%s]]></description>
<musicurl><! [cdata[%s]]></musicurl>
</Music> ";

$item _str = sprintf ($ITEMTPL, $musicArray [' Title '], $musicArray [' Description '], $musicArray [' Musicurl '], $musicArray [' Hqmusicurl ']);

$TEXTTPL = "<xml>
<tousername><! [cdata[%s]]></tousername>
<fromusername><! [cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><! [cdata[music]]></msgtype>
$item _str
</xml> ";

$result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time ());
return $result;
}

Log records


Private Function Logger ($log _content)


{


if (Isset ($_server[' http_appname ')) {//sae


Sae_set_display_errors (FALSE);


Sae_debug ($log _content);


Sae_set_display_errors (TRUE);


}else if ($_server[' remote_addr ']!= "127.0.0.1") {//local


$max _size = 10000;


$log _filename = "Log.xml";


if (file_exists ($log _filename) and (ABS (FileSize ($log _filename)) &gt; $max _size)) {unlink ($log _filename);}


File_put_contents ($log _filename, date (' H:i:s '). " ". $log _content." \ r \ n ", file_append);


}


}


}


?&gt;








Use the same method in the first chapter, save the above code as index.php, compress into Index.zip, or click to download, upload to SAE, your public account can receive and reply all message types and event notification.

Reply to the following text in the public account and you will receive the same reply as the previous chapter.

Copy Code code as follows:

Text
Graphic
Multi-text
Music
Time

You can also try the following to experience other messages

Send a picture to the public account
Send a voice to the public account
Send a video to a public account
Send location information to public account
Send a link in a collection to the public account fifth analysis of the development mode of micro-letter public platform

After experiencing the various functions of the previous section, we are only aware of it, in this section, will introduce on the basis of the above on the micro-trust public platform to send and receive messages mechanism and principle, this is the reason why.

The principle of message checking when development mode becomes developer

When a developer submits a validation request for the first time, the micro-server sends a GET request to the completed URL, with four parameters (signature, timestamp, nonce, ECHOSTR), which the developer uses to validate the signature (that is, signature) To determine the authenticity of this message.

Since then, each time the developer receives the user message, the micro-letter will also bring the previous three parameters (signature, timestamp, nonce) to the URL of the developer set up, and the developer will still judge the authenticity of the message by the effectiveness of the signature. The method is consistent with the first submission of the validation request.

Parameters Description
Signature The micro-letter encryption signature, signature, combines the token parameters and the timestamp parameters and Nonce parameters that the developer fills in.
Timestamp Time stamp
Nonce Random number
Echostr Random string



The developer verifies the request by checking the signature (there is a check method below). If you confirm this get request from the micro-trust server, please return the ECHOSTR parameter content, then the access is effective, the developer succeeds, otherwise the access failed.

The encryption/validation process is as follows:
1. Sort token, timestamp, nonce three parameters in dictionary order
2. Concatenation of three parameter strings into a string for SHA1 encryption
3. A developer obtains an encrypted string that can be compared with signature, identifying that the request originated from a micro-signaling enabling interface that is validated by the Checksignature () function in the code. If this principle is difficult to understand, you can temporarily do not delve, continue to look below.

The principle of being a developer after message sending and receiving

Look at this diagram again when the user sends a "?" , the system replies for a time

The message flow chart for this principle is shown below.

From the image above, you can see that the user is sending one?, the micro-trust server will assemble a message sent to our own server and then reply to a time, and the time will also be assembled in accordance with certain rules, reply to the public account, the public account and then reply to the user, in the process of sending and receiving, The sender and receiver are swapped (Tousername and fromusername value swaps), sending and receiving are transmitted in the background in XML format,

So mastering a variety of message types is the basis for the development of micro-trust public platform !

The following describes the various message types described above for the format of their XML packets.

XML packet analysis for various transceiver messages

Receive Message

1. Text (including emoticons)
Send text and expressions

Text Background format:

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1359028446</CreateTime>
<msgtype><! [cdata[text]]></msgtype>
<content><! [cdata[Test text]]></content>
<MsgId>5836982729904121631</MsgId>
</xml>

Expression background format

Copy Code code as follows:

<xml><tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1359044526</CreateTime>
<msgtype><! [cdata[text]]></msgtype>
<content><! [cdata[/::)/::~/::b/::|/:8-)]] ></Content>
<MsgId>5837051792978241864</MsgId>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type; text message literal
Content Message Contents
MsgId Message ID Number

As you can see, both the text and the expression type are text

2. Picture

Send picture

Background format:

Copy Code code as follows:

<xml><tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1359028479</CreateTime>
<msgtype><! [cdata[image]]></msgtype>
<picurl><! [cdata[http://mmbiz.qpic.cn/mmbiz/ l4qjytoibummhn90t1mnaibyiar8ljyicf3mw7xx3blp1qzgub7ctz0dxqyfi4uaqh1fws3huicpibjf0poqleqydmlg/0]]></ Picurl>
<MsgId>5836982871638042400</MsgId>
<mediaid><! [cdata[pgkso3lagbvtsfyo7fgu51kuya07d0c_nozz2fn1z6vythosf59ptfl0vaggxkvh]]></mediaid>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type; Picture message is image
Picurl Image link address, can be obtained with HTTP GET
MsgId Message ID Number

3. Voice

Send Voice

Background format:

Copy Code code as follows:

<xml><tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1359028479</CreateTime>
<msgtype><! [cdata[image]]></msgtype>
<picurl><! [cdata[http://mmbiz.qpic.cn/mmbiz/ l4qjytoibummhn90t1mnaibyiar8ljyicf3mw7xx3blp1qzgub7ctz0dxqyfi4uaqh1fws3huicpibjf0poqleqydmlg/0]]></ Picurl>
<MsgId>5836982871638042400</MsgId>
<mediaid><! [cdata[pgkso3lagbvtsfyo7fgu51kuya07d0c_nozz2fn1z6vythosf59ptfl0vaggxkvh]]></mediaid>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type; voice message is voice
MediaId Media ID
Format speech format, here for AMR
MsgId Message ID Number

Appendix: Introduction of AMR Interface
Full name adaptive multi-rate, mainly used for mobile device audio, compression is larger, but compared to other compression format quality is poor, because more for the voice, call, the effect is very good.

4. Video

Send video

Background format:

Copy Code code as follows:

xml><tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1359028186</CreateTime>
<msgtype><! [cdata[video]]></msgtype>
<mediaid><! [cdata[dbvfrij29lb2hxuypc0r6vlyxwgychzpbrj_iis6yaghutyxuktfsdcscpeoquyr]]></mediaid>
<thumbmediaid><! [cdata[mxuj5gcceesjwx2t9qsk62yziclcp_hnrdftqcojlpet2g9q3d22ukslybflz01j]]></thumbmediaid>
<MsgId>5836981613212624665</MsgId>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type; video Messages for videos
MediaId Media ID
Thumbmediaid media thumbnail ID?
MsgId Message ID Number

5. Location

Send Location

Background format:

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></flacfromusername>
<CreateTime>1359036619</CreateTime>
<msgtype><! [cdata[location]]></msgtype>
<Location_X>22.539968</Location_X>
<Location_Y>113.954980</Location_Y>
<Scale>16</Scale>
<label><! [Cdata[, No. No. 9789 Shennan Avenue, South Mt. District, Shenzhen, Guangdong, China: 518057]]></label>
<MsgId>5837017832671832047</MsgId>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type, location is location
location_x geographical latitude
location_y Geographical longitude
Scale Map Zoom Size
Label location Information
MsgId Message ID Number

6. Link

Send Link

Background format:

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjl2lydftam-oxdgb4xzcnc8]]></fromusername>
<CreateTime>1359709372</CreateTime>
<msgtype><! [cdata[link]]></msgtype>
<title><! [cdata[Public platform Developer's]]></title>
<description><! [cdata[Chen Kun public number This time the fire, everyone ...]] ></Description>
<url><! [cdata[http://israel.duapp.com/web/photo.php]]></url>
<MsgId>5839907284805129867</MsgId>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername Message receiver micro-signal, generally for the public platform account micro-signal
Fromusername message sending side micro-signal
Createtime Message creation Time
Msgtype message type, links to link
Title Text message Header
Description Text message Description
URL Click Text message Jump link
MsgId Message ID Number

Send a message

Only three types of messages are presented: text, graphics, music. The picture and text message including a single message and a number of text messages, display way a little different.

1. Text Message Format
Reply text

Background format:

Copy Code code as follows:

<xml>
<tousername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></tousername>
<fromusername><! [cdata[gh_680bdefc8c5d]]></fromusername>
<CreateTime>1359036631</CreateTime>
<msgtype><! [cdata[text]]></msgtype>
<content><! [cdata["Shenzhen" Weather fact temperature: 27 ℃ Humidity: 59% Wind Speed: 3 Class of Northeast
Sunday, November 03 27℃~23℃ rain, Northeast 4-5
November 04 Monday 26℃~21℃ Shower Breeze
November 05 Tuesday 27℃~22℃ Yin Breeze]]></content>
<FuncFlag>0</FuncFlag>
</xml>

XML Format Tutorial

Copy Code code as follows:

Fromusername message Sender
Tousername Message Receiver
Createtime Message creation Time
Msgtype message type, text message must be filled in
Content message contents, size is limited to 2048 bytes, Word blank is illegal request
Funcflag star Mark Field

2. Text Message Format
2.1 Single text message
Reply to a single text




Background format:

Copy Code code as follows:



&lt;xml&gt;


&lt;tousername&gt;&lt;! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]&gt;&lt;/tousername&gt;


&lt;fromusername&gt;&lt;! [cdata[gh_680bdefc8c5d]]&gt;&lt;/fromusername&gt;


&lt;CreateTime&gt;1359011899&lt;/CreateTime&gt;


&lt;msgtype&gt;&lt;! [cdata[news]]&gt;&lt;/msgtype&gt;


&lt;content&gt;&lt;! [cdata[]]&gt;&lt;/content&gt;


&lt;ArticleCount&gt;1&lt;/ArticleCount&gt;


&lt;Articles&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata[[Apple product information Inquiry]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[serial numbers: Use IMEI number


IMEI No.: 358031058974471


Device Name: IPhone 5C


Device color:


Equipment Capacity:


Activation Status: Activated


Phone support: not expired [2014-01-13]


Hardware warranty: not expired [2014-10-14]


Production Factory: China]]&gt;


&lt;/Description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/banner.jpg]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;/Articles&gt;


&lt;FuncFlag&gt;0&lt;/FuncFlag&gt;


&lt;/xml&gt;


2.2 Multi-text message

Reply Multi-text

Background data format

Copy Code code as follows:



&lt;xml&gt;


&lt;tousername&gt;&lt;! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]&gt;&lt;/tousername&gt;


&lt;fromusername&gt;&lt;! [cdata[gh_680bdefc8c5d]]&gt;&lt;/fromusername&gt;


&lt;CreateTime&gt;1359011829&lt;/CreateTime&gt;


&lt;msgtype&gt;&lt;! [cdata[news]]&gt;&lt;/msgtype&gt;


&lt;content&gt;&lt;! [cdata[]]&gt;&lt;/content&gt;


&lt;ArticleCount&gt;5&lt;/ArticleCount&gt;


&lt;Articles&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata["Shenzhen" Weather Fact temperature: 3 ℃ Humidity: 43﹪ wind Speed: Southwest 2]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/banner.jpg]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata[06 Month 24th Thursday 2℃~-7℃ Clear North 3-4 to the southeast wind is less than 3 level]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/d00.gif]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata[06 Month 25th Friday -1℃~-8℃ clear Southeast Wind is less than 3 turn to the northeast 3-4 class]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/d00.gif]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata[06 Month 26th Saturday -1℃~-7℃ Cloudy and easterly winds 3-4 turn southeast wind is less than 3 grade]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/d01.gif]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;item&gt;


&lt;title&gt;&lt;! [cdata[06 month 27th Sunday 0℃~-6℃ Cloudy Southeast Wind is less than 3 turn to the northeast 3-4 class]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[http://www.doucube.com/weixin/weather/icon/d01.gif]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[]]&gt;&lt;/url&gt;


&lt;/item&gt;


&lt;/Articles&gt;


&lt;FuncFlag&gt;0&lt;/FuncFlag&gt;


&lt;/xml&gt;


XML Format Tutorial

Copy Code code as follows:

Fromusername message Sender
Tousername Message Receiver
Createtime Message creation Time
Msgtype message type, text message must be filled in news
Content message contents, text message can fill in the blanks
Articlecount text message number, limited to 10
Articles multiple message information, the default first item for large image
Title Text message Header
Description Text message Description
Picurl picture link, support JPG, PNG format, good effect for large figure 640*320, small figure 80*80
URL Click Text message Jump link
Funcflag star Mark Field

3. Music News

Reply to music messages

Background format:

Copy Code code as follows:



&lt;xml&gt;


&lt;tousername&gt;&lt;! [cdata[ollb4jqgdo_crnvxk_wrnsywgtq8]]&gt;&lt;/tousername&gt;


&lt;fromusername&gt;&lt;! [cdata[gh_b629c48b653e]]&gt;&lt;/fromusername&gt;


&lt;CreateTime&gt;1372310544&lt;/CreateTime&gt;


&lt;msgtype&gt;&lt;! [cdata[music]]&gt;&lt;/msgtype&gt;


&lt;Music&gt;


&lt;title&gt;&lt;! [cdata[the most dazzling national wind]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [Cdata[Phoenix legend]]&gt;&lt;/description&gt;


&lt;musicurl&gt;&lt;! [cdata[http://zj189.cn/zj/download/music/zxmzf.mp3]]&gt;&lt;/musicurl&gt;


&lt;hqmusicurl&gt;&lt;! [cdata[http://zj189.cn/zj/download/music/zxmzf.mp3]]&gt;&lt;/hqmusicurl&gt;


&lt;/Music&gt;


&lt;FuncFlag&gt;0&lt;/FuncFlag&gt;


&lt;/xml&gt;


XML Format Tutorial

Copy Code code as follows:

Tousername Receiver Account (OpenID received)
Fromusername Developer Micro-signal
Createtime Message creation Time
Msgtype message type, here is music
Title Music titles
Description Music Description
Musicurl Music Links
Hqmusicurl High quality music links, WiFi environment first use the link to play music
Funcflag bit 0x0001 is flagged when the star has just received the message.

Event message Type

At present, users in the attention and cancellation of attention, and click on the menu will automatically send the event to the public platform push message:

1. Attention to Events

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_b629c48b653e]]></tousername>
<fromusername><! [cdata[ollb4jv7la3tydjvijp5v9qtu_ka]]></fromusername>
<CreateTime>1372307736</CreateTime>
<msgtype><! [cdata[event]]></msgtype>
<event><! [cdata[subscribe]]></event>
<eventkey><! [cdata[]]></eventkey>
</xml>

2. Cancellation of attention Events

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_b629c48b653e]]></tousername>
<fromusername><! [cdata[ollb4jqgdo_crnvxk_wrnsywgtq8]]></fromusername>
<CreateTime>1372309890</CreateTime>
<msgtype><! [cdata[event]]></msgtype>
<event><! [cdata[unsubscribe]]></event>
<eventkey><! [cdata[]]></eventkey>
</xml>

3. Menu click event

Copy Code code as follows:

<xml>
<tousername><! [cdata[gh_680bdefc8c5d]]></tousername>
<fromusername><! [cdata[oidrpjqasytpnxrmps9o_ruzgsfk]]></fromusername>
<CreateTime>1377886191</CreateTime>
<msgtype><! [cdata[event]]></msgtype>
<event><! [cdata[click]]></event>
<eventkey><! [cdata[Weather Shenzhen]]></eventkey>
</xml>

XML Format Tutorial

Copy Code code as follows:

Tousername receiver-side micro-signal
Fromusername signal, if for ordinary users, is an OpenID
Createtime Message creation Time
Msgtype Message Type, event
Event events type, subscribe (subscription), unsubscribe (unsubscribe), click (Custom menu click event)
Eventkey event key value, corresponding to key value in custom menu interface



The sixth chapter develops the weather forecast function

In this chapter, we develop the weather forecast function quickly, we use the square times the corresponding interface of the studio to realize. The following code implements this functionality.

Copy Code code as follows:



&lt;?php


/*


Square Times Studio


CopyRight 2014 All Rights Reserved


*/

Define ("TOKEN", "Weixin");

$WECHATOBJ = new Wechatcallbackapitest ();
if (!isset ($_get[' echostr ')) {
$WECHATOBJ->responsemsg ();
}else{
$WECHATOBJ->valid ();
}

Class Wechatcallbackapitest
{
Public Function Valid ()
{
$ECHOSTR = $_get["Echostr"];
if ($this->checksignature ()) {
Echo $echoStr;
Exit
}
}

    Private Function checksignature ()
    {
         $signature = $_get["signature"];
        $timestamp = $_get["timestamp"];
        $nonce = $_get["nonce"];
        $token = token;
        $tmpArr = Array ($token, $timestamp, $nonce);
        Sort ($TMPARR, sort_string);
        $tmpStr = implode ($TMPARR);
        $tmpStr = SHA1 ($TMPSTR);

if ($tmpStr = = $signature) {
return true;
}else{
return false;
}
}

Public Function responsemsg ()
{
$POSTSTR = $GLOBALS ["Http_raw_post_data"];
if (!empty ($POSTSTR)) {
$this->logger ("R". $postStr);
$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata);
$RX _type = Trim ($postObj->msgtype);

Switch ($RX _type)


{


Case "Event":


$result = $this-&gt;receiveevent ($POSTOBJ);


Break


Case "Text":


$result = $this-&gt;receivetext ($POSTOBJ);


Break


}


$this-&gt;logger ("T". $result);


echo $result;


}else {


echo "";


Exit


}


}

    Private Function Receiveevent ($object)
    {
         $content = "";
        switch ($object->event)
         {
            case "Subscribe":
                 $content = "Welcome attention to Square Times Studio";
                break;
       }
        $result = $this->transmittext ($object, $content);
        return $result;
   }

Private Function Receivetext ($object)
{
$keyword = Trim ($object->content); $url = "http://apix.sinaapp.com/weather/?appkey=". $object->tousername. " &city= ". UrlEncode ($keyword);
$output = file_get_contents ($url);
$content = Json_decode ($output, true);

$result = $this->transmitnews ($object, $content);
return $result;
}

Private Function Transmittext ($object, $content)
{
$TEXTTPL = "<xml>
<tousername><! [cdata[%s]]></tousername>
<fromusername><! [cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><! [cdata[text]]></msgtype>
<content><! [cdata[%s]]></content>
</xml> ";
$result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time (), $content);
return $result;
}

Private Function Transmitnews ($object, $newsArray)


{


if (!is_array ($newsArray)) {


Return


}


$ITEMTPL = "&lt;item&gt;


&lt;title&gt;&lt;! [cdata[%s]]&gt;&lt;/title&gt;


&lt;description&gt;&lt;! [cdata[%s]]&gt;&lt;/description&gt;


&lt;picurl&gt;&lt;! [cdata[%s]]&gt;&lt;/picurl&gt;


&lt;url&gt;&lt;! [cdata[%s]]&gt;&lt;/url&gt;


&lt;/item&gt;


";


$item _str = "";


foreach ($newsArray as $item) {


$item _str. = sprintf ($ITEMTPL, $item [' Title '], $item [' Description '], $item [' Picurl '], $item [' Url ']);


}


$NEWSTPL = "&lt;xml&gt;


&lt;tousername&gt;&lt;! [cdata[%s]]&gt;&lt;/tousername&gt;


&lt;fromusername&gt;&lt;! [cdata[%s]]&gt;&lt;/fromusername&gt;


&lt;CreateTime&gt;%s&lt;/CreateTime&gt;


&lt;msgtype&gt;&lt;! [cdata[news]]&gt;&lt;/msgtype&gt;


&lt;content&gt;&lt;! [cdata[]]&gt;&lt;/content&gt;


&lt;ArticleCount&gt;%s&lt;/ArticleCount&gt;


&lt;Articles&gt;


$item _str&lt;/articles&gt;


&lt;/xml&gt; ";

$result = sprintf ($NEWSTPL, $object->fromusername, $object->tousername, Time (), Count ($newsArray));
return $result;
}

Private Function Logger ($log _content)
{

}
}
?>

The commands used in the public accounts are as follows:

1. Send the city name, such as "Shenzhen", can inquire the weather of the city
Enter the appropriate command on your public account, and the implementation looks similar to the following:

Seventh Chapter Summary

In general, through this tutorial, you get the following rewards:

1. You get a free cloud computing space of 2 through this tutorial. You have successfully enabled the development model and implemented an automatic response time of 3. You have experienced a variety of message receiving and sending very quickly, for example, times when the time spent on their own exploration is much shorter than 4. You understand the principle of the development of the micro-credit public platform, and familiar with all kinds of messages and how it was sent 5. You use the interface of the Square Times studio, successfully developed your first micro-trust public platform function-weather forecast.
What should we do next? You can learn to develop some of the basics of common functions, recommended: Square times Studio preparation, the machinery industry press published the "Micro-trust platform development best Practice", which contains a lot of PHP development techniques, database use, and nearly 30 micro-trust public platform practical functions or technology.

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.