Does FCM support the new apns-push-type for iOS 13 - firebase-cloud-messaging

We currently have a solution to send the push notification from FCM to APNS and then to iOS. Due to the introduction of iOS13, the APNS now requires apns-push-type in any incoming payload that specifies whether it's an alert notification, background notification, or any other type. I am wondering how to add this information in the message sent to the FCM.
Currently we use pyFCM to send messages to FCM. And we follow this page as reference: https://firebase.google.com/docs/cloud-messaging/http-server-ref
from pyfcm import FCMNotification
push_service = FCMNotification(api_key="XXXX")
registration_id = '<Token>'
data_message = {
"Score": "3*1",
"DeviceId": "XXXXXX",
}
# Background notification
result = push_service.notify_single_device(registration_id=registration_id,
content_available=True,
data_message=data_message)
# Alert notification
result = push_service.notify_single_device(registration_id=registration_id,
message_title='Sample title',
message_body='Sample body',
data_message=data_message,
)
This works fine with existing iOS app. But for iOS 13, I cannot find any place to specify apns-push-type, or any equivalent field that FCM will translate to apns-push-type that would be sent to APNS.
I know iOS 13 is relatively new, so everyone is still working on adapting the existing solution to it. Hopefully someone can give me some insight how to put the apns-push-type into my existing solution. Thanks.

Just add 'apns-push-type' = 'XXX' in the request header which you want to send to FCM

you can add this option using 'extra_kwargs' of the Notification.
Add extra_kwargs={"apns_push_type":"background"} for background notification.
# Background notification
result = push_service.notify_single_device(registration_id=registration_id,
content_available=True,
data_message=data_message,
low_priority=True,
extra_kwargs={"apns_push_type": "background"})
Also, mark the priority of background notification as low. This is done by sending low_priority as true.
For alert notifications, we are required to send the apns push-type as "alert"
# Alert notification
result = push_service.notify_single_device(registration_id=registration_id,
message_title='Sample title',
message_body='Sample body',
data_message=data_message,
extra_kwargs={"apns_push_type": "alert"}
)

you can check if push notifications work json api post request to https://fcm.googleapis.com/fcm/send url.
in configure header
Content-Type : application/json and
Authorization:key=<Your FCm server key>
then in request body add these
{ "to" : "device_token",
"notification" :
{
"title": "message title!",
"body": "MESSAGE BODY",
"token": "XXXXXXXXXX",
"id": 1959,
"sound": "default"
},
"apns": {
"headers": {
"apns-push-type": "alert"
}
}
}
then you can check if it works or not. my project was previously working before updating IOS 13. after update, notifications doesnt worked on background,
adding
"apns": {
"headers": {
"apns-push-type": "alert"
}
}
to project made receive notifications possible

Our solution is to add it to the header upon request (This answer is on PHP code)
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
'apns-push-type: background'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payloads));
$result = json_decode(curl_exec($ch), true); curl_close($ch);

Related

to push notifications using java or python [duplicate]

I'm starting with the new Google service for the notifications, Firebase Cloud Messaging.
Thanks to this code https://github.com/firebase/quickstart-android/tree/master/messaging I was able to send notifications from my Firebase User Console to my Android device.
Is there any API or way to send a notification without use the Firebase console? I mean, for example, a PHP API or something like that, to create notifications from my own server directly.
Firebase Cloud Messaging has a server-side APIs that you can call to send messages. See https://firebase.google.com/docs/cloud-messaging/server.
Sending a message can be as simple as using curl to call a HTTP end-point. See https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"
You can all this REST API from within any environment, but there are dedicated so-called Admin SDKs for many platforms listed here.
This works using CURL
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_KEY_HERE",
'Content-Type: application/json'
);
$ch = curl_init ();
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, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
$message is your message to send to the device
$id is the devices registration token
YOUR_KEY_HERE is your Server API Key (or Legacy Server API Key)
Use a service api.
URL: https://fcm.googleapis.com/fcm/send
Method Type: POST
Headers:
Content-Type: application/json
Authorization: key=your api key
Body/Payload:
{
"notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1"
},
"data": {
"<some_key>": "<some_value>"
},
"to": "<device_token>"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Also check the answer on Firebase onMessageReceived not called when app in background
Examples using curl
Send messages to specific devices
To send messages to specific devices, set the to the registration token for the specific app instance
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send
Send messages to topics
here the topic is : /topics/foo-bar
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send
Send messages to device groups
Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send
Examples using Service API
API URL : https://fcm.googleapis.com/fcm/send
Headers
Content-type: application/json
Authorization:key=<Your Api key>
Request Method : POST
Request Body
Messages to specific devices
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to": "<registration token>"
}
Messages to topics
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!"
}
}
Messages to device groups
{
"to": "<aUniqueKey>",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!"
}
}
As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won't be able to
send notifications to a Firebase User Identifier (UID) and
send notifications to user segments (targeting properties & events like you can on the user console).
Meaning: you'll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it's a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.
Introduction
I compiled most of the answers above and updated the variables based on the FCM HTTP Connection Docs to curate a solution that works with FCM in 2021. Credit to Hamzah Malik for his very insightful answer above.
Prerequisites
First, ensure that you have connected your project with Firebase and that you have set up all dependencies on your app. If you haven't, first head over to the FCM Config docs
If that is done, you will also need to copy your project's server response key from the API. Head over to your Firebase Console, click on the project you're working on and then navigate to;
Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key
Configuring your PHP Backend
I compiled Hamzah's answer with Ankit Adlakha's API call structure and the FCM Docs to come up with the PHP function below:
function sendGCM() {
// FCM API Url
$url = 'https://fcm.googleapis.com/fcm/send';
// Put your Server Response Key here
$apiKey = "YOUR SERVER RESPONSE KEY HERE";
// Compile headers in one variable
$headers = array (
'Authorization:key=' . $apiKey,
'Content-Type:application/json'
);
// Add notification content to a variable for easy reference
$notifData = [
'title' => "Test Title",
'body' => "Test notification body",
'click_action' => "android.intent.action.MAIN"
];
// Create the api body
$apiBody = [
'notification' => $notifData,
'data' => $notifData,
"time_to_live" => "600" // Optional
'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
];
// Initialize curl with the prepared headers and body
$ch = curl_init();
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($apiBody));
// Execute call and save result
$result = curl_exec ( $ch );
// Close curl after call
curl_close ( $ch );
return $result;
}
Customizing your notification push
To submit the notifications via tokens, use 'to' => 'registration token'
What to expect
I set up the function in my website back-end and tested it on Postman. If your configuration was successful, you should expect a response similar to the one below;
{"message":"{"message_id":3061657653031348530}"}
this solution from this link helped me a lot. you can check it out.
The curl.php file with those line of instruction can work.
<?php
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p> </p>";
echo "The Result : ".$result;
Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.
First you need to get a token from android and then you can call this php code and you can even send data for further actions in your app.
<?php
// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];
switch ($action) {
Case "M":
$r=$_GET["r"];
$t=$_GET["t"];
$m=$_GET["m"];
$j=json_decode(notify($r, $t, $m));
$succ=0;
$fail=0;
$succ=$j->{'success'};
$fail=$j->{'failure'};
print "Success: " . $succ . "<br>";
print "Fail : " . $fail . "<br>";
break;
default:
print json_encode ("Error: Function not defined ->" . $action);
}
function notify ($r, $t, $m)
{
// API access key from Google API's Console
if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
$tokenarray = array($r);
// prep the bundle
$msg = array
(
'title' => $t,
'message' => $m,
'MyKey1' => 'MyData1',
'MyKey2' => 'MyData2',
);
$fields = array
(
'registration_ids' => $tokenarray,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
return $result;
}
?>
Works in 2020
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization'=> 'key='. $token,
])->post($url, [
'notification' => [
'body' => $request->summary,
'title' => $request->title,
'image' => 'http://'.request()->getHttpHost().$path,
],
'priority'=> 'high',
'data' => [
'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
'status'=> 'done',
],
'to' => '/topics/all'
]);
Here is the working code in my project using CURL.
<?PHP
//Avoid keys confusions!
//firebase Cloud Messaging have 3 different keys:
//API_KEY, SERVER_KEY and PUSH_KEY ... here we need SERVER_KEY
// SERVER access key from Google firebase Console
define( 'SERVER_ACCESS_KEY', 'YOUR-SERVER-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
// use this to method if want to send to topics
// 'to' => 'topics/all'
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . SERVER_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
You can use for example a PHP script for Google Cloud Messaging (GCM). Firebase, and its console, is just on top of GCM.
I found this one on github:
https://gist.github.com/prime31/5675017
Hint: This PHP script results in a android notification.
Therefore: Read this answer from Koot if you want to receive and show the notification in Android.
Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint.
https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send.
You need to generate and download private key of service account using Firebase console and generate access key using google api client library. Use any http library to post message to above end point, below code shows posting message using OkHTTP. You can find complete server side and client side code at firebase cloud messaging and sending messages to multiple clients using fcm topic example
If a specific client message needs to sent, you need to get firebase registration key of the client, see sending client or device specific messages to FCM server example
String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
String FCM_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("firebase-private-key.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
final MediaType mediaType = MediaType.parse("application/json");
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(FCM_ENDPOINT)
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "Bearer " + token)
.post(RequestBody.create(mediaType, jsonMessage))
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
log.info("Message sent to FCM server");
}
Go to cloud Messaging select: Server key
function sendGCM($message, $deviceToken) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"title" => "Notification title",
"body" => $message,
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_SERVER_KEY",
'Content-Type: application/json'
);
$ch = curl_init ();
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, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ($ch);
}
Or you can use Firebase cloud functions, which is for me the easier way to implement your push notifications.
firebase/functions-samples
If you're using PHP, I recommend using the PHP SDK for Firebase: Firebase Admin SDK. For an easy configuration you can follow these steps:
Get the project credentials json file from Firebase (Initialize the sdk) and include it in your project.
Install the SDK in your project. I use composer:
composer require kreait/firebase-php ^4.35
Try any example from the Cloud Messaging session in the SDK documentation:
use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;
$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();
$message = CloudMessage::withTarget(/* see sections below */)
->withNotification(Notification::create('Title', 'Body'))
->withData(['key' => 'value']);
$messaging->send($message);
If you want to send push notifications from android check out my blog post
Send Push Notifications from 1 android phone to another with out server.
sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send
code snippet using volley:
JSONObject json = new JSONObject();
try {
JSONObject userData=new JSONObject();
userData.put("title","your title");
userData.put("body","your body");
json.put("data",userData);
json.put("to", receiverFirebaseToken);
}
catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("onResponse", "" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorizationey=" + SERVER_API_KEY);
params.put("Content-Typepplication/json");
return params;
}
};
MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I suggest you all to check out my blog post for complete details.
Using Firebase Console you can send message to all users based on application package.But with CURL or PHP API its not possible.
Through API You can send notification to specific device ID or subscribed users to selected topic or subscribed topic users.
Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message

Twitch New API : URL (Helix)

Recently, Twitch bring a new API version using new endpoints etc..
I was working on the V5, but I didn't use Curl command line, I work with URL.
So I decide to look at the references of the new version, trying for example to getting the followers and found this :
https://api.twitch.tv/helix/users/follows?to_id='user ID'
So I replace the user_ID by an id (mine and/or another) and get :
{
"error":"Unauthorized",
"status":401,"message":"Must provide a valid Client-ID or OAuth token"
}
When I was working on the V5, I was putting the client_id and the oauth at the end of the URL like this :
https://api.twitch.tv/kraken/channels/CHANNELNAME?client_id=xXxXxXxXxX&oauth_token=aaaabbbbccc111
And it was working, but in the new API, I already have a parameter so I added the client_id and token after with a & connector... But still have the same error.
I also try to put them before the to_id parameter, but same...
So my question is really stupid but anyone know the URL format on the new API?
You should send your Client-ID in request's header now, not as a param in URL. But there's other problem with SSL/HTTPS in this case if you use curl.
Here is a solution to your problem
DEFINE (TWITCH_API_KEY,'YOUR_KEY_HERE');
$url = 'https://api.twitch.tv/helix/streams/metadata';
$ch = curl_init();
$headers=['Client-ID: '.TWITCH_API_KEY];
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;

Generate Access Token in Bigcommerce

I have an issue when trying to generate Access Token by POST data to https://login.bigcommerce.com/oauth2/token. There is an exception error ('The remote server returned an error: (400) Bad Request.'). I don't know why but I already read the document at https://developer.bigcommerce.com/apps/callback#token
If I open that URL on any web browsers. It said that "The page you were looking for doesn't exist."
Could you please help me this?
Thank you,
Trung
If you are getting a 400 response to your POST request to https://login.bigcommerce.com/oauth2/token then that is indicating a problem with your data. The most likely causes are:
You are not including the following header in your POST request:
Content-Type: application/x-www-form-urlencoded
You are not URL encoding your POST data such as the following example:
client_id=236754&client_secret=m1ng83993rsq3yxg&code=qr6h3thvbvag2ffq&scope=store_v2_orders&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth%26context%3Dstores%2Fg5cd38&context=stores%2Fabc123
Also note that the error response message body that you receive should have some more details about the source of the problem.
If you have confirmed the above points then maybe try giving a sample of your POST data or some information about what you are doing to URL encode your data. Make sure not to include your actual client ID, client secret, or redirect URI.
Try ussing cURL
$data = array( "client_id" => "sdfgdfgdfkxddfgdfgdfdfgdfgddfgdfg2",
"client_secret" => "sdfgsdfgsdfgsdfgsdfgdf",
"redirect_uri" => "https://youapp.com/oauth",
"grant_type" => "authorization_code",
"code" => $_GET["code"], "scope" => $_REQUEST["scope"], "context" => $_GET["context"], );
$postfields = http_build_query($data);
$ch = curl_init();
$url = "https://login.bigcommerce.com/oauth2/token";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);
$obj = json_decode($output);
var_dump($obj);
Firstly you need to get temporary authorization code, but sending GET request to https://login.bigcommerce.com/oauth2/authorize with parameters clientId, Scope, Context ("stores/{your_store_hash}") and redirect_url.
Only after this, you can change your temporary token to permanent token (see previous post).
This permanent token expires in 30-60 days, but I don't know how to renew it automatically without user action. If you know that, please write how.

Import 140k objects to Parse.com

I am trying to populate a Data Class in Parse with 140k objects. Because I have GeoPoints, I can not import via the web interface. The REST API they suggest does not allow you to create multiple objects with one API call. So, it looks like I will be making 140k API calls.
Right now, I have a file with 140k rows of properly formed JSON, waiting to be imported into Parse.
I have tried doing this with curl in PHP on my webserver. I got 5-10k objects imported before the script stops running. I tried adding this to the PHP file-
ignore_user_abort(true);
set_time_limit(0);
But this didn't work. So I thought maybe I'd have more control in Javascript, again 5-10k objects imported before crashing. I added a timeout pause every 50 objects, and it still crashed. I've tried waiting for a success response before making the next API call, or running them all concurrently, and it doesn't make a difference.
Anyways, my question is how to most efficiently make 140k REST API calls, without crashing.
You can import geopoints using Parse's JSON importer (instead of CSV). See Importing Data for details.
Even if you can import complex layouts using the JSON importer, that importer have som issues with large files
You can create multiple objects in one call. Use /1/batch, See example usage below;
{
"requests": [{
"method": "POST",
"path": "/1/classes/YOURCLASS",
"body": {
"your": "parameters",
"live": "here"
}
}, {
"method": "POST",
"path": "/1/classes/YOURCLASS",
"body": {
"second": "request",
"parameters": "here"
}
}]
}
I've successfully imported around 10k rows like this without any problem, I did run it through the terminal however using PHP and cURL, here's the cURL call for reference;
$headers = array(
'X-Parse-Application-Id: APPID',
'X-Parse-REST-API-Key: RESTKEY',
'Content-type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/batch');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
CURLOPT_RETURNTRANSFER is not necessary if you are not interested in if all went well or not, aka "fire and forget".
Good luck!

Pubsubhubbub subscriber problem

Pubsubhubbub hub.verify is sync.
But it says me "Error trying to confirm subscription".
Here's my subscribe code:
<?php
if(isset($_GET["hub_challenge"])) {
exit($_GET["hub_challenge"]);;
}
$feeded = $_POST['feed'];
$ch = curl_init("http://pubsubhubbub.appspot.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,"hub.mode=subscribe&hub.verify=sync&hub.callback=http://rssreaderbg.net/pubsubbub/example/cssexam/index1.php?url=$feeded&hub.topic=$feeded");
curl_exec($ch);
$conn = mysql_connect("localhost","rssreade_rss","siatsowi");
mysql_select_db("rssreade_rss");
?>
and my callback code:
if(isset($_GET["hub_challenge"])) {
file_put_contents("logmeme1.txt",$HTTP_RAW_POST_DATA,FILE_APPEND);
exit($_GET["hub_challenge"]);
}
Where's my error?
From the spec:
The subscriber MUST confirm that the hub.topic and hub.verify_token correspond to a pending subscription or unsubscription that it wishes to carry out. If so, the subscriber MUST respond with an HTTP success (2xx) code with a response body equal to the hub.challenge parameter.
You may need to explicitly specify a 2xx header. This is the working code I use:
if (isset($_GET['hub_challenge'])) {
header('HTTP/1.1 204 "No Content"', true, 204);
echo $_GET['hub_challenge'];
exit;
}