首页 > 解决方案 > 发送数组 UTF8 CURL

问题描述

我正在尝试通过 curl 将此数组发送到 facebook。

我正在尝试向页面用户发送带有按钮的消息:

ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL);
$userPageConversation = 'XXXX';
$Access_token = "XXXXX";    
if (isset($_GET['hub.mode']) && isset($_GET['hub.challenge']) && isset($_GET['hub.verify_token'])) {
    if ($_GET['hub.verify_token'] == 'gyt45h153581tg1hry94165151sd5v151s')
        echo $_GET['hub.challenge'];
} else {
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;

$ch = curl_init($url);

function utf8_converter($array)
{
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
                $item = utf8_encode($item);
        }
    });
    return $array;
}
$variavel = array(
'message' => array(
'attachment' => array(
'type' => urlencode('template'),
'payload' => array(
    'template_type' => urlencode('button'),
    'text' => urlencode('Try the postback button!'),
    'buttons' => [array(
        'type' => urlencode('postback'),
        'title' => urlencode('Postback Button'),
        'payload' => urlencode('START')
    )]
))));
$fields_string = http_build_query(utf8_converter($variavel));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array(
    'Content-type: application/json',
    'charset: utf-8',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields_string));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_exec($ch);
if($errno = curl_errno($ch)){
    $error_message = curl_strerror($errno);
    $erro =  "cURL error ({$errno}):\n {$error_message}";
    $exemplo = fopen('text.txt','w');
    fwrite($exemplo,$erro);
    fclose($exemplo);
}
curl_close($ch);
http_response_code(200);
}

但我收到了这个错误:

{"error":{"message":"(#100) Param body 必须是 UTF-8 编码的字符串","type":"OAuthException","code":100,"fbtrace_id":"HRFiDIbCLRs"}}

谁能帮我?

标签: phparrayscurl

解决方案


尝试更换

$headers = array(
    'Content-type: application/json',
    'charset: utf-8',
);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$headers = array(
    'Content-Type: application/x-www-form-urlencoded',
    'charset=utf-8',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

推荐阅读