针对Linnworks的AJAX请求

时间:2017-09-13 09:20:50

标签: javascript php json ajax laravel

我正在使用Laravel为Linnworks API创建应用程序。我在PHP中创建了自己的AJAX请求,从javascript接收数据。

这是一项工作要求。

Linnworks示例

inventoryItemId=28c6226d-08de-4eb5-9bf1-f6089972cf18&fieldName=0&fieldValue=sample string 1&locationId=e10f6f45-d4ad-4128-8b58-6ff84b23199a

Javascript请求PHP

var itemArray = 
{
    "inventoryItemId": "39692932-f8b0-42d7-9419-0500d6d79769",
    "fieldName": "StockLevel",
    "fieldValue": 6,
    "locationId": "00000000-0000-0000-0000-000000000000"
};

var itemArrayStr = JSON.stringify(itemArray);

AjaxRequestNew({'dataArray': itemArrayStr, 'linnworksURL': 'Inventory/UpdateInventoryItemLevels'});

function AjaxRequestNew(ajaxData) {
$.ajax({
    headers: {'X-CSRF-TOKEN': mytoken},
    url: '/api-linnworks-request',
    method: 'post',
    data: ajaxData,
    async: false,
    complete: function (data) {
        resp = data.responseText;
    }
});
}

PHP AJAX请求

public function apiLinnworksRequest(Request $request){
$url ='https://eu1.linnworks.net//api/'.$request->linnworksURL;
$data = json_decode($request->dataArray);

$myvar = WebController::linnworksRequestNew($url, $data , $request);
}

public function linnworksRequestNew($url, $data , $request) {
$client = new Client();
// dd($data);

$res = $client->request(
    'POST', $url, [
    'headers' => [
        'Authorization' => $request->session()->get('LinnReturnToken')
    ],
    'form_params' => $data
]);
var_dump($res->getBody()->__toString());
}

这样可以更新项目的库存水平,但我需要同时更新多个项目。我发现Stock / SetStockLevel符合我的要求,但我无法正确格式化请求并继续收到错误。

Linnworks示例

 stockLevels=[
{
    "SKU": "sample string 1",
    "LocationId": "2260b419-69dd-4586-b2b2-08db9591921c",
    "Level": 3
},
{
    "SKU": "sample string 1",
    "LocationId": "2260b419-69dd-4586-b2b2-08db9591921c",
    "Level": 3
}
]

1 个答案:

答案 0 :(得分:2)

感谢Linnworks的帮助和使用Postman,我发现请求需要采用以下格式进行格式化。

PHP

 'stocklevels' => 
     '[ { "SKU": "SUIT-4PC-[philip / paisley]-BLACK-02yrs", ]
     "LocationId": "00000000-0000-0000-0000-000000000000", 
     "Level": 3 }, { "SKU": "SUIT-4PC-[philip / paisley]-BLACK-03yrs", 
     "LocationId": "00000000-0000-0000-0000-000000000000", 
     "Level": 3 } ]'

为了复制这个,我已经按照以下格式从Javascript发送了数据:

JS

var itemArray = 
    [
        {
            "SKU": "SUIT-4PC-[philip / paisley]-BLACK-02yrs",
            "LocationId": "00000000-0000-0000-0000-000000000000",
            "Level": 6
        },
        {
            "SKU": "SUIT-4PC-[philip / paisley]-BLACK-03yrs",
            "LocationId": "00000000-0000-0000-0000-000000000000",
            "Level": 6
        }
    ];

    var itemArrayStr = JSON.stringify(itemArray);
    var dataRequest = {stocklevels: itemArrayStr};