[文章作者:张宴 本文版本:v1.0 最后修改:2012.02.16 转载请注明原文链接:http://blog.zyan.cc/taobaoke_click_urls/]

  根据淘宝商品 num_iid 批量生成淘宝客(什么是淘宝客?)链接的 PHP 文件内容如下。

  淘宝 API 有调用次数限制,一次 API 调用,可以最大返回40个商品的淘宝客链接,因此,在本函数内,如果需要批量生成的淘宝商品 num_iid 数大于40,将按照40个一次,分多次调用。如果调用淘宝 API 查询过的商品 num_iid,不管其是否有淘宝客链接(有些商品没有淘宝客推广链接),都将利用 Memcached 缓存起来,下次直接查缓存,不会重复调用淘宝 API。

<?php
require_once(dirname(__FILE__).'/TopSdk.php'); //引用淘宝开放平台 API SDK

function object2Array($d)
{
        if (is_object($d))
        {
            $d = get_object_vars($d);
        }

        if (is_array($d))
        {
            return array_map(__FUNCTION__, $d);
        }
        else
        {
            return $d;
        }
}


/*********************************************
* 函数名:get_taobaoke_link ($num_iids)
* 函数用途:通过淘宝商品 num_iids 获取其对应的淘宝客手机版链接
* 创建时间:2012-02-14
* 创建人:张宴 net@zyan.cc
* 参数说明:
*    $num_iids   淘宝商品ID(支持多个商品)数组,示例如下:
*          $num_iids[] = "13583512568";
*          $num_iids[] = "10809380078";
*          $num_iids[] = "10809380079";  
* 返回值:
*    下标为淘宝商品 num_iid ,值为淘宝客链接 click_url 的二维数组。如果无淘宝客链接,click_url 为空字符串,示例如下:
*          array(3) {
*            ["13583512568"]=>
*            string(191) "http://auction1.wap.taobao.com/auction/item_detail-0db2-13583512568.jhtml?tks=jUTwPLMDtUUNEZhqfEuTZqkZhGw1LA7%2BzCJBXCj27NpurHxjZN70Amg0DVaFU61pfnHwW%2FI4MZGm%0Awgb69kbb1NL8uwtu%2BDnyAunBCVDP"
*            ["10809380078"]=>
*            string(187) "http://auction1.wap.taobao.com/auction/item_detail-0db2-10809380078.jhtml?tks=jUTwPLMDtUUNEGWhOOgVVuX%2BJKYt7fesyuZjEe7hvmpTJxYDfK8i1Wpvfl7lwI7nzD9W8M352v6E%0AyuUtsKun81AGltKzJWCYPiVDiOeC"
*            ["10809380079"]=>
*            string(0) ""
*          }  
*********************************************/
function get_taobaoke_link ($num_iids) {
  $memcache = new Memcache;
  $memcache->connect('127.0.0.1', 11911); //Memcached 缓存服务器地址
  $click_urls = $memcache->get($num_iids);
  
  foreach ($num_iids AS $num_iid) {
    if (!isset($click_urls[$num_iid])) {
      $tbapi_num_iids_arr[] = $num_iid;
    }
  }
  
  if (!empty($tbapi_num_iids_arr)) {
    $numbers = count($tbapi_num_iids_arr);
    $numbers_max = 40; //淘宝 API 限制最大返回40条记录
    if ($numbers > 0) {
      $numbers_times = ceil($numbers / $numbers_max); //第一层循环的循环次数
      $numbers_start = 0;
      $numbers_end = $numbers_max;
      for ($numbers_i = 1; $numbers_i <= $numbers_times; $numbers_i++) {
        for ($numbers_j = $numbers_start; $numbers_j < $numbers_end; $numbers_j++) {
          if ($numbers_j >= $numbers) {
            break;
          }
          $tbapi_num_iids_arr_sp[] = $tbapi_num_iids_arr[$numbers_j];
        }
        
        $numbers_start = $numbers_start + $numbers_max;
        $numbers_end = $numbers_end + $numbers_max;
        
        $tbapi_num_iids = implode(",", $tbapi_num_iids_arr_sp);
        $c = new TopClient;
        $c->appkey = 12498835; //淘宝开放平台 API 接口 App Key
        $c->secretKey = "745db5f8e316f9f1aa8310a7568d6566"; //淘宝开放平台 API 接口 App Secret
        $c->format = "json";
        $req = new TaobaokeItemsConvertRequest;
        $req->setFields("num_iid,click_url");
        $req->setNumIids($tbapi_num_iids);
        $req->setPid(29509662); //淘宝联盟(阿里妈妈)PID
        $req->setIsMobile("true"); //如果要生成手机页面的淘宝客链接,选择 true;网页版选择 false
        $resp = $c->execute($req);
        $res = object2Array($resp);
  
        if (isset($res["taobaoke_items"]["taobaoke_item"])) {
          $links = $res["taobaoke_items"]["taobaoke_item"];
          foreach ($links as $value) {
            $memcache->set($value["num_iid"], $value["click_url"], MEMCACHE_COMPRESSED, 0);
            $click_urls[(string)$value["num_iid"]] = $value["click_url"];
          }
        }
        
        unset($tbapi_num_iids_arr_sp);
        unset($tbapi_num_iids);
        unset($resp);
        unset($res);
        unset($links);
        unset($value);
      }
    }
  }
  
  foreach ($num_iids AS $num_iid) {
    if (!isset($click_urls[$num_iid])) {
      $memcache->set($num_iid, "", MEMCACHE_COMPRESSED, 0);
      $click_urls[(string)$num_iid] = "";
    }
  }  
  
  $memcache->close();
  return $click_urls;
}

//演示
$num_iids[] = "13583512568";
$num_iids[] = "10809380078";
$num_iids[] = "10809380079";
$click_urls = get_taobaoke_link ($num_iids);
var_dump($click_urls);
?>




  淘宝开放平台(http://open.taobao.com/) PHP SDK 下载:


  申请淘宝 API 的 App Key 和 App Secret ,可以到 http://my.open.taobao.com/ 进行。

  点击在新窗口中浏览此图片




技术大类 » PHP/JS/Shell | 评论(224) | 引用(0) | 阅读(103360)
官方正品旗舰店 Homepage
2012-3-14 22:06
看来我们这代人接触的东西都好像!
gh
2012-3-16 17:25
Ugly Meter (丑脸评分)安卓  http://www.mooyy.com/Ugly%20Meter/
vcn
2012-3-16 17:26
Ugly Meter (丑脸评分)安卓  http://www.mooyy.com/Ugly%20Meter/
chinaphp Homepage
2012-4-4 00:16
也准备做个淘客站,用memcache 做缓存很不错. http://bbs.chinaphp.com
CIManTB Email Homepage
2012-4-7 09:07
哈哈,很实用,收藏了!
wangzhengyi
2012-4-11 10:37
每次您的更新我都会跟着学习,将近一年服务器端的学习,从您的博客里确认获得了不少东西,支持更新!
阳光罐 Homepage
2012-4-20 11:36
向楼主学习了   www.yangguangguan.com
让青春继续 Email Homepage
2012-4-20 20:31
来支持一下,这个教程好,拿来新手练习一下挺好的。限制了请求量,一般用用够了。
Abercrombie Email Homepage
2012-5-9 10:34
Cependant, le plus rapidement, même en dépit Abercrombie du fait que vous vous rendez compte les avantages et comment relaxant c'est encore, malgré le fait que vous tend encore bien au sein de l'intérieur de la sauvegarde et de luxe dans votre maison à tout moment appartenant vers le soir ou le soir manquante de l'acquisition de crapahuter dans les un magasin à un autre essayer de localiser l'inconfort que vous essayez de trouver, vous allez vite être acheter pour le net seulement pour vos spécifications indépendamment de pas un problème c'est peut-être aAbercrombie de sortie que vous essayez de découvrir ou de tout autre type de Abercrombiesortie de vêtements d'achat en plus des vêtements finition unique spéciale robuste.
Hogan Email Homepage
2012-5-10 17:44
Mentre youre gestione di problemi complessi tra cui PAYE insieme con le imprese del prelievo, l'idea è sicuramente intelligente per acquisire specializzata fare qualcosa di sicuro si sta usando la vostra organizzazione. Self-employmentSelf lavoratori uomini e donne potrebbe anche fare pieno uso Hogan dei ragionieri in tutta Stansted, quando hanno l'effetto della loro prelievo unico e sì, è spesso sconcertante. Stare di fronte a una buona varietà prelievo può essere schiacciante, di conseguenza, il
hogan280 Email
2012-5-10 18:00
Nazir Afzal, il pubblico ministero appena nominato capo nazionale per il Nord Ovest, che era responsabile per portare i responsabili in giudizio, ha detto al Guardian: "Non era la loro gara che li ha definiti, è stato il loro trattamento delle Hogan donne". Prima di aggiungere: "Non c'è nessuna comunità in cui le donne e le ragazze non sono vulnerabili agli attacchi sessuali e questo è un dato di fatto."
智林 Homepage
2012-5-12 14:11
关注一下
看看淘宝是怎么赚钱的 Homepage
2012-5-24 10:23
看看淘宝是怎么赚钱的http://www.369in.com
北极鱼 Homepage
2012-6-4 14:48
租用的虚拟主机无法安装memcached,不知道还有没其他办法实现该功能??
衣服的穿配法 Email Homepage
2012-6-8 23:26
做淘宝直接用后台的代码不可以~??~这个很强大,但还用不到。谢谢分享。~
cxf0401
2012-6-11 10:38
Welcome to our sunglasses wholesaleonline sales shop, where you can always buy the most affordable price to a your favorite discount designer sunglasses.discount sunglassesart and technology with a smooth edge of attitude for your active lifestyle. Engineered for those who understand that style is something define for yourself.
vivienne westwood bags Email Homepage
2012-6-11 23:30
<p>your next updates would you to world wide web trunk  <strong>vivienne westwood bags</strong>  world would provide you yourself you the wisest yuletide Vivienne  <strong>Vivienne Westwood Jewellery</strong>  Westwood  <strong>vivienne westwood sale</strong>  Melissa yet suiting your your dream would like yet would like working in your within your budget manner. Vivienne Westwood Melissa would you the wisest trunk wear yet you the your woman with them days.  ,Look more related about <strong>vivienne westwood bags</strong>:http://www.ukviviennewestwoodhandbags.com/ </br></p>
Loore
2012-6-13 19:25
Modern çocuk odası dekorasyonu konusunda yanda örneklerini gördüğünüz çalışmalar dışında istekleriniz doğrultusunda özel tasarım ve imalat da bünyemizde yapılmaktadır. Çocuk odası modelleri biri mutlaka çocuğunuz için.
cheap designer sunglasses
2012-6-29 15:17
If you want a high quality pair of cheap sunglasses, Designer wholesale sunglasses are your best options. You now have the opportunity to select from one of our many wholesale sunglasses.These sunglasses are the highest in quality and fashion.If you are looking for the hottest new sunglass styles please visit our wholesale designer sunglasses web site and let us show you why we are the industries leader!
cheaperoakleysunglasses Email Homepage
2012-6-30 09:32
If you are not a movement, but would like a pair of sunglasses that will capture others attention, discount oakley sunglasses is still option is ideal for you. You like sports style was low-key and vintage look, if I decide to buy oakley sunglasses will give you every option in the Sun. Once you know that Oakley Active Sunglasses protect you from the Sun's glare, you can style and fashion--you decide, it is at the top of Oakley Asian Fit Sunglasses in this market.
分页: 2/12 第一页 上页 1 2 3 4 5 6 7 8 9 10 下页 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]