此篇用來介紹Facebook API發文的三種方式,
分別是JavaScript SDK、PHP SDK以及Java SDK。
首先是JavaScript SDK,
下方程式碼使用FB.api來進行發文動作,
社團以及粉絲頁的動作幾乎一模一樣,
唯一的差別是粉絲頁需使用粉絲頁專用Token,
取得方式請看前一篇取得社團及粉絲頁資訊。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 社團 */ | |
FB.api( | |
"/{page-id}/feed", | |
"POST", | |
{ | |
"message": "This is a test message", | |
}, | |
function (response) { | |
if (response && !response.error) { | |
/* handle the result */ | |
} | |
} | |
); | |
/* 粉絲頁 */ | |
FB.api( | |
"/{page-id}/feed", | |
"POST", | |
{ | |
"message": "This is a test message", | |
"access_token":accessTokenEpire | |
/* accessTokenEpire是粉絲頁專用token */ | |
}, | |
function (response) { | |
if (response && !response.error) { | |
/* handle the result */ | |
} | |
} | |
); |
再來是PHP SDK,
PHP要先載入Facebook專用的SDK,
如需下載請參考第三篇淺談SDK種類及使用時機,
一樣要注意的是 access-token 有分一般級粉絲頁專用的token。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* PHP SDK v5.0.0 */ | |
/* make the API call */ | |
try { | |
// Returns a `Facebook\FacebookResponse` object | |
$response = $fb->post( | |
'/{page-id}/feed', | |
array ( | |
'message' => 'This is a test message', | |
), | |
'{access-token}' | |
); | |
} catch(Facebook\Exceptions\FacebookResponseException $e) { | |
echo 'Graph returned an error: ' . $e->getMessage(); | |
exit; | |
} catch(Facebook\Exceptions\FacebookSDKException $e) { | |
echo 'Facebook SDK returned an error: ' . $e->getMessage(); | |
exit; | |
} | |
$graphNode = $response->getGraphNode(); | |
/* handle the result */ |
最後是Java SDK,
跟PHP一樣要先載入專用的SDK,
我選的是 第三方SDK→Java→Mark Allen 開發的 RestFB。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@page import="com.restfb.types.FacebookType"%> | |
<%@page import="com.restfb.Parameter"%> | |
<%@page import="com.restfb.Version"%> | |
<%@page import="com.restfb.FacebookClient"%> | |
<%@page import="com.restfb.DefaultFacebookClient"%> | |
request.setCharacterEncoding("utf-8"); | |
/* message 是利用使用者輸入表單後送到此檔處理*/ | |
String message = request.getParameter("message"); | |
/* token 的使用需判斷是社團或粉絲頁*/ | |
FacebookClient facebookClient = new DefaultFacebookClient(token,Version.LATEST); | |
FacebookType publishMessageResponse = facebookClient.publish("/"+target_id+"/feed", FacebookType.class, Parameter.with("message", message)); | |
/* target_id為社團或粉絲頁ID */ |
以上是我的一點經驗,
提供給大家參考。
文章標籤
全站熱搜