php - 使用 Square Connect API 和 PHP 上传商品图像

标签 php square-connect

我已经查看了 Stackoverflow 上发布的有关此问题的旧问题。 但我没有找到任何 php 集成的示例。

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

    $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>";

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

谢谢

最佳答案

您需要使用文件对象的正确多部分 header 发布原始图像数据(未进行 Base64 编码)。这是一个工作示例(替换 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_status\n";

    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'
    )
);
?>

关于php - 使用 Square Connect API 和 PHP 上传商品图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186920/

相关文章:

ios - 是否可以使用非 HTTPS URL 作为连接到 Square 的 Web 应用程序的 Web 回调 URL?

javascript - Square PoS Android 网页 auto_return

php - WordPress 在打印时获取 woocommerce 缩略图

php - session 劫持在 PHP 中究竟是如何工作的?

php - 当 PHP Gearman 客户端无法连接到服务器时,我得到与无法获取新作业时相同的代码

ios - 如何检测 Square Reader 硬件是否通过蓝牙与 iPad 连接?

javascript - SquareUp 支付 : Can we turn off SSL verification for development server?

javascript - 来自 square-connect 的用于 CC 处理的 iframe 在 angularjs 中不起作用

php - 如何正确存储和查找电话号码的区号

php - 通过 HTML 表中的 while 循环显示数据库中的信息