Juin
04
|
Avoir un compte eBay, ça peut être bien…
Avoir un nabaztag:tag, ça peut être bien…
Mais si le second peut nous alerter lorsque l’échéance d’une enchère approche, c’est peut-être mieux…
Pour cela, j’ai récupéré des bouts de scripts que j’ai assemblé/modifié dont :
My eBay Watch List
Mon code est largement améliorable… je me suis contenté de copier/coller et d’adapter pour que ça fasse ce que je voulais… n’hésitez pas à l’enrichir
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | <?php // Les phrases du script sont volontairement mal orthographiées pour une meilleure lecture du lapin ;o) // Nabaztag define("API_SN", "xxxxxxxxxxxx"); define("API_TOKEN", "xxxxxxxxxx"); define("PREFIX_VOICE", "FR-"); define("DEFAULT_VOICE", "FR-Anastasie"); define("DEFAULT_SPEED", 30); define("TTLIVE", 120); define("API_URL", "https://api.nabaztag.com/vl/FR/api.jsp?token=".API_TOKEN."&sn=".API_SN."&"); // eBay //these keys can be obtained by registering at https://developer.ebay.com $devID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; $appID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; $certID = '<em>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</em>'; //the token representing the eBay user to assign the call with $userToken = 'xxxxxxxx'; $userID = "<em>YourEbayPseudo</em>"; $alertMinutes = 60; // between 1 & 60. I put 60 because my Webcron just allow me to trigger it each hour //SiteID must also be set in the Request's XML //SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, .... //SiteID Indicates the eBay site to associate the call with $siteID = 71; // France // NORMALLY NOTHING TO UPDATE BELOW THIS PART //set the Server to use (Sandbox or Production) $serverUrl = 'https://api.ebay.com/ws/api.dll'; //the call being made: $verb = 'GetMyeBayBuying'; //Regulates versioning of the XML interface for the API $compatabilityLevel = 433; $ebayError = false; $aEbayErrors = array(); $aEbayWatchList = array(); $aEbayBidList = array(); //function taken directly from the eBay PHP SDK //takes the strucutred XML request and returns the XML response from //eBay API function sendHttpRequest($requestBody, $serverUrl, $headers) { //initialise a CURL session $connection = curl_init(); //set the server we are using (could be Sandbox or Production server) curl_setopt($connection, CURLOPT_URL, $serverUrl); //stop CURL from verifying the peer's certificate curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0); //set the headers using the array of headers curl_setopt($connection, CURLOPT_HTTPHEADER, $headers); //set method as POST curl_setopt($connection, CURLOPT_POST, 1); //set the XML body of the request curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody); //set it to return the transfer as a string from curl_exec curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); //Send the Request $response = curl_exec($connection); //close the connection curl_close($connection); //return the response return $response; } /** buildEbayHeaders Generates an array of string to be used as the headers for the HTTP request to eBay Input: $developerID $applicationID $certificateID $compatLevel $siteID $verb Output: String Array of Headers */ function buildEbayHeaders($developerID, $applicationID, $certificateID, $compatLevel, $siteID, $verb) { $headers = array ( //Regulates versioning of the XML interface for the API "X-EBAY-API-COMPATIBILITY-LEVEL: $compatLevel", //set the keys "X-EBAY-API-DEV-NAME: $developerID", "X-EBAY-API-APP-NAME: $applicationID", "X-EBAY-API-CERT-NAME: $certificateID", //the name of the call we are requesting "X-EBAY-API-CALL-NAME: $verb", //SiteID must also be set in the Request's XML //SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, ....France, site ID 71, abbreviation FR, currency EUR. //SiteID Indicates the eBay site to associate the call with "X-EBAY-API-SITEID: $siteID", ); return $headers; } function getAlert() { global $aEbayWatchList, $aEbayBidList, $alertMinutes; // ex : P6DT1H24M35S P7DT21H57M50S PT7H25M50S PT2H48M51S $result = ""; $watchListExists = false; if(count($aEbayWatchList) > 0) { if(substr($aEbayWatchList[0][2], 0, 2) == "PT") { preg_match_all('|PT(\d{1,2})S|U', $aEbayWatchList[0][2], $deadline); if($deadline[1][0] != 0) { $result = "Alerte ibai : Un objet sous surveillance expire dans quelques secondes !"; $watchListExists = true; } else { preg_match_all('|PT(\d{1,2})M((\d{1,2})S)?|U', $aEbayWatchList[0][2], $deadline); if(($deadline[1][0] != 0) && ($deadline[1][0] < $alertMinutes)) { $result = "Alerte ibai : Un objet sous surveillance expire dans ".$deadline[1][0]." minutes !"; $watchListExists = true; } } } } if(count($aEbayBidList) > 0) { if(substr($aEbayBidList[0][2], 0, 2) == "PT") { preg_match_all('|PT(\d{1,2})S|U', $aEbayBidList[0][2], $deadline); if($deadline[1][0] != 0) { if($watchListExists && ($aEbayBidList[0][2] == $aEbayWatchList[0][2])) $result = "Alerte ibai : Un objet ou vous avez une enchaire se termine dans quelques secondes !"; else $result .= " Alerte ibai : Un objet ou vous avez une enchaire se termine dans quelques secondes !"; } else { preg_match_all('|PT(\d{1,2})M((\d{1,2})S)?|U', $aEbayBidList[0][2], $deadline); if(($deadline[1][0] != 0) && ($deadline[1][0] < $alertMinutes)) { if($watchListExists && ($aEbayBidList[0][2] == $aEbayWatchList[0][2])) $result = "Alerte ibai : Un objet ou vous avez une enchaire se termine dans ".$deadline[1][0]." minutes !"; else $result .= " Alerte ibai : Un objet ou vous avez une enchaire se termine dans ".$deadline[1][0]." minutes !"; } } } } return $result; } function getItems($myList){ $resultArray = array(); foreach($myList as $item){ $itemID = $item->get_elements_by_tagname('ItemID'); $title = $item->get_elements_by_tagname('Title'); $aPrice = $item->get_elements_by_tagname('CurrentPrice'); if(count($aPrice) > 0) $price = sprintf("%01.2f", $aPrice[0]->get_content()); else $price = ""; $aFraisdeport = $item->get_elements_by_tagname('ShippingServiceCost'); if(count($aFraisdeport) > 0) $fraisdeport = sprintf("%01.2f", $aFraisdeport[0]->get_content()); else $fraisdeport = ""; $aTempsRestant = $item->get_elements_by_tagname('TimeLeft'); if(count($aTempsRestant) > 0) $tempsRestant = $aTempsRestant[0]->get_content(); else $tempsRestant = ""; $betterBidderName = ""; $aBetterBidder = $item->get_elements_by_tagname('HighBidder'); if(count($aBetterBidder) > 0) { $aBetterBidderName = $aBetterBidder[0]->get_elements_by_tagname('UserID'); if(count($aBetterBidderName) > 0) $betterBidderName = $aBetterBidderName[0]->get_content(); } // ItemID, Title, TimeLeft, CurrentPrice, ShippingServiceCost, HighBidder $resultArray[] = array($itemID[0]->get_content(), $title[0]->get_content(), $tempsRestant, $price, $fraisdeport, $betterBidderName); } return $resultArray; } function convertRemainingTime($remainingtimecode) { // ex : P6DT1H24M35S P7DT21H57M50S PT7H25M50S PT2H48M51S | 1 jours, 1 heures 55 minutes 5 secondes $result = substr(str_replace(" 1 secondes", " 1 seconde", str_replace(" 1 minutes", " 1 minute", str_replace(" 1 heures", " 1 heure", str_replace(" 1 jours", " 1 jour", str_replace("P", "", str_replace("D", " jours, ", str_replace("T", "", str_replace("H", " heures ", str_replace("M", " minutes ", str_replace("S", " secondes", " ".$remainingtimecode)))))))))), 1); return $result; } //get an array of strings containing the required headers $headers = buildEbayHeaders($devID, $appID, $certID, $compatabilityLevel, $siteID, $verb); ///Build the request Xml string $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>'; $requestXmlBody .= '<GetMyeBayBuyingRequest xmlns="urn:ebay:apis:eBLBaseComponents">'; $requestXmlBody .= "<DetailLevel>ReturnAll</DetailLevel>"; $requestXmlBody .= "<ErrorLanguage>en_US</ErrorLanguage>"; $requestXmlBody .= "<Site>France</Site>"; $requestXmlBody .= "<Pagination><EntriesPerPage>3</EntriesPerPage><PageNumber>1</PageNumber></Pagination>"; $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>"; $requestXmlBody .= "<IncludeWatchCount>true</IncludeWatchCount>"; $requestXmlBody .= '</GetMyeBayBuyingRequest>'; $responseXml = sendHttpRequest($requestXmlBody, $serverUrl, $headers); if(stristr($responseXml, 'HTTP 404') || $responseXml == '') { $ebayError = true; $aEbayErrors[] = "Bad Ebay server response."; } else { //Xml string is parsed and creates a DOM Document object $responseDoc = domxml_open_mem($responseXml); if(!$responseDoc) { // Assign each line to array. $arXML = explode("\n", $xml); foreach ($error as $errorline) { $aEbayErrors[] = $errorline['errormessage']. "Node: ".$errorline['nodename']."\n". "Line: ".$errorline['line']."\n". "Column: ".$errorline['col']."\n"; // Locate actual line number. $arErrorMessage = explode(' line ', $errorline['errormessage']); $arErrorMessage = explode(' ', $arErrorMessage[1]); $errorLineNumber = $arErrorMessage[0]; // Show +/- 10 lines around error. $minErrorLineNumber = max(0, $errorLineNumber-10); $maxErrorLineNumber = min(sizeof($arXML), $errorLineNumber+10); $aEbayErrors[] = "XML snip (linies: ".$minErrorLineNumber." to ".$maxErrorLineNumber."):\n"; for($n = $minErrorLineNumber; $n < $maxErrorLineNumber; $n++) if($n == $errorLineNumber) $aEbayErrors[] = "<B>".htmlentities($arXML[$n])."</B>\n"; else $aEbayErrors[] = htmlentities($arXML[$n])."\n"; } } //get any error nodes $errors = $responseDoc->get_elements_by_tagname('Errors'); //if there are error nodes if(count($errors) > 0){ $ebayError = true; $aEbayErrors[] = '<P><B>eBay returned the following error(s):</B>'; //display each error //Get error code, ShortMesaage and LongMessage $code = $errors[0]->get_elements_by_tagname('ErrorCode'); $shortMsg = $errors[0]->get_elements_by_tagname('ShortMessage'); $longMsg = $errors[0]->get_elements_by_tagname('LongMessage'); //Display code and shortmessage $aEbayErrors[] = '<P>'.$code[0]->get_content().' : '.str_replace(">", "&gt;", str_replace("<", "&lt;", $shortMsg[0]->get_content())); //if there is a long message (ie ErrorLevel=1), display it if(count($longMsg) > 0) $aEbayErrors[] = '<BR>'.str_replace(">", "&gt;", str_replace("<", "&lt;", $longMsg[0]->get_content())); } else { $watchList = $responseDoc->get_elements_by_tagname('WatchList'); if(count($watchList)>0){ $watchItems = $watchList[0]->get_elements_by_tagname('Item'); $aEbayWatchList = getItems($watchItems); } $bidList = $responseDoc->get_elements_by_tagname('BidList'); if(count($bidList)>0){ $bidItems = $bidList[0]->get_elements_by_tagname('Item'); $aEbayBidList = getItems($bidItems); } } } $alert = getAlert(); if($alert != "") { $handle = @fopen(API_URL."voice=".DEFAULT_VOICE."&ttlive=".TTLIVE."&speed=".DEFAULT_SPEED."&tts=".str_replace("\n", "+", str_replace(" ", "+", $alert)), "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); $actionStatus .= $buffer; } fclose($handle); } if(strpos($actionStatus, "<comment>Your text has been sent</comment>") > 0) { print "Alerte envoyée !"; } else { print "L'alerte n'a pas pu être envoyée..."; } } else { print "Rien &agrave; envoyer..."; if((count($aEbayWatchList) > 0) && ((count($aEbayWatchList) == 0) || ((count($aEbayWatchList) > 0) && ($aEbayWatchList[0][2] != $aEbayBidList[0][2])))) { print "<br/>Ech&eacute;ance du prochain objet surveill&eacute; : ".convertRemainingTime($aEbayWatchList[0][2]); } if(count($aEbayBidList) > 0) { print "<br/>Ech&eacute;ance du prochain objet o&ugrave; vous avez ench&eacute;ri : ".convertRemainingTime($aEbayBidList[0][2]); } } ?> |
Concrêtement, cette page se connecte à eBay via son API (il vous faut un compte spécifique que vous pouvez créer ici : https://developer.ebay.com) et récupère les informations associées à l’utilisateur dont on a passé le jeton ($userToken) qui aura été créé à partir du site d’eBay.
Dans les informations récupérées, le programme va simplement prendre, si elles existent, les dates de l’article surveillé et de l’objet sur lequel on a enchéri le plus proche…
Si l’un des deux expire dans moins d’une heure ($alertMinutes), un message est envoyé au lapin.
Après avoir paramétré toutes les informations nécessaires (nabaztag + eBay), vous pouvez exécuter cette page sur un serveur web avec php supportant le module cURL.
Si vous voulez vérifier si le module cURLW est installé, vous pouvez exécuter la ligne suivante dans un script php : print_r(get_loaded_extensions());
Si vous avez d’autres erreurs, il faudra les analyser au cas par cas pour voir de quoi il s’agit exactement…
Si tout fonctionne, vous avez une page qui permet de déclencher votre lapin lorsqu’une enchère arrive à échéance… il ne reste plus qu’à l’exécuter à intervalle régulier.
Personnellement, j’ai programmé un appel de cette page à partir de la page d’administration de mon hébergeur :
Si vous avez une machine qui tourne tout le temps, vous pouvez simplement ouvrir un onglet de votre navigateur pointant sur votre page et programmer un rafraîchissement automatique de celle-ci… si vous avez la flemme, il existe par exemple des extensions qui recharge un onglet dans Firefox…
Derniers commentaires