淘宝API开发系列--商家的绑定

在上篇《淘宝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的部分说明如下:

26Missing Session缺少SessionKey参数
27Invalid Session无效的SessionKey参数

 

 我们先看看具体实现的界面,然后分析其中的实现逻辑吧。

1、首次需要登录的时候,使用一个Winform嵌套一个WebBrowser控件,实现网页登录。 

 

 

 2、商家用户输入账号密码后,确认是否授权程序访问相关资源。

 

 3、确认后生成SessionKey,这个Key正是我们的程序需要的关键内容,因此需要自动获取出来。

 

4、程序拿到该Session Key后,把它作为参数来访问淘宝API获取相关的信息,这里获取交易API的购买信息,需要SessionKey的。

 

 以上就是使用SessionKey的API工作流程界面,我们下面介绍一下相关的实现代码。

1) 主窗体主要的操作代码:

ExpandedBlockStart.gif 代码
     public   partial   class  Form1 : Form
    {
        
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控件,窗体代码如下:

ExpandedBlockStart.gif 代码
     public   partial   class  FrmAuthorized : Form
    {
        
///   <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失效的时候,让商家用户输入账号密码并确认即可,其他使用即可顺利无阻。

是不是有点意思呢,赶快试试吧,说不定带来一些意想不到的收获及创意哦。 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值