【问题标题】:GCM push notification return error: field data must be a json arrayGCM推送通知返回错误:字段数据必须是json数组
【发布时间】:2023-04-11 00:06:01
【问题描述】:

当我使用 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;

}

【问题讨论】:

    标签: php json wordpress push-notification google-cloud-messaging


    【解决方案1】:

    您的内容类型是"application/json",这意味着"data" 字段必须是以下格式的 JSON:

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

    请注意,此示例中的 "message" 键是自定义的。您可以使用任何您希望使用的键,并且您的应用在收到消息时必须搜索这些键。

    我不知道 PHP,但这样的东西可能有用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2014-05-24
      • 2016-12-16
      • 2016-10-24
      • 2015-03-08
      • 2016-07-31
      相关资源
      最近更新 更多