2017-01-09 64 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做编码为您服务。