原文轉載地址:http://www.cnblogs.com/wuhuacong/archive/2010/03/26/1697005.html
--------------------------------------------------------------
在上篇《淘寶API開發系列--開篇概述》介紹了下淘寶API平臺的一些基本知識,由於一直有事情忙,就沒有及時跟進隨筆的更新,本篇繼續討論淘寶API的開發知識,主要介紹商家的綁定操作。上篇我們說過,淘寶就是基於應用程序鍵來控制用戶的訪問頻率和流量的,另外可以通過應用程序鍵,讓使用者登陸確認,獲取到相關的授權碼,然後獲取SessionKey,作爲訪問使用者淘寶資源(如買入賣出等私人記錄的信息)。
我們再看看SessionKey是如何獲取的(下面是淘寶關於正式環境下SessionKey的說明):
正式環境下獲取SessionKey
注意:web插件平臺應用和web其它應用在正式環境下是同樣的獲取方法
1、WEB應用
例如回調URL爲:http://localhost
訪問 http://container.open.taobao.com/container?appkey={appkey},頁面會跳轉到回調URL,地址類似如下:
http://localhost/?top_appkey={appkey} &top_parameters=xxx&top_session=xxx&top_sign=xxx
回調url上的top_session參數即爲SessionKey
2、客戶端應用
訪問 http://auth.open.taobao.com/?appkey={appkey},即可獲得授權碼
通過http方式訪問 http://container.open.taobao.com/container?authcode={授權碼},會得到類似如下的字符串
top_appkey=1142&top_parameters=xxx&top_session=xxx&top_sign=xxx
字符串裏面的top_session值即爲SessionKey。
由於本篇文章主要是介紹C/S客戶的應用,因此客戶端的應用就不能通過回調Url方式獲得用戶的驗證,我們可以通過在Winform中的WebBrowser控件,顯示一個登陸驗證及訪問確認的操作界面給客戶,當客戶確認的時候並返回Session Key的內容界面的時候,我們取出Session Key保存並關閉瀏覽器窗口即可,今後把該SessionKey作爲參數來訪問相關需要Session Key的API即可。
另外,由於SessionKey的間隔時間比較短,如果API調用間隔時間比較長,那麼SessionKey有可能失效的,但是我們注意到,如果API調用的時候,SesionKey過期 那麼會拋出TopException(其中ErrorCode爲26或者27是SessionKey過期),裏面有關於與TopException的部分說明如下:
26 | Missing Session | 缺少SessionKey參數 |
27 | Invalid Session | 無效的SessionKey參數 |
我們先看看具體實現的界面,然後分析其中的實現邏輯吧。
1、首次需要登錄的時候,使用一個Winform嵌套一個WebBrowser控件,實現網頁登錄。
2、商家用戶輸入賬號密碼後,確認是否授權程序訪問相關資源。
3、確認後生成SessionKey,這個Key正是我們的程序需要的關鍵內容,因此需要自動獲取出來。
4、程序拿到該Session Key後,把它作爲參數來訪問淘寶API獲取相關的信息,這裏獲取交易API的購買信息,需要SessionKey的。
以上就是使用SessionKey的API工作流程界面,我們下面介紹一下相關的實現代碼。
1) 主窗體主要的操作代碼:
{
private TopJsonRestClient jsonClient;
private TopContext context;
private void Form1_Load(object sender, EventArgs e)
{
this.winGridView1.ProgressBar = this.toolStripProgressBar1.ProgressBar;
this.winGridView1.AppendedMenu = this.contextMenuStrip1;
jsonClient = new TopJsonRestClient("http://gw.api.taobao.com/router/rest", "12033411", "你的密鑰");
client = GetProductTopClient("json");
xmlClient = new TopXmlRestClient("http://gw.api.taobao.com/router/rest", "12033411", "你的密鑰"");
}
/// <summary>
/// 判斷是否順利獲取SessionKey
/// </summary>
/// <returns></returns>
private bool GetAuthorizeCode()
{
string authorizeCode = "";
FrmAuthorized dlg = new FrmAuthorized();
if (dlg.ShowDialog() == DialogResult.OK)
{
authorizeCode = dlg.AuthrizeCode;
}
if (string.IsNullOrEmpty(authorizeCode)) return false;
context = SysUtils.GetTopContext(authorizeCode);
if (context == null) return false;
return true;
}
private void BindData()
{
if (context == null)
{
bool flag = GetAuthorizeCode();
if (!flag) return;
}
string sessionKey = context.SessionKey;
////獲取用戶信息
//UserGetRequest request = new UserGetRequest();
//request.Fields = "user_id,nick,sex,created,location,alipay_account,birthday";
//request.Nick = "wuhuacong";
//User user = client.Execute(request, new UserJsonParser());
//MessageBox.Show(ReflectionUtil.GetProperties(user));
try
{
//買入交易
TradesBoughtGetRequest req = new TradesBoughtGetRequest();
req.Fields = "tid,title,price,type,iid,seller_nick,buyer_nick,status,orders";
req.PageNo = 1;
req.PageSize = 10;
ResponseList<Trade> rsp = jsonClient.GetBoughtTrades(req, sessionKey);
this.winGridView1.DataSource = rsp.Content;
MessageBox.Show(rsp.Content.Count.ToString());
//賣出交易
TradesSoldGetRequest soldReq = new TradesSoldGetRequest();
soldReq.Fields = "tid,title,price,type,iid,seller_nick,buyer_nick,status,orders";
soldReq.PageNo = 1;
soldReq.PageSize = 10;
ResponseList<Trade> soldRsp = jsonClient.GetSoldTrades(soldReq, sessionKey);
this.winGridView1.DataSource = soldRsp.Content;
MessageBox.Show(soldRsp.Content.Count.ToString());
}
catch (TopException ex)
{
if (ex.ErrorCode == 26 || ex.ErrorCode == 27)
{
if (MessageUtil.ShowYesNoAndError("SessionKey過期,您是否需要重新認證") == DialogResult.Yes)
{
bool flag = GetAuthorizeCode();
if (!flag) return;
BindData();//重新刷新
}
else
{
return;
}
}
}
}
private void btnTest_Click(object sender, EventArgs e)
{
BindData();
}
2、用戶登陸的窗體,就是一個form窗體加上一個WebBrowser控件,窗體代碼如下:
{
/// <summary>
/// 授權碼
/// </summary>
public string AuthrizeCode = "";
private string url = "http://open.taobao.com/authorize/?appkey=12033411";
public FrmAuthorized()
{
InitializeComponent();
}
/// <summary>
/// 獲取HTML頁面內製定Key的Value內容
/// </summary>
/// <param name="html"></param>
/// <param name="key"></param>
/// <returns></returns>
public string GetHiddenKeyValue(string html, string key)
{
string str = html.Substring(html.IndexOf(key));
str = str.Substring(str.IndexOf("value") + 7);
int eindex1 = str.IndexOf("'");
int eindex2 = str.IndexOf("\"");
int eindex = eindex2;
if (eindex1 >= 0 && eindex1 < eindex2)
{
eindex = eindex1;
}
return str.Substring(0, eindex);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsoluteUri == url)
{
AuthrizeCode = GetHiddenKeyValue(this.webBrowser1.DocumentText, "autoInput");
if (!string.IsNullOrEmpty(AuthrizeCode) && AuthrizeCode.IndexOf("TOP-") >= 0)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
private void FrmAuthorized_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(url);
}
}
這樣我們就可以在首次使用API或者SessionKey失效的時候,讓商家用戶輸入賬號密碼並確認即可,其他使用即可順利無阻。
是不是有點意思呢,趕快試試吧,說不定帶來一些意想不到的收穫及創意哦。