Platform technology-Introduction to the use of messaging services


The message service is an active push service launched by the open platform to improve the efficiency of application API calls (FromTaobao). The push content includes (Taobao transactions, products, refunds, etc. information) , based on this push service, the application no longer needs to continuously poll the API to obtain Taobao data. It only needs to call the API when receiving the message pushed by Taobao, which greatly improves the efficiency of API calls and reduces API usage costs. At the same time, it also provides message return service (ToTaobao). The application can return information to Taobao and provide product data source services.

FromTaobao: Taobao pushes Taobao (including Tmall) official news about transactions, products, refunds, etc.

To Taobao: That is, the message is returned to Taobao.

So how to use the messaging service? Please see the following detailed instructions for using the messaging service From Taobao and To Taobao.

FromTaobao message service uses

image

#App subscription message

Enter ISV console, On the "Application Management->Message Service->Subscription Message" page, select the required message to subscribe, and click "Subscribe" behind the corresponding message

image

# #The subscription message is successful. You can view the successfully subscribed messages in "My Subscriptions". If you need to cancel the message subscription, click "Cancel Subscription" directly. Click the message name to view the detailed field information returned by each message.

image

Note: If the message does not have permission, it means that the application has not opened the relevant API call permission. Click "Apply for permission" to apply for the corresponding permission package. In addition, if you need to activate the message service in the sandbox, you can refer to the [Sandbox Message Service Activation] chapter of this article

Activate the message for the user

Call

taobao The .tmc.user.permit interface is activated for users (i.e. Taobao or Tmall merchants). You can choose to activate only some message types for users, or you can activate all of them. For details, please see the API parameter description.

Remark:

  • The prerequisite for activating messages for users is that the user has authorized the application. If not authorized, please refer to Getting user authorization instructions.
  • To cancel the user's message service, call the taobao.tmc.user.cancel interface.
  • You can obtain the user's activated message through the interface taobao.tmc.user.get. The input parameters must be input is_valid, topics, modified to determine whether the user authorization message is successful
  • Message service API document:Click here to view

Code to implement receiving messages

Formal environment service address: ws://mc.api.taobao.com/
Sandbox environment service address: ws://mc.api.tbsandbox.com/
There are two ways to receive messages: Receive messages through SDK, Receive through API Message, it is recommended to use SDK to receive messages.

Receive messages through SDK

Currently supports JAVA and .NET languages. For other languages, it is recommended to use API to receive messages. When receiving messages through the SDK, you only need to focus on business processing. You do not need to worry about message resending, confirmation, reconnection of long connections, etc. The SDK will automatically handle everything.

JAVA interface usage instructions

public interface MessageHandler {
 
    /**
     * 消息通道客户端收到消息后,会回调该方法处理具体的业务,处理结果可以通过以下两种方式来表述:
     * <ul>
     * <li>抛出异常或设置status.fail()表明消息处理失败,需要消息通道服务端重发
     * <li>不抛出异常,也没有设置status信息,则表明消息处理成功,消息通道服务端不会再投递此消息
     *
     * @param message 消息内容
     * @param status 处理结果,如果调用status.fail(),消息通道将会择机重发消息;否则,消息通道认为消息处理成功
     * @throws Exception 消息处理失败,消息通道将会择机重发消息
     */
    public void onMessage(Message message, MessageStatus status) throws Exception;
 
}

JAVA usage code examples

TmcClient client = new TmcClient("app_key", "app_secret", "default"); // 关于default参考消息分组说明
client.setMessageHandler(new MessageHandler() {
    public void onMessage(Message message, MessageStatus status) {
        try {
            System.out.println(message.getContent());
            System.out.println(message.getTopic());
        } catch (Exception e) {
            e.printStackTrace();
            status.fail(); // 消息处理失败回滚,服务端需要重发
          // 重试注意:不是所有的异常都需要系统重试。
          // 对于字段不全、主键冲突问题,导致写DB异常,不可重试,否则消息会一直重发
          // 对于,由于网络问题,权限问题导致的失败,可重试。
          // 重试时间 5分钟不等,不要滥用,否则会引起雪崩
        }
    }
});
client.connect("ws://mc.api.taobao.com"); // 消息环境地址:ws://mc.api.tbsandbox.com/
Note: Use the Java main method to run in Eclipse When testing the above code, please add Thread.sleep after client.connect() to let the main thread wait for a period of time to observe the real-time reception of messages. Otherwise, after the main thread ends, the TMC long connection will also be disconnected. If you are running the above code on a web server, you do not need to add any Thread.sleep code after client.connect(), nor do you need to wrap a while (true) loop outside, because the main thread on the web server only needs the server to Closing will not end, and the long connection of TMC will always be maintained.

C#Use sample code

TmcClient client = new TmcClient("appkey", "appsecret", "default"); // 关于default参考消息分组说明
client.OnMessage += (s, e) =>
{
    try
    {
        Console.WriteLine(e.Message.Topic);
        Console.WriteLine(e.Message.Content);
        // 默认不抛出异常则认为消息处理成功
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp.StackTrace);
        e.Fail(); // 消息处理失败回滚,服务端需要重发
        // 重试注意:不是所有的异常都需要系统重试。 
        //对于字段不全、主键冲突问题,导致写DB异常,不可重试,否则消息会一直重发
        // 对于,由于网络问题,权限问题导致的失败,可重试。
        // 重试时间 5分钟不等,不要滥用,否则会引起雪崩
    }
};
client.Connect("ws://mc.api.taobao.com/"); // 消息环境地址:ws://mc.api.tbsandbox.com/
Note: When using the C# Main method to run the above code test in the VS console project, please add Console.Read() or Thread.Sleep after client.Connect to keep the main thread from ending temporarily so that you can observe the messages. The real-time reception situation, otherwise after the Main thread ends, the TMC long connection will also be disconnected. If you are running the above code in an IIS server or C# application, you do not need to add any waiting code after client.Connect, nor do you need to wrap a while (true) loop outside. As long as the IIS server or C# application does not When closed, TMC's long connection will be maintained.

Receive messages through API

The purpose of providing API to receive messages is to use languages ​​that are inconvenient for multi-threading and long connection processing, such as PHP and Python. There is currently no official SDK provided for these languages. You can use the following two APIs together to achieve the purpose of receiving and confirming messages. It is recommended to use the SDK method as much as possible. If the API must be used, it is recommended that the taobao.tmc.messages.consume interface be called with no concurrency or too much concurrency. There are situations where the real-time performance of API use is not very high. If the real-time requirements are high, it is still recommended. Use SDK.

Basic steps:

  • First consume the message: API name: taobao.tmc.messages.consumeAfter the message is consumed, the pointer will automatically move backward and will be called next time Unconsumed messages are automatically obtained, but messages after consumption confirmation cannot be obtained again.
  • Then confirm the message: API name: taobao.tmc.messages.confirmAfter obtaining the message, if it is not confirmed, the message service will choose the opportunity to resend, and the number of resends is controlled by the message service. If the message is not confirmed within 3 days it will be deleted.

JAVA Sample Code

TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "app_key", "app_secret", "json");
do {
    long quantity = 100L;
    TmcMessagesConsumeResponse rsp = null;
    do {
        TmcMessagesConsumeRequest req = new TmcMessagesConsumeRequest();
        req.setQuantity(quantity);
        req.setGroupName("default");
        rsp = client.execute(req);
        if (rsp.isSuccess() && rsp.getMessages() != null) {
            for (TmcMessage msg : rsp.getMessages()) {
                // handle message
                System.out.println(msg.getContent());
                System.out.println(msg.getTopic());
                // confirm message
                TmcMessagesConfirmRequest cReq = new TmcMessagesConfirmRequest();
                cReq.setGroupName("default");
                cReq.setsMessageIds(String.valueOf(msg.getId()));
                TmcMessagesConfirmResponse cRsp = client.execute(cReq);
                System.out.println(cRsp.getBody());
            }
        }
        System.out.println(rsp.getBody());
    } while (rsp != null && rsp.isSuccess() && rsp.getMessages() != null && rsp.getMessages().size() == quantity);
    Thread.sleep(1000L);
} while (true);

C#Sample Code

ITopClient client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", "app_key", "app_secret", "json");
do
{
    long quantity = 100L;
    TmcMessagesConsumeResponse rsp = null;
    do
    {
        TmcMessagesConsumeRequest req = new TmcMessagesConsumeRequest();
        req.GroupName = "default";
        req.Quantity = quantity;
        rsp = client.Execute(req);
        if (!rsp.IsError && rsp.Messages != null)
        {
            foreach (TmcMessage msg in Messages)
            {
                // handle message  
                Console.WriteLine(msg.Topic);
                Console.WriteLine(msg.Content);
                // confirm message  
                TmcMessagesConfirmRequest cReq = new TmcMessagesConfirmRequest();
                cReq.GroupName = "default";
                cReq.SMessageIds = msg.Id.ToString();
                TmcMessagesConfirmResponse cRsp = client.Execute(cReq);
                Console.WriteLine(cRsp.Body);
            }
        }
        Console.WriteLine(rsp.Body);
    } while (rsp != null && !rsp.IsError && rsp.Messages != null && rsp.Messages.Count == quantity);
    Thread.Sleep(new TimeSpan(0, 0, 1));
} while (true);
Note: Average of messages pulled through API RT can reach about 10 milliseconds when the network is good. Every time the message obtained by consumption is empty, be sure to pause for at least 1 second before executing the next loop to pull messages. Otherwise, many unnecessary requests will be generated and the server's time will be wasted. resources, as well as the application's own API traffic package.

Introduction to the use of message grouping

When the number of users is large, multiple machines need to form a cluster to receive messages, or merchants are isolated to receive messages independently. Both SDK and API can receive messages through multiple connections.

The messaging service supports multiple connections in two ways: Ⅰ. Create multiple user groups, and each user group establishes a connection. Ⅱ. Establish multiple connections in the same group

  • Create a group: Call the interface taobao.tmc.group.addCreate a custom group. Note: The messaging service will create a default group for the application. Users who are not assigned to the specified group [group] belong to the default group. When consuming messages through the SDK or API, if a group is not specified, the default group connection is used.
  • Delete a group: Call the interface taobao.tmc.group.deleteDelete the specified group or users under the group. Note: Each application can create up to 50 groups, and there is no limit to the number of users in each group.

To use Taobao message service

LB1n7l2LpXXXXXkXFXXXXXXXXXX.png

Subscription data return message

In the application management background , click "Subscribe Message", if the message does not have permission, click "Apply Permission" to enter the application for the corresponding value-added package

LB1l58TLpXXXXXrXVXXXXXXXXXX.png

Code to implement push messages

There are two ways to return messages: Publishing messages through API, Publishing messages through SDK, it is recommended to use API to publish messages.

Publish messages through API

For specific instructions, please refer to the API documentation: taobao.tmc.message.produce

Publish messages through SDK (not recommended)

Currently supports JAVA and .NET languages. For other languages, it is recommended to use API to publish messages.

JAVA code example

TmcClient client = new TmcClient("app_key", "app_secret", "default");
client.connect("ws://mc.api.taobao.com/");
for (int i = 0; i < 10; i++) {
    client.send("helloworld-topic", "{helloworld-content}", "session_key");
}


##C# code example

TmcClient client = new TmcClient("app_key", "app_secret", "default");
client.Connect("ws://mc.api.taobao.com/");
for (int i = 0; i < 10; i++)
{
    client.Send("helloworld-topic", "{helloworld-content}", "session_key");
}

Common message types Note

The platform has provided a structured message description document. Click here to enter the

Message document. You can also enter the message service in the console to subscribe and unsubscribe.

Sandbox message service activation

1. Visit

http://mini.tbsandbox.com/ and log in to the sandbox [You can register your own sandbox account or use the default one For account information, please refer to the "Test Account Creation" introduction at http://www.tbsandbox.com/doc/

2. Select the sandbox testing tool - Message Channel Management

LB1c9abLpXXXXaaXXXXXXXXXXXX.png

Enter the sandbox apppkey subscription message [Sandbox test uses test product inventory modification as an example to subscribe to taobao_item_ItemStockChanged]

LB1t1V5LpXXXXbvXpXXXXXXXXXX.png

3. Sandbox to obtain SessionKey shortcut operation, enter the sandbox AppKey and click search to obtain the SessionKey. As shown in the figure below, the sandbox_c_1 authorization 1021719331 application can obtain its data. The authorization code is the value corresponding to the SessionKey. Then call the taobao.tmc.user.permit interface to authorize 1021719331 to receive its message.

LB1WMRNLpXXXXcXXVXXXXXXXXXX.png

4. Code running (request to ws://mc.api.tbsandbox.com/, use sandbox appkey, secret, sandbox account, refer to the code part above After the official environment) is up, you can go to the sandbox seller center to modify the inventory for testing and verification.

Message service FAQ

What is grouping and whether grouping is needed
Message grouping is a way to isolate user messages. The messages of users in the group will only Sent to connections with the same group name. The same group supports multiple connections, and messages in the same group are randomly sent to a certain connection in the group. If you want to treat messages differently based on user types, such as giving priority to paying users and then free users, you can receive messages from different users through message grouping. Each application can create up to 50 groups, and there is no limit to the number of users in each group.

What is multi-connection message reception and how to establish multiple connections
Multi-connection message reception means that the ISV server in the same group establishes multiple connections with the TOP message server to receive messages. . Multi-link means that for the same group, when a message is delivered, one connection is randomly selected from multiple connections in the group to deliver the message. Multi-links have the function of randomly delivering messages, and multiple connections in the same group can be used to implement clustering and load functions.

Establishing multiple links only requires restarting a TmcClient instance with the same code. Multiple links of the same group can be established on the same ISV server or on different ISV servers.

When to use multiple connections
The server of the message service has a message accumulation function. It depends on the processing capability of your client. As long as it can handle it, it will send it to you. , it accumulates on the server if it cannot be processed. Generally, there is no need to establish multiple connections. A single connection can fill up the machine's network card. The multi-connection of the new messaging service is more commonly used in user grouping or cluster deployment scenarios.

What is the message resending logic?
In the case of disconnection (such as the application hanging), the server will accumulate messages and wait for the application to reconnect. Stacked messages are pushed to the client sequentially. From the time a message is born, if the application does not receive it, the maximum retention time on the server is 3 days. If it exceeds 3 days, it will be automatically cleared. If the connection is normal but the message processing fails, the server will resend the message for the first time every 10 minutes at the earliest. If the application continues to fail to process, the server will resend the message regularly until the message is cleared.

json_decode integer overflow problem in PHP
Below PHP version 5.3, json_decode relies on the number of digits of the operating system to interpret numbers. On 32-bit systems, it only supports a maximum of 2^32 number interpretation. On 64-bit systems, the maximum number supported is 2^64. Since the message ID of the message service exceeds the maximum value of the 32-bit system, if it is not upgraded to PHP version 5.3 or above, the wrong message ID will be confirmed, resulting in repeated message delivery. The solution is: 1. Upgrade PHP to 5.3 or above; 2. Deploy the application to a 64-bit system; 3. Replace the numbers in the JSON message with strings through regular expressions and other means.

Message disconnection and heartbeat test
The client should disconnect the message directly: TmcClient.close(); Heartbeat test whether the connection is normal: TmcClient.isOnline();

The difference between Tmall refund and Taobao refund
Tmall refund only includes orders from Tmall, Taobao refund includes orders from Taobao and Tmall, but Tmall refunds The state is a little richer and has more processes. If it is not used, it is recommended to use Taobao refund message. If necessary, you need to apply for Tmall refund API permission, which can be activated after application.

Will there be a delay in the messaging service?
It takes 10 seconds to activate the messaging service taobao.tmc.user.permit for the user to take effect. There is basically no delay in using messages, and they will be received within 1 second. If there are messages accumulated or the program is not processed in time, there will be a delay. Delay time is related to program processing capabilities. Canceling the message service for the user will take effect within 1 second after taobao.tmc.user.cancel. After cancellation, the accumulated messages will continue to be sent, and new messages will not be sent.

Is it normal for the nick in product message message.getContent() to be empty? How can I tell which store the message belongs to?
In product information, there are cases where the nick is empty. You can use an outer layer to get message.getUserNick() or message.getUserId().

Message service, if the user expires, will he still receive messages?
There are two conditions for judging the push of message service: 1. Whether the user authorization is within the validity period; 2. Whether the user has activated the message service (toabao.tmc.user.permit). Only when both are satisfied at the same time will it be pushed. On the contrary, if the user authorization expires, it will not be pushed. In addition, within one month after the user authorization expires, the user's activation relationship will be saved and will be cleared after one month. If the user reauthorizes within one month, there is no need to re-enable the messaging service for the user.

After obtaining the message, if it is not confirmed, the message service will choose an opportunity to resend it. The number of resends is controlled by the message service. How many times will it be resent so far?
The message service checks for unprocessed messages every ten minutes, and then sends them at an appropriate time. If the message is not confirmed within 3 days, it will be deleted

The message has not been received. How to confirm whether the message service has missed it?
Through daily feedback, there is no message leakage in the message service. Generally, the ISV program does not receive the message or the program processing capability causes the message to be blocked. The troubleshooting message can be confirmed from the following aspects:
* First confirm whether the authorization (SessionKey) is valid;
* Call taobao.tmc.user.get to confirm the current user and activated messages, and pass the return parameters into topics; call TmcClient. isOnline() tests whether the heartbeat is connected normally. If the above troubleshooting fails, you can submit the problem to the support center and attach: AppKey, user nick, message status, approximate message time, order tid, and product num_iid.

Notes on client configuration parameters
.NET SDK: ReconnectIntervalSeconds reconnection time, identifies the time interval for reconnection when TmcClient is disconnected. This value must be >10s. If this value is too small, the link will fail. The reason is that if the server detects a reconnection within 500ms, it will disconnect the new link.

Notes on product inventory changes

  • When modifying the quantity through API (taobao.item.quantity.update, or taobao.item.sku.update) When the item is in stock, the taobao_item_ItemStockChanged message will be generated.
  • When the product quantity is updated through the API (taobao.item.update) or the product inventory is modified through the page, only the product change message (taobao_item_ItemUpdate) will be generated, but the taobao_item_ItemStockChanged message will not be sent. The message only contains the product. Inventory quantity, no change.

In the following operation, the inventory quantity of the product is directly returned:

  • When the product is photographed (photographed to reduce inventory) or payment is made (payment to reduce inventory) (including When creating a transaction via API), the above message is generated.
  • This message will be generated when an order is closed or a sub-order is closed (including closing transactions through API).
  • When the buyer completes the payment and the seller modifies the SKU of the order product through the page, the SKU inventory of the corresponding product will also change and the above message will be generated (the transaction change message taobao_trade_TradeChanged will also be generated at this time).

Refund related message description
No refund related message will be generated when making a refund through the interface taobao.trade.fastrefund (fast refund). There must be a refund related message. Refund related messages will only be generated during the refund process. The fast refund interface (taobao.trade.fastrefund) directly pays the buyer and then closes the transaction. The refund process will not be created, so no refund message will be generated. Currently, only virtual categories support the taobao.trade.fastrrefund interface.

Time, outtime, localtime message related field description

  • time is the message generation time
  • outtime is the current push time of the message
  • localtime is the time of the local machine
  • outtime - time represents the processing on the server side Or the resend delay time
  • localtime - outtime indicates the difference between the local time and the TOP time, or network delay, or the delay in processing after receiving the message

Message service error isp.system-error: unknown errors, isv.tmc-switch-off: appkey, the app do not enable messaging-channel feature
The application does not subscribe to (activate) the messaging service, so it uses TmcClient to receive messages.

FAQ

  • There is no FAQ about this document