这篇文章介绍消息服务的使用
1. 登陆沙箱用户
用户名:sandbox_c_20
密码:taobao1234
2. 进行消息授权与订阅
点击左边沙箱测试工具,右边消息同道管理,输入appkey,选择消息类型。然后点击订阅即可。
3. 在eclipse里面新建一个类,内容如下,循环接收消息
package tb.lws.test;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.top.link.LinkException;
public class SdkMsgTest {
/**
* @param args
* @throws LinkException
* @throws InterruptedException
*/
public static void main(String[] args) throws LinkException,
InterruptedException {
TmcClient client = new TmcClient("ws://mc.api.tbsandbox.com/",
"1021604294", "sandbox5ac97e191c11cabb19bb16329", "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();// 消息处理失败回滚,服务端需要重发
}
}
});
client.connect();
Thread.sleep(1000000); // 测试使用,为了观察效果
}
}
4. 以另外一个用户登陆
用户名:sandbox_cilai_c
密码:taobao1234
然后点击店铺搜索,搜索sandbox_c_20的店铺,然后点击商品购买
5. 如果订阅了订单创建消息,我们可以看到eclipse会打印出来内容。
PS: 如果收不到消息,通过接口taobao.tmc.user.get获取用户已开通消息,如下代码所示:
String appKey = "1021604294";
String appSecret = "sandbox5ac97e191c11cabb19bb16329";
String serverUrl = "http://gw.api.tbsandbox.com/router/rest";
TaobaoClient client2 = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
TmcUserGetRequest requser = new TmcUserGetRequest();
requser.setFields("user_nick,topics,user_id,is_valid,created,modified");
requser.setNick("sandbox_c_20"); //店铺昵称
TmcUserGetResponse response = client2.execute(requser);
System.out.println(response.getBody());
如果发现没有开通消息,通过如下代码开通消息即可:
TaobaoClient client3 = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
TmcUserPermitRequest req3 = new TmcUserPermitRequest();
req3.setTopics("taobao_trade_TradeSuccess,taobao_trade_TradeCreate,taobao_trade_TradeBuyerPay"); //开通消息列表
TmcUserPermitResponse response3 = client3.execute(req3,
"6100e03980213c6ad26e045d34ebdc6fd3a490aa7ff89052054555330"); //sessionkey
System.out.println(response3.getBody());