最近、アリババのコミュニケーションアプリ「来往」に関する議論が多くなっていますが、ここではそのビジネス戦略については触れず、主に技術的な観点から「来往」を使用した注文取得システムの開発について説明します。
あるクライアントは私たちの注文管理システムを使用しており、同時にタオバオ外卖でも店舗を運営していました。しかし、タオバオ外卖からの注文を注文管理システムと連携させる必要がありました。そこで、タオバオ外卖のAPIを利用して未確認の注文を取得し、それを注文管理システムに反映させる方法について考察しました。
タオバオ外卖が提供しているAPIは主に以下の3つです:
- 未確認の注文を取得するAPI
- 注文を確認するAPI
- 注文を拒否するAPI
これらのAPIを利用して、タオバオ外卖からの注文を注文管理システムに取り込み、適切な配達員に割り当てるシステムを開発しました。
以下にAPIの使用方法とサンプルコードを示します。
アクセス権限の取得
まず最初に必要なのは、タオバオからのアクセストークン(top_session)の取得です。
string appKey = ConfigurationManager.AppSettings["taobaoAppKey"];
string redirectUrl = $"http://container.open.taobao.com/container?appkey={appKey}&encode=utf-8";
Response.Redirect(redirectUrl);
未確認の注文の取得
次に、取得したtop_sessionを使用して未確認の注文を取得します。
string topSession = Request.QueryString["top_session"] ?? string.Empty;
if (string.IsNullOrEmpty(topSession))
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('未認証のため、注文を取得できません。認証を行ってください。');", true);
return;
}
string shopId = Request.Cookies["taobaoShopId"]?.Value ?? string.Empty;
if (string.IsNullOrEmpty(shopId))
{
Response.Redirect("getSectionKey.aspx");
return;
}
var client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", appKey, appSecret, "json");
var request = new TradeWaimaiGetRequest
{
StoreId = long.Parse(shopId),
IsAll = true,
MaxSize = 20
};
var response = client.Execute(request, topSession);
if (response.Result?.ResultList != null)
{
var orders = response.Result.ResultList.Select(MapToInternalOrder).ToList();
// ここでordersをデータバインディングする
}
注文の確認
最後に、取得した注文をシステムに登録し、タオバオ外卖に確認情報を送信します。
protected void OrderList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "confirm")
{
string orderId = e.CommandArgument.ToString();
if (IsOrderAlreadyRegistered(orderId))
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('この注文は既に登録されています。');", true);
return;
}
var internalOrder = RegisterOrderToSystem(orderId);
if (internalOrder != null)
{
ConfirmOrderToTaobao(orderId);
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('注文を確認しました。');", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('注文の登録に失敗しました。');", true);
}
}
}
private bool IsOrderAlreadyRegistered(string orderId)
{
// 注文が既に登録されているかチェックするロジック
return false;
}
private InternalOrderModel RegisterOrderToSystem(string orderId)
{
// タオバオの注文情報を内部モデルにマッピングし、データベースに登録するロジック
return new InternalOrderModel();
}
private void ConfirmOrderToTaobao(string orderId)
{
var client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", appKey, appSecret, "json");
var request = new TradeWaimaiConfirmRequest
{
OrderId = long.Parse(orderId)
};
client.Execute(request, topSession);
}
以上のように、タオバオ外卖のAPIを利用して注文取得システムを構築することができます。