I have looked through Github but could not find any related class or documentation.
https://github.com/google/google-api-php-client-services/tree/master/src/Google/Service
I am trying to send an FCM message from the server to a web client. Below is how I am currently achieving that.
<?php
header('Content-Type: text/json');
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
)
)
);
$server_key = 'ya29.ElqKBGN2Ri_Uz...HnS_uNreA';
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = 'Authorization:key = '.$firebase_api_key."\r\n".'Content-Type: application/json'."\r\n".'Accept: application/json'."\r\n";
$registration_ids = array('bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...');
$fields = array('registration_ids' => $registration_ids, 'data' => $data);
$content = json_encode($fields);
$context = array('http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $content));
$context = stream_context_create($context);
$response = file_get_contents($url, false, $context);
print($response);
But I am hoping there is a Google Service I can use for the sake of future compatibility. See the example below.
<?php
header('Content-Type: text/json');
require_once __DIR__.'/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
),
'token': 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'
)
);
$fcm = new Google_Service_FirebaseCloudMessaging($client);
$response = $fcm->send($data);
print($response);
First generate a private key file for your service account:
In the Firebase console, open Settings > Service Accounts (https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk).
Click Generate New Private Key, and confirm by clicking Generate Key.
Securely store the JSON file containing the key.
See: https://firebase.google.com/docs/cloud-messaging/migrate-v1
Install the Google Client PHP sources via composer
$ composer require google/apiclient
Now use the API
<?php
require __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/api-project-1234567-firebase-adminsdk-abcdefg.json');
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$http_client = $client->authorize();
$message = [
'message' => [
'token' => 'dG****:****r9jM',
'notification' => [
'body' => 'This is an FCM notification message!',
'title' => 'FCM Message',
],
],
];
$project = 'api-project-1234567';
// Send the Push Notification - use $response to inspect success or errors
$response = $http_client->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
echo (string)$response->getBody() . PHP_EOL;
Of course you have to replace the token with the receiver token, the credentials file with that one you have downloaded in the first step and the project with your project id.
I found the solution here: https://gist.github.com/Repox/64ac4b3582f8ac42a6a1b41667db7440
The FCM Service has been added on 2019-05-17 update
https://github.com/googleapis/google-api-php-client-services/commit/29cd38940096a3e973ad348d69101d1c2f1526d8#diff-dfabf19b00a6fe639dc70ab311952848
Related
Having some problem on the chatbot that I'm currently developing it replies to messages nonstop.
I'm pretty new to this, the code below I just copied the code below to a youtube video the code is working but I'm not able to get why it was sending too many messages
<?php
file_put_contents("fb.txt", file_get_contents("php://input"));
$fb = file_get_contents('fb.txt');
$fb = json_decode($fb);
$sid = $fb->entry[0]->messaging[0]->sender->id;
if($sid == "105140841657941"){
exit();
}
$data = array(
'messaging_type' => 'RESPONSE',
'recipient' => array('id' => "$sid"),
'messsage' => array('text' => "Nice to Meet you")
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode($data),
'header' => "Content-type: application/json\n"
)
);
$context = stream_context_create($options);
$token = "SAMPLE TOKEN";
file_get_contents("https://graph.facebook.com/v10.0/me/messages?access_token=$token", false, $context);
file_put_contents("fb.txt", "");
?>
The following code subscribes to an SNS HTTP Endpoint:
$protocol = 'http';
$endpoint = 'http://test.com/endpoint.php';
$filterPolicyTest = array(
'test' => ['1','2','3']
);
$filterPolicyString = json_encode($filterPolicyTest);
$result = $this->awsClient->subscribe([
'Protocol' => $protocol,
'Endpoint' => $endpoint,
'ReturnSubscriptionArn' => true,
'TopicArn' => 'myTopicARN',
'Attributes' => [
'FilterPolicy' => $filterPolicyString,
],
]);
After confirming the subscription, I can view the subscription in the AWS console and see the Filter policy.
Now I try the same thing but with an email:
$protocol = 'email';
$endpoint = 'myemail#gmail.com';
$filterPolicyTest = array(
'test' => ['1','2','3']
);
$filterPolicyString = json_encode($filterPolicyTest);
$result = $this->awsClient->subscribe([
'Protocol' => $protocol,
'Endpoint' => $endpoint,
'ReturnSubscriptionArn' => true,
'TopicArn' => 'myTopicARN',
'Attributes' => [
'FilterPolicy' => $filterPolicyString,
],
]);
No errors are thrown. I successfully receive a confirmation email and click the link to subscribe. But, in the AWS console for this subscription, I see:
The FilterPolicy attribute is completely ignored.
I am using the PHP SDK version 3. Here is the documentation for this request. I tried submitting a FilterPolicy both as an array and json encoded string with no luck.
I got some example scripts from Facebook App Management to use the Marketing API. When I run the script, I just get this error by curl:
'Unsupported post request. Object with ID \'105101623679981\' does not exist, cannot be loaded due to missing permissions, or does not support this operation.
I already tried to deactivate the Sandbox Mode and go public, tried many different scripts in different languages and also other keys.
Any Ideas?
This is the Script:
<?php
//Add all those Uses and the autoloader
$access_token = '<my_very_long_accessToken';
$ad_account_id = '<my_account_id>'; //<-- This is the Object in the Error Code
$app_secret = '<my_app_secret>';
$page_id = '<my_page_id>';
$app_id = '<my_app_is>';
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array(
);
$params = array(
'objective' => 'PAGE_LIKES',
'status' => 'PAUSED',
'buying_type' => 'AUCTION',
'name' => 'My Campaign',
);
$campaign = (new AdAccount($ad_account_id))->createCampaign(
$fields,
$params
);
$campaign_id = $campaign->id;
echo 'campaign_id: ' . $campaign_id . "\n\n";
$fields = array(
);
$params = array(
'status' => 'PAUSED',
'targeting' => array('geo_locations' => array('countries' => array('US'))),
'daily_budget' => '1000',
'billing_event' => 'IMPRESSIONS',
'bid_amount' => '20',
'campaign_id' => $campaign_id,
'optimization_goal' => 'PAGE_LIKES',
'promoted_object' => array('page_id' => $page_id),
'name' => 'My AdSet',
);
//...
Yeah. I got it. It has to be "act_"
So bad. The Script is really crappy. So many Errors. And it's created by facebook!
I'm using the Azure OCR Service to get the text of an image back (
https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP).
So far everything is up and running, but now I would like to use a local file instead of an already uploaded one.
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}"); // Replace with the body, for example, "{"url": "http://www.example.com/images/image.jpg"}
Unfortunately I don't know how to pass the raw binary as the body of my POST request in PHP.
At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header, then we can send requests that use a stream resource as the body.
Here's my working code using Guzzle for your reference:
<?php
require 'vendor/autoload.php';
$resource = fopen('./Shaki_waterfall.jpg', 'r');
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze', [
'query' => [
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en'
],
'headers' => [
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>'
],
'body' => $resource
]);
echo $res->getBody();
Using HTTP_Request2:
<?php
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze');
$url = $request->getUrl();
$headers = array(
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>',
);
$request->setHeader($headers);
$parameters = array(
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en',
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setBody(fopen('./Shaki_waterfall.jpg', 'r'));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
I am working with mailgun php sdk. But I am getting error (Invalid resource type: array) when I try to update a user from mailing list. My Code is bellow.
$client = new \Http\Adapter\Guzzle6\Client();
$mgClient = new \Mailgun\Mailgun('YOUR_API_KEY', $client);
$listAddress = 'LIST#YOUR_DOMAIN_NAME';
$memberAddress = 'bob#example.com';
# Issue the call to the client.
$result = $mgClient->put("lists/$listAddress/members/$memberAddress", array(
'subscribed' => 'no',
'name' => 'Foo Bar'
));
First, make sure you are using the last version of php-http/guzzle6-adapter, then try the following:
$client = \Http\Adapter\Guzzle6\Client::createWithConfig([
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded'
]
]);
$mgClient = new \Mailgun\Mailgun('YOUR_API_KEY', $client);
$listAddress = 'LIST#YOUR_DOMAIN_NAME';
$memberAddress = 'bob#example.com';
# Issue the call to the client.
$result = $mgClient->put("lists/$listAddress/members/$memberAddress", http_build_query([
'subscribed' => 'no',
'name' => 'Foo Bar'
]));