2

當我使用GCM進行推送通知時,出現錯誤,返回值爲:field「data」必須是JSON數組。 當用戶創建新帖子時,通知將發送到所有註冊的設備。任何人都有如何解決它的想法?謝謝。GCM推送通知返回錯誤:字段數據必須是json數組

function Notification($post) { 
    global $wpdb; 
    $pub_post = get_post($post_ID); 
    $post_title=$pub_post->post_title; 
    $totalrecord = $this->get_allrecord(); 

    $message = "Your New post, " .$post_title." has been published"; 
     if (count($totalrecord) > 0) { 
     //$display_row = null; 
     foreach ($totalrecord as $row) { 
     $a = $row->token; 
     $this->sendPushNotification($a, $message); 

      } 
     } 
    } 

function get_allrecord(){ 
    global $wpdb; 
    $results =$wpdb->get_results('SELECT token FROM wp_push_tokens ', OBJECT); 
    return $results; 
    } 

function sendPushNotification($registration_ids, $message) { 
    $apiKey = "xxxxxxxxxxxxxxxxxxxxxxx"; 
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey); 
    $fields = array(
     'register' =>$registration_ids, 
     'data' =>$message ); 

    $ch = curl_init(); 
// Set the url, number of POST vars, POST data 

curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send"); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
// Disabling SSL Certificate support temporarly 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_POSTFIELDS, wp_json_encode($fields)); 
// Execute post 
$result = curl_exec($ch); 
    if($result === false) 
     die('Curl failed ' . curl_error()); 
// Close connection 
curl_close($ch); 
return $result; 

}

回答

1

你的內容類型是"application/json",這意味着"data"場的形式必須是一個JSON:

"data": { 
    "message": "your message" 
} 

注意,在這個例子中"message"關鍵是定製的。您可以使用您希望的任何鍵,並且您的應用在收到該消息時必須搜索這些鍵。

我不知道PHP,但這樣的事情可能工作:

$fields = array(
    'registration_ids' =>$registration_ids, 
    'data' => array('message' => $message));