php - 使用Square Connect API和PHP上传项目图像

52 4

下面是我的代码示例,但它失败了


 $url = 'https://connect.squareup.com/v1/me/items/9999999/image';


 $auth_bearer = 'Authorization: Bearer '. $this->accessToken;


 $image_data = base64_encode(file_get_contents('image.jpeg'));


 $header = array(


 $auth_bearer,


 'Accept: application/json',


 'Content-Type: multipart/form-data; boundary=BOUNDARY',



 );



 $ch = curl_init($url);


 curl_setopt($ch, CURLOPT_POST, true);


 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);


 curl_setopt($ch, CURLOPT_POSTFIELDS, 'files='. $image_data);


 $head = curl_exec($ch);


 curl_close($ch);



 $response = json_decode($head);


 echo"<pre>";


 print_r($response);


 echo"</pre>";



什么都没发生......这里有什么帮助?

谢谢

时间: 原作者:

125 2

你需要将原始图像数据( 非base64编码) 和适当的多部分 header 发布到文件对象中。 下面是一个工作示例( 替换 ACCESS_TOKENITEM_IDIMAGE_FILE ) 。


<?php


function uploadItemImage($url, $access_token, $image_file) {


 $headers = ["Authorization: Bearer $access_token"];



 $ch = curl_init();



 curl_setopt($ch, CURLOPT_URL, $url);


 curl_setopt($ch, CURLOPT_POST, 1);


 curl_setopt($ch, CURLOPT_POSTFIELDS, ['image_data' =>"@$image_file"]);


 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);



 $data = curl_exec($ch);


 $return_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);


 print"POST to $url with status $return_statusn";



 curl_close($ch);



 return $data? json_decode($data) : false;


}



print_r(


 uploadItemImage(


 'https://connect.squareup.com/v1/me/items/ITEM_ID/image',


 'ACCESS_TOKEN',


 'IMAGE_FILE.jpg'


 )


);


?>



原作者:
...