@2010/01/01 新增一篇更完整的教學:Wretch 無名小站 API - 申請、使用完整教學
記得以前寫過模擬瀏覽器的程式,像是模擬使用者登入、發表文章等程式,現在,終於不必再如此偷偷摸摸了!如果無名能夠再提供 XML-RPC 那就更好了!(好像也可以自己寫了?),先來測試一下無名小站 API 吧!參考資料如下:
至於要怎樣才能使用,我覺得比一般還麻煩一點點 :P
- 申請 API 使用權
- 連到網站上,填寫一些資訊即可
- Kind of Application : Web-based
- Application URL : 你家程式想跑的位置
- Application Domain : 這比較麻煩,似乎不能帶 port 資訊
- Access Scopes : 記得要選無名小站 Wretch 的 Read/Write 啦
- 之後就會要確認 Application Domain ,要在網站根目錄擺在特定的檔名供 Yahoo 認證。
- 如果蹦出 Domain Verification Failed 訊息
- There was an internal error while an application is being created. Please try again.
- 如果你沒用網域只有 IP 的話,請先申請個 Domain 吧!例如 http://tw.twbbs.org 可免費申請,一開始我懶的弄,僅用 IP 位置,結果在這邊卡關就不玩了 :P 幾天後我終於去申請網域後再 Try 成功囉
- 下載 PHP Library
- 測試 PHP 程式
- 需要支持 curl 喔 (其實hack也是用這個lib寫的 XD)
- sudo apt-get install php5-curl (Ubuntu安裝法)
- <?php
require("Yahoo.inc");
// Your Consumer Key (API Key) goes here.
define('CONSUMER_KEY', "");
// Your Consumer Secret goes here.
define('CONSUMER_SECRET', "");
// Your application ID goes here.
define('APPID', "");
$session = YahooSession::requireSession(CONSUMER_KEY,CONSUMER_SECRET,APPID);
?>
- 將上述的相對位置弄一弄後,連過去就會將你導去 Yahoo 登入畫面,登入完就回到你的程式了
- 登入者會收到 Yahoo 寄來的信件,其標題類似於"你的 Yahoo! 帳戶現已與 xxx 連結",也可以再解除設定,就像在 facebook 上玩遊戲時的情況一樣,不想用可以再拿掉。
以上都搞定了,那代表可以真的開始寫程式囉!以下是一些小小的讀取範例!程式如下(別忘了加上上述測試Session的程式碼):
<?php
$yahoo_user = $session->getSessionedUser();
// Profile
$url = 'http://wretch.yahooapis.com/v1/profileService/'.$yahoo_user->guid;
//$response = $session->client->get($url);
//print_r($response);
// Albums
$url = 'http://wretch.yahooapis.com/v1/albumService/'.$yahoo_user->guid.'/albums';
//$response = $session->client->get($url);
//print_r($response);
// Blog
$url = 'http://wretch.yahooapis.com/v1/blogService/'.$yahoo_user->guid.'/articles';
$response = $session->client->get($url);
print_r($response);
?>
寫入範例,建立相簿。但很奇怪地建出來都沒照我想要名字或敘述?比較想試的其實是發表文章至無名小站,但測試的結果都是錯誤訊息?改天有空再玩玩吧。經由 GTStudy 提醒,在 POST 的 contentType 設定成 "application/xml" 就可以成功建立相簿囉!我也順道找了一下投影片,裡頭的敘述果真詳細了一點,第 18 頁的確有看到這個關鍵字,十分感謝!
<?php
$yahoo_user = $session->getSessionedUser();
$url = 'http://wretch.yahooapis.com/v1/albumService/'.$yahoo_user->guid.'/albums';
$content = <<<multi_line_end
<?xml version="1.0" encoding="utf-8"?>
<req>
<title>My title</title>
<desc>My desc</desc>
</req>
multi_line_end;
//$content = simplexml_load_string($content);
$request = Array (
'class_id' => 1
);
$url .= '?'.http_build_query( $request );
$contentType = 'application/xml';
$response = $session->client->post( $url , $contentType , $content );
print_r( $response );
?>
雖然無名小站正式提供不錯的 API ,但我覺得能提供如 MetaWeblog API 將會是更好的服務,但也許是綁著 Yahoo 帳號的關係,在管控上已經不能簡單化。更多 API 細節請至 Wretch API 文件 查看。