I have an application both in Android and iOS platforms. Both of them are registered with Amazon SNS. This is successfully done, because if I have the device tokens, then I can login to my applications dashboard in Amazon, and can send SNS from their console.
I want it make it automated. I mean have my own PHP admin site (and API) for the applications. I want add another page to the admin site, that can request the amazon SNS to send single payload with device identifier, registration keys and message body provided with the request.
First question - Is it possible? I have seen Urban Airship allows it, so it is usual that amazon also does?
Second question - What is the process? Since I am working on this for one of my client and all the docs are not accessible to me. My client is unable to explain it to amazon.
When I have registered my apps to amazon, shouldn't they provide me some keys and secrets that I can use to call their service over http?
Yes, it is possible.
Download the Amazon Web Service (AWS) PHP SDK from here and follow their instructions to use this in you web server API. Get the Platform Application ARN's for both iOS and android, access key id and the secret key from Amazon console. And then try the code below and follow the commented out instructions:
<?php
require '<path to this file>/aws.phar';
use Aws\Sns\SnsClient;
if(isset($_POST['submit']))
{
$push_message = $_POST['push_message'];
if(!empty($push_message))
{
// Create a new Amazon SNS client
$sns = SnsClient::factory(array(
'key' => '<access key>',
'secret' => '<app secret>',
'region' => '<region code>'
));
// region code samples: us-east-1, ap-northeast-1, sa-east-1, ap-southeast-1, ap-southeast-2, us-west-2, us-gov-west-1, us-west-1, cn-north-1, eu-west-1
$iOS_AppArn = "<iOS app's Application ARN>";
$android_AppArn = "<android app's Application ARN>";
// Get the application's endpoints
$iOS_model = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $iOS_AppArn));
$android_model = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $android_AppArn));
// Display all of the endpoints for the iOS application
foreach ($iOS_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
echo $endpointArn;
}
// Display all of the endpoints for the android application
foreach ($android_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
echo $endpointArn;
}
// iOS: Send a message to each endpoint
foreach ($iOS_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
try
{
$sns->publish(array('Message' => $push_message,
'TargetArn' => $endpointArn));
echo "<strong>Success:</strong> ".$endpointArn."<br/>";
}
catch (Exception $e)
{
echo "<strong>Failed:</strong> ".$endpointArn."<br/><strong>Error:</strong> ".$e->getMessage()."<br/>";
}
}
// android: Send a message to each endpoint
foreach ($android_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
try
{
$sns->publish(array('Message' => $push_message,
'TargetArn' => $endpointArn));
echo "<strong>Success:</strong> ".$endpointArn."<br/>";
}
catch (Exception $e)
{
echo "<strong>Failed:</strong> ".$endpointArn."<br/><strong>Error:</strong> ".$e->getMessage()."<br/>";
}
}
}
}
?>
The code is tested and it works, feel free to change as your need.
If you want to send alert sound and badge number with custom payload replace this code block // iOS: Send a message to each endpoint
foreach ($iOS_model['Endpoints'] as $endpoint)
with this code block
foreach ($iOS_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
try
{
$sns->publish(array(
'TargetArn' => $endpointArn,
'MessageStructure' => 'json',
'Message' => json_encode(array(
'default' => $title,
'APNS_SANDBOX' => json_encode(array(
'aps' => array(
'alert' => $title,
'sound' => 'default',
'badge' => 1
),
// Your custom payload if needed
'whatever' => 'here',
'andwhatever' => 'here'
))
))
));
echo "1";//Success push
}
catch (Exception $e)
{
echo "2";//Failed push
}
}
i believe the simplest way to send push notification to single device or user is by this code
$snsClient = Aws\Sns\SnsClient::factory(array(
'credentials' => array(
'key' => AMAZON_KEY,
'secret' => AMAZON_SECRET,
),
'region' => AMAZON_REIGON
));
//you should have variable that have user end single point .
$result = $snsClient->publish(array(
'Message' => "push text message",
'TargetArn' => $user_end_point
));
Related
I have a weird issue with microsoft graph api v1.
I am trying to setup a subscription, so that I get webhook notification after a new outlook email arrives.
$body = [
"changeType" => "created,updated",
"notificationUrl" => route('api.outlook.push'),
"resource" => "me/messages",
"expirationDateTime" => now()->addMinutes(self::SUBSCRIPTION_EXPIRATION_MINUTES),
];
$response = null;
try {
$response = $this->service->createRequest('POST', '/subscriptions')
->attachBody(json_encode($body))
->setReturnType(Subscription::class)
->execute();
} catch (Exception $exception) {
logger()->info('outlook subscription exception', ['message' => $exception->getMessage()]);
}
This seems to be working correctly as microsoft is sending a notification to specified url with verification code, that I'm returning and the message says that subscription was created. The issue is that even though it was set up properly - I am not getting a single one webhook. Did any of you guys had this issue and manage to fix it?
I am developing a website that will have an audio to text page, i am trying to use the API from Google but it seems to load indefinitly and giving me a timeout, on the Google console it show me that request has been made so i guess it come from my rendering (I am developing on Symfony)
Here's my function
public function transcribeAction($audioFile = 'C:\Users\Poste3\Downloads\rec.flac', $languageCode = 'fr-FR', $options = ['sampleRateHertz' => 16000, 'speechContexts' => ['phrases' => ['The Google Cloud Platform', 'Speech API']]])
{
// Create the speech client
$speech = new SpeechClient([
'keyFilePath' => 'C:\Users\Poste3\Downloads\Speech-74da45e82b8e.json',
'languageCode' => $languageCode,
]);
// Make the API call
$results = $speech->recognize(
fopen($audioFile, 'r'),
$options
);
// Print the results
foreach ($results as $result) {
$alternative = $result->alternatives()[0];
printf('Transcript: %s' . PHP_EOL, $alternative['transcript']);
printf('Confidence: %s' . PHP_EOL, $alternative['confidence']);
}
return $this->render('OCPlatformBundle:Advert:speech.html.twig');
}
And here's the call to the function
{{ render(controller('OCPlatformBundle:Advert:transcribe')) }}
First of all you should dump the response you are getting from Speech API.
Possible problems here:
Key is not correctly configured, and has no permissions to make this operation
Your file is more than 1 minute long, in this case google speech requires you to first upload .flac file to Google Cloud and use longrunningrecognize
I am new to FCM in laravel 5.2.
I am following this tutorial click here. But I am not able to send push notification. I have change the server and sender key in config/fcm.php but still it is throwing the error "FCM_SENDER_ID or FCM_SERVER_KEY are invalid".
Here I am using Api key as my server key and project number as sender Id.
try {
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$token = "...";
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
print_r($downstreamResponse);die();
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();
//return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();
//return Array (key : oldToken, value : new token - you must change the token in your database )
$downstreamResponse->tokensToModify();
//return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();
}
catch (\Exception $e) {
return $e->getMessage();
}
And my config/fcm.php
return [
'driver' => env('FCM_PROTOCOL', 'http'),
'log_enabled' => true,
'http' => [
'server_key' => env('FCM_SERVER_KEY', '...'),
'sender_id' => env('FCM_SENDER_ID', '....'),
'server_send_url' => 'https://fcm.googleapis.com/fcm/send',
'server_group_url' => 'https://android.googleapis.com/gcm/notification',
'timeout' => 30.0, // in second
],
];
Any help would be appreciated.
put those two parameters in the bottom of .env file just like that ...
FCM_SERVER_KEY=AAAAAAhDK2...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
and
FCM_SENDER_ID=358248592342
The FCM_SENDER_ID or FCM_SERVER_KEY are invalid is pertaining to a misused credential, in this case is the FCM_SERVER_KEY.
When using FCM, you should only use the Server Key for Authorization, which is seen in your Firebase Console > Project > Project Settings > Cloud Messaging tab.
You are selecting the incorrect FCM_SERVER_KEY
You have to go
Project -> Configuration -> Cloud Messaging -> Legacy Server Key
I'm trying to build a service that let's users create facebook ads with a custom audience based on our database of emails.
Before creating the facebook ad I want to create a preview of the ad. This works just fine when I login in with my own account (admin of facebook app) but fails when logging in as test user.
This is what the user will do:
1. Visit the website of the service.
2. Login using Facebook account with scope: public_profile,email,manage_pages,publish_pages,business_management,ads_management
3. Select facebook page to use
4. Create AdCreative. From this an ad preview can be made. But it fails creating an Adcreative and gives me the following error:
"error":{"message":"Application does not have permission for this action","type":"OAuthException","code":10,"error_subcode":1341012,"is_transient":false,"error_user_title":"No permission to access this profile","error_user_msg":"You don't have required permission to access this profile","fbtrace_id":"EgTeMOXPCUp"}}
The access token as well as ad account belongs to the facebook app. I tried to use the page access token as well but then I don't have permission to access the ad account.
This is code:
function fbadcreative($url, $message, $carasoul, $fbtoken, $pageid){
$calength = count($carasoul);
$children = array();
for($i = 0; $i < $calength; $i++){
$caitem = $carasoul[$i];
$caitem['hash'] = fbaddimage($caitem['picture'], $caitem['id']);
$child = (new AdCreativeLinkDataChildAttachment())->setData(array(
AdCreativeLinkDataChildAttachmentFields::LINK => $caitem['link'],
AdCreativeLinkDataChildAttachmentFields::NAME => $caitem['name'],
AdCreativeLinkDataChildAttachmentFields::DESCRIPTION => $caitem['description'],
AdCreativeLinkDataChildAttachmentFields::IMAGE_HASH => $caitem['hash'],
));
$children[] = $child;
}
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::LINK => $url,
AdCreativeLinkDataFields::CAPTION => $url,
AdCreativeLinkDataFields::MESSAGE => $message,
AdCreativeLinkDataFields::MULTI_SHARE_END_CARD => false,
AdCreativeLinkDataFields::MULTI_SHARE_OPTIMIZED => false,
AdCreativeLinkDataFields::CHILD_ATTACHMENTS => $children,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $pageid,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, 'act_<accountid>');
$creative->setData(array(
AdCreativeFields::NAME => $url,
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
try {
$creative->create();
return $creative->id;
//return $creative->read(array(AdCreativeFields::ID,));
} catch (FacebookAds\Http\Exception\AuthorizationException $e) {
echo 'Message: ' . var_dump($e);
$previousException = $e->getPrevious();
// Do some further processing on $previousException
exit;
}
I know this is an older post, but it might be interesting for others to read how to solve this.
You need to give the user that requests via api the Advertise and analyze permissions on the PAGE the ad creative will be created for.
Example request here using the graph explorer:
page_id/assigned_users?user=system_user_id&tasks=['ADVERTISE', 'ANALYZE']
In my case i am getting this same error due to giving the wrong page Id , i was giving the another page id that was not linked to this ad account.
I'm developing with Laravel a package to post on facebook. My code responsible for obtaining and storing the access token of the page post a link besides test makes this operation correctly with an app that I have created test fb . The problem is to create another app on facebook to put it into production , this second app facebook created it with the same configuration that does work but when publishing gives me the following error: (# 200 ) The user hasn 't Authorized the application to perform this action .
This is the code snippet I use for testing .
public function getTest(){
//$accessToken = new AccessToken($this->getParam('TOKEN'));
try {
$page_post = (new FacebookRequest($this->session, 'POST', '/'.$this->getParam('PAGE_ID').'/feed', array(
'access_token' => $this->getParam('TOKEN'),
'link' => 'link',
'description' => 'Hola mundo desde laravel',
'picture' => 'link/img.png',
'message' => 'Messge',
) ))->execute()->getGraphObject()->asArray();
// return post_id
print_r( $page_post );
} catch(FacebookSDKException $e) {
var_dump($this->getParam('TOKEN'));
echo $e->getMessage();
// var_dump($e);
exit;
}
As for the authorization of the application is correctly even when you enter to view user applications see 2 ( The works and which not) , both with the same permissions accepted.
Fixed , I lacked a permit : ' publish_pages '
$params = array(
'scope' => 'manage_pages','publish_actions','publish_stream','publish_pages'
);