WeChat public platform development-mass messaging and mass messaging on public platforms

Source: Internet
Author: User
Tags openid

Public platform development-mass messaging and mass messaging on public platforms

1. Purpose

Send messages to the public account. This is just a simple task.Text sending. You can also send voice images, but the data sending format is different. There is a link below to query the data sending format.

2. Process of sending mass messages

3. Obtain the test public account + follow public account

1) obtain the public test account

Access the connection above, select "Interface Test number application" to get to open the http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo directly? Action = showinfo & t = sandbox/index: scan the client to log on.

After logon, you can obtain information about a public account. There are two parameters: appId and appsecret, which uniquely identify a public number and use them as parameters to obtain user information. ,

2) configure the Interface Information

For this step, you can refer to the access instructions. This page provides a php instance for downloading. It is easy to modify the custom TOKEN and then place the verification page on your server.

Here I provide an example:

Prepare resources:

Domain name + space (My sae space + hichina domain name), PHP file for verification only

I created a wx_sample.php

Wx_sample.php

<?php/**  * wechat php test  *///define your tokendefine("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)){                /* 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;        }    }}?>

Then fill in the configuration information Token (must be consistent with the token in wx_sample.php above), URL (wx_sample.php address)

 

Then you can submit it.

If the message fails, check the Token and URL. [if your domain name and space are used, apply for an ICP filing; baidu sae and Sina sae must apply for and pass the certification by themselves (that is, they must take a hand-held Certificate photo and upload it in at least two days). This step is required]

3) configure the JS interface Security Domain Name

Enter this domain name is not to bring protocol, such as http://www.sagosoft.com/This is wrong, this is the URL is not a Domain Name

The domain name should be similar to www.sagosoft.com [otherwise, the invalid url domain will be prompted during js-sdk access]

 

4) follow the public account

Only when a user pays attention to this public account can he authorize a third party to log on and obtain user information through the link with the public account information. Therefore, we need to use our attention number as follows:

We can see that there is a QR code on this page, and we can scan the QR code to follow it, follow the "user list" on the right to add more user information. As shown in:

5) configure the callback function

When the client accesses a third-party webpage (that is, our own webpage), we can use the webpage authorization mechanism, we need not only the previously obtained appid and appsecret, but also the domain name settings for callback after user authorization, that is, where the page will jump to after user authorization. The specific configuration is as follows:

On the previous page, there is a "webpage authorization to obtain basic user information" and click Modify next to it.

Enter the callback Domain Name:

The domain name is the root domain name configured above. If you fill in zcr.sinaaappc.com/wx_sample.php in the "interface configuration information" above, you only need to fill in zcr.sinaaappc.com.

If your website is not blacklisted, it will appear on the top

Note::

1. Enter the domain name (a string) instead of the URL. Therefore, do not add http: // and other protocol headers. 2. Configure the authorization callback domain name as a full domain name, for example, the need for web site authorization Domain Name: www.qq.com, after the configuration of this domain name under the page http://www.qq.com/music.html, http://www.qq.com/login.html can be OAuth2.0 authentication. But http://pay.qq.com, http://music.qq.com, http://qq.com cannot perform OAuth2.0 Authentication

Here, we have completed the acquisition and configuration of the Public Account test account, and the user has followed the public account.

4. Get our access_token through appid and appsecret

Access_token is the globally unique ticket of the public account. access_token is required when the Public Account calls each interface. Developers need to properly store them. The storage of access_token must contain at least 512 characters. The validity period of access_token is currently 2 hours. You need to refresh it regularly. Repeated access_token acquisition will invalidate the last access_token.

Method:

Http Request Method: GEThttps: // api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = APPID & secret = APPSECRET

 

Parameter description

Parameters Required? Description
Grant_type Yes Obtain access_token and enter client_credential
Appid Yes Unique third-party user credential
Secret Yes The unique credential key of a third-party user, that is, appsecret

Return description

Normally, the following JSON data packet is returned to the Public Account:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

 

Parameters Description
Access_token Obtained credential
Expires_in Valid credential time, in seconds


When an error occurs, an error code or other information is returned. An example of a JSON data packet is as follows (this example is an invalid AppID error ):

{"errcode":40013,"errmsg":"invalid appid"}

 

Example:

Get access_token:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4d1cb8dbd827a16e9&secret=d462d4c36b116795d1d99dcf0547af5443d

Returned data:

{  "access_token": "qR5UK2vMf5aTHV8e-uB10FZW0caTZm_1kbkUe4OPK2ILVvNaoa7pLzYWqLUAmx6Sjq1E7pKHrVAtuG0_1MPkqmDfOkm2750kaLWNk59DS-iDOpjjxompJtXa3WhbN5FKRWNhADAVAR",  "expires_in": 7200}

5. send SMS messages through access_token

On the website of the public platform, the Group Sending permission is provided for the subscription number one per day, and the Group Sending permission is provided for the service number four per month (calendar month. For some public account operators with development capabilities, they can use the advanced group sending interface to achieve more flexible Group Sending capabilities.

Note:

1. For the authentication subscription number,Group interface can be successfully called once a dayThis group can be sent to all users or a group. 2. Although developers can use the advanced group interface to send authentication service numbers up to 100 times a day, however, a user can receive only four messages per month. No matter on the public platform website or using an interface to send Group messages, the user can receive only four group messages each month, if more than four messages are sent to a group, the user will fail to be sent. 3. If you have a public account with the payment permission, when you use the group-sending interface to upload or send text messages to a group, you can use the <a> label to add an external link. 4. The developer can use the preview interface to verify the message style and layout. The preview interface can send edited messages to the specified user for verification.

 

1) group by group. [Both the subscription number and service number can be used after authentication]

Call interface:

Http Request Method: POSThttps: // api.weixin.qq.com/cgi-bin/message/mass/sendall? Access_token = ACCESS_TOKEN

Add the following data to the body (send data in JSON format) -- send data in other formats. You only need to modify the parameter information. For details, refer to the official documentation:

{   "filter":{      "is_to_all":false,      "group_id":2   },   "text":{      "content":"CONTENT"   },    "msgtype":"text"}

 

Parameter description:

Parameters Required? Description
Filter Yes Used to set the receiver of a text message
Is_to_all No This parameter is used to set whether to send messages to all users. The value is true or false. If it is set to true, the messages are sent to all users. If it is set to false, messages can be sent to users in the specified group based on group_id.
Group_id No Group_id of the group to which a group is sent. This parameter is used for the user group interface in user management. If the value of is_to_all is true, group_id is not required.
Mpnews Yes Used to set the text message to be sent
Media_id Yes Media_id used for group messages
Msgtype Yes Group message type. The text message is mpnews, the text message is text, the voice is voice, the music is music, the image is image, the video is video, and the card coupon is wxcard.
Title No Message Title
Description No Message description
Thumb_media_id Yes Media ID of the video thumbnail

Example: Send to everyone

Url:

https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=KBoNONaJZ4-KhafQVJoQ6VBX0F-bls7nAsJBn8Fy7GLwav4Be1lRJcob1RHH6wW35IxxFwkJnZfnc-On9EQITg3oxEWUw7O2YyVW9naDknu6PQX9fnSmQcr8ojTK8Ug-HDTcAAABXN

 

Json data sent: send to all users

{   "filter":{      "is_to_all":true   },   "text":{      "content":"CONTENT"   },    "msgtype":"text"}

 

Returned data:

{  "errcode": 0,  "errmsg": "send job submission success",  "msg_id": 1000000003}

 

Parameter meaning:

 

Parameters Description
Type Media file types, including image, voice, video, and thumb.
Errcode Error Code
Errmsg Error Message
Msg_id ID of the message sending task
Msg_data_id The data ID of the message. This field appears only when a group of text messages is sent. It can be used to obtain the corresponding text message data in the graphic analysis data interface, which is the first half of the msgid field in the graphic analysis data interface, for details, see the description of the msgid field in the graphic analysis data interface.

Error Codes and query:

Global error code parsing

Use postman to simulate https request sending, as shown in:

2) send a group of [subscription numbers unavailable, available after service number authentication] based on the OpenID list]

Http request url: (Note: different from the above)

Http Request Method: POSThttps: // api.weixin.qq.com/cgi-bin/message/mass/send? Access_token = ACCESS_TOKEN

 

Data format:

{   "touser":[    "OPENID1",    "OPENID2"   ],    "msgtype": "text",    "text": { "content": "hello from boxer."}}

 

OPENID1 and OPENID2 are the user openId (Unique User ID) to be sent ).

Example:

Send "oF3PcsnsrMiJzEwalZZbAfWQpxCI ","OF3PcshH1CUIhR_WYau6swUiPzlw" two users.

Content: hello from boxer. <a href = 'www .baidu.com '> welcome to Baidu </a>

Url:

https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=wRyTbnsiu18ssEhMPLf4bDfeT-Bt6e6tgR4CQGVLBipRcyJPkdAKPYfM6-qkKuHUN8uRKJh6Xvm0OuAdFgqOo8Ru8hoDxl-cGc9bh-ezJb2ZUcJSnQk2s416zI8kbEOfOGYdAFARJB

 

Json data:

{"Touser": ["oF3PcsnsrMiJzEwalZZbAfWQpxCI", "audio"], "msgtype": "text", "text": {"content": "hello from boxer. <a href = 'HTTP: // www.seewoedu.com/'> welcome to xivo college </a> "}}

 

Returned data:

{  "errcode": 0,  "errmsg": "send job submission success",  "msg_id": 3147483654}

 

Use postman to send the following requests:

Received content:

 

Related Development:

Open Platform development-web page scan login (OAuth2.0) public platform development-authorized login (OAuth2.0)

Thank you!

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.