我正在使用以下代码使用 GCM 将数据发送到我的设备。
// Replace with real client registration IDs
$registrationIDs = array( $regID );
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
这有效,我在我的设备上收到数据,但是一旦我将代码放在功能标签之间:
function sendMessage($regID, $message) {
//CODE above
}
$regID = "XXXXXX";
$message = "Dit is een test.";
sendMessage($regID, $message);
我有以下错误:
未经授权的错误 401