前几日的PHP方法有点小问题。现在针对Post JSON Data这种方式做了一些整合。
无论是Post还是Get,在做Base String的时候是没有区别的。如果确实要说区别,就在于POST的时候,Parameter是NULL。所以做成oauth_signature的时候,规则也是一致的。
区别的地方在于用Curl向外发送Request的时候,Curl的curl_setopt的参数是有区别。显然,Post的时候,要打开Post,而且吧PostData传给CURLOPT_POSTFIELDS。我这边特殊的是要传送JSON数据。习惯上是先做好数组形式的Post Data,然后再用PHP json_encode方法,转换成标准的JSON格式。调用公函最后做成如下
[sourcecode language=’php’]
reqOrg = OAuthRequest::from_request(NULL, NULL, NULL);
$this->debugFlg = $debugFlg;
if($mode == ‘Trusted’) {
$this->xoauth_requestor_id = ‘1111111111’;
}else {
$this->xoauth_requestor_id = $this->reqOrg->get_parameter(‘opensocial_viewer_id’);
}
}
public function makeHeaders($url,$method) {
$consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
$token = new OAuthToken(
$this->reqOrg->get_parameter(‘oauth_token’),
$this->reqOrg->get_parameter(‘oauth_token_secret’));
parse_str(parse_url($url, PHP_URL_QUERY), $params);
$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $params);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer, $token,$this->xoauth_requestor_id);
$auth_header = $request->to_header(“”,$this->xoauth_requestor_id);
$headers = array(“Content-Type: application/json; charset=utf-8”,$auth_header);
return $headers;
}
public function fetchAPI($url,$method,$headers,$fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if($this->debugFlg) {
curl_setopt($ch, CURLOPT_HEADER, true);
}else {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
}
if($method == ‘POST’) {
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
}
$ch_data=curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($status < 400) {
return $ch_data;
}else {
return null;
}
}
public function callAPI($url,$method,$fields=null) {
$headers = $this->makeHeaders($url,$method);
$res = $this->fetchAPI($url,$method,$headers,$fields);
return $res;
}
}
?>
[/sourcecode]