2017-01-09 51 views
1

我試圖寫一個基於此指令的PHP腳本:PHP添加反斜槓我curl命令爲Facebook離線轉換

https://developers.facebook.com/ads/blog/post/2016/12/18/lead-ads-offline/

但我在與作爲通過JSON字符串問題一個參數在PHP中捲曲。它看起來像它的加入反斜槓(「match_keys」:「無效的鍵\」電子郵件\」等)。這是導致API調用失敗

我試着玩了:

json_encode($array,JSON_UNESCAPED_SLASHES); 

我已經嘗試了一堆SO答案已經喜歡Curl add backslashes,但沒有運氣

<?php 

$email = hash('sha256', '[email protected]'); 

$data = array("match_keys" => '{"email": $email}', 
       "event_time" =>1477632399, 
       "event_name"=> "Purchase", 
       "currency"=> "USD", 
       "value"=> 2.00); 

$fields = [ 
      // 'upload_tag'=>'2016-10-28-conversions', 
      'access_token'=>'#######', 
      'data'=> $data 
     ]; 


$url = 'https://graph.facebook.com/v2.8/#######/events'; 

echo httpPost($url, $fields); 


function httpPost($url, $fields) 
{ 
    $curl = curl_init($url); 
    curl_setopt($curl, CURLOPT_POST, true); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields)); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    $response = curl_exec($curl); 
    curl_close($curl); 
    return $response; 
} 


?> 

這是響應:

Array{"error":{"message":"(#100) Invalid parameter","type":"OAuthException","code":100,"error_data":{"match_keys":"Invalid keys \"email\" were found in param \"data[match_keys]\".","event_time":"Out of bounds array access: invalid index match_keys","event_name":"Out of bounds array access: invalid index match_keys","currency":"Out of bounds array access: invalid index match_keys","value":"Out of bounds array access: invalid index match_keys"},"fbtrace_id":"BrVDnZPR99A"}}% 

回答

0

您正在將JSON混合到PHP數組中。由於您使用的是http_build_query,我懷疑它實際上是用來發送數據的JSON。試試這個:

$data = array("match_keys" => ["email" => $email], 
    "event_time" =>1477632399, 
    "event_name"=> "Purchase", 
    "currency"=> "USD", 
    "value"=> 2.00 
); 

有了這個,你定義數據作爲一個數組,並留下http_build_query做編碼爲您服務。