Amazon SNS to push topic using PHP - php

I'm trying to understand amazon php sdk for AWS but I really can't use it.
I find some basic classes to create, display and push topic but I doesn't work either.
I just want to find a way (the simplest way) to push a topic from my website.

First and foremost, to get acquainted with Amazon Simple Notification Service (SNS), I recommend to perform all required step manually once via the AWS Management Console as explained in the Getting Started Guide, i.e. Create a Topic, Subscribe to this Topic and Publish a message to it.
Afterwards it should be fairly straight forward to facilitate the sample fragments provided in the documentation of the AWS SDK for PHP running, see e.g. method publish() within class AmazonSNS:
$sns = new AmazonSNS();
// Get topic attributes
$response = $sns->publish(
'arn:aws:sns:us-east-1:9876543210:example-topic',
'This is my very first message to the world!',
array(
'Subject' => 'Hello world!'
)
);
// Success?
var_dump($response->isOK());
For a more complete example you might want to check out the the example provided in Sending Messages Using SNS [...].
If none of this works out, you'll have to provide more details regarding the specific problems you are encountering, as requested by tster already.
Good luck!

As told to you by #SteffenOpel, you should once try to perform all required steps manually once via the AWS Management Console.
Then you may use the AWS SDK for PHP(v3) as below to create the SNS client(or infact any service's client, surely with some changes) and then to create a SNS Topic.
<?php
//assuming that use have downloaded the zip file for php sdk
require 'C:/wamp/www/aws sdk/aws-autoloader.php'; //Change the path according to you
use Aws\Sns\SnsClient;
try{
/*-------------METHOD 1----------------*/
// Create a new Amazon SNS client using AWS v3
//$sns = new Aws\Sns\SnsClient([
$sns = new SnsClient([
'region' => 'us-west-2', //Change according to you
'version' => '2010-03-31', //Change according to you
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
'scheme' => 'http', //disables SSL certification, there was an error on enabling it
]);
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
/*-------------METHOD 2----------------*/
/*
// Create a new Amazon SNS client using AWS v2
$sns = SnsClient::factory(array(
'region' => 'us-west-2',
'version' => '2010-03-31',
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
'scheme' => 'http',
));
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
*/
/*-------------METHOD 3----------------*/
/*
// Create a new Amazon SNS client using AWS SDK class
// Use the us-west-2 region and latest version of each client.
$sharedConfig = [
'region' => 'us-west-2',
'version' => '2010-03-31',
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
//'ssl.certificate_authority' => '/path/to/updated/cacert.pem',
'scheme' => 'http',
];
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);
$sns = $sdk -> createSns();
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
*/
if ($result)
echo "Yes";
else
echo "No";
}
catch(Exception $e){
echo 'Caught Exception: ', $e->getMessage(), "\n";
}
?>
NOTE: This code illustrates creating the client for SNS in three different methods.
You may uncomment and use one according to your need.
Method 1 (version 3) is the best if you're creating a single client, else use Method 3. Method 2 is soon gonna depreciate (as its version 2)

I success to do it by using this classes->
Amazon-SNS-client-for-PHP
Very good, easy to use and working just great.

According to the AWS official docs here, we will have to create a SnsClient and call it's publish method. You can get topic's ARN from AWS console.
$SnSclient = new SnsClient([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2010-03-31'
]);
$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';
try {
$result = $SnSclient->publish([
'Message' => $message,
'TopicArn' => $topic,
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}

Related

Sending SmS using Aws

I am implementing an SMS sending server, for that I am using AWS. I have already used their documentation to carry out all the configuration and installation. I have also placed the files and SDK on the AWS server to run the application. But when running the application, I have no error return, but the SMS does not arrive either.
My code is:
public function SendAwsSms(){
// Passing Aws\Credentials\AssumeRoleCredentialProvider options directly
$profile = new InstanceProfileProvider();
$ARN = "arnkeyprovidedfromaws";
$sessionName = "nameaccessrandom";
$assumeRoleCredentials = new AssumeRoleCredentialProvider([
'client' => new StsClient([
'region' => 'sa-east-1',
'version' => 'latest',
'credentials' => $profile
]),
'assume_role_params' => [
'RoleArn' => $ARN,
'RoleSessionName' => $sessionName,
],
]);
$provider = CredentialProvider::memoize($assumeRoleCredentials);
$SnSclient = new SnsClient([
'region' => 'sa-east-1',
'version'=> 'latest',
]);
try {
$result = $SnSclient->publish([
"SenderID"=>"Idsender",
"SMSType"=>"Promocional",
"Message"=>"Message test",
"PhoneNumber"=>"+1111111111111",
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}
}
When I run the code, no error is displayed, but the SMS does not arrive at the destination.
Can someone show me what's wrong in there? I using PHP, with the CodeIgniter framework, and my system is located in AWS servers.

Credentials must be an instance of Aws\\Credentials\\CredentialsInterface error on PHP SDK with SQS

I am trying to delete a message from SQS in AWS using the php SDK. I have the following configuration.
$sqsClient = new SqsClient([
'version' => '2012-11-05',
'region' => 'us-east-1',
'credentials' => [
'key' => KEY,
'secret' => SECRET
]
]);
Then I am trying to delete like the following :
$sqsClient->deleteMessage([
'QueueUrl' => quque-url
'ReceiptHandle' => handle
]);
I am getting the following error on initialization :
Credentials must be an instance of Aws\\Credentials\\CredentialsInterface, an associative array that contains \"key\", \"secret\", and an optional \"token\" key-value pairs, a credentials provider function, or false."
The credentials I am using is correct. Before I was not passing the config and then also the same error was appearing. How this can be fixed ?
I found this code example and I think your code is correct.
How about create instance of Credentials?
You can use these code for initiating instance.
$credentials = new Aws\Credentials\Credentials(KEY, SECRET);
$sqsClient = new SqsClient([
'version' => '2012-11-05',
'region' => 'us-east-1',
'credentials' => $credentials
]);
Check this document.
And for security reason, I recommend that you'd better use credentials file or set environment variable.
I hope all is well.

AWS IoT receive message

Hello I try receive message from AWS IoT. For publishing I use php-sdk
use Aws\IotDataPlane\IotDataPlaneClient
$connectionParams = [
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret,
]
];
$this->client = new IotDataPlaneClient($connectionParams);
$this->client->publish([
"payload" => $message,
'qos' => 1,
'topic' => $topic,
]);
But I it is no any method for receiving. Anyone knows how connect and receive messages?
You need to subscribe to the MQTT topic. You have a few options.
You can connect the broker with Lambda, to Kinesis, SNS etc. So your receive handler can exist in lambda.
You can write code to subscribe to the MQTT broker yourself and put it in EC2, ECS etc with proper IAM roles/policies. The IoT endpoint in fact is a MQTT broker so thats the only config you will need to receive messages. The endpoint is visible on AWS IoT > Settings > Custom Endpoint
Lambda to receive messages will look something like this where event is an inbound MQTT message
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
const id = event.id;
const chan0 = event.chan0;
}

SNS service does not send SMS V3 API

I tried to use the V2 API to send SMS in the SNS service, and it worked, but it obligated me to create a topic and a subscription with the cellphone number target.
The documentation tells that i am not obligated to create a topic and subscription for the destination cellphone number to send SMS, so i discovered that i must use V3 API to send SMS without TopicARN obligation.
After to use a PHP server with 5.5 version, and V3 API, the TOPIC ARN was not asked, but it took so much time, more than 1 minute, and i got the 503 error as server response, there is no error on log_error.
Could you try to help me?
The code i used and worked on V2 but not V3:
require 'aws-autoloader.php';
use Aws\Sns\SnsClient;
$snsClient = SnsClient::factory(array(
'key' => 'mykey',
'secret' => 'mysecret',
'version' => 'latest',
'region' => 'us-west-2'
));
$destination = array('+number'); // this way works on V2, but not on V3
//$destination = '+number'; // tried like this too
try {
$resp = $snsClient->publish(array(
'PhoneNumber' => $destination,
'Message' => utf8_encode('Message')
));
echo $resp->get('MessageId');
} catch(Exception $e)
{
echo $e->getMessage(); // I didn´t get exception, i got server error 503
}
I found the problem, after the start to use the PHP API V3 i must start like this:
$snsClient = SnsClient::factory(array(
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => array(
'key' => 'mykey',
'secret' => 'mysecret',
)
));
But i still with problems, i receive this message:
Error executing "Publish" on "https://sns.us-west-2.amazonaws.com"; AWS HTTP error: Client error: POST https://sns.us-west-2.amazonaws.com resulted in a 400 Bad Request response: Sender InvalidPara (truncated...) InvalidParameter (client): Invalid parameter: TopicArn or TargetArn Reason: no value for required parameter - Sender InvalidParameter Invalid parameter: TopicArn or TargetArn Reason: no value for required parameter
I didn´t set up the TopicARN or TargetARN because i don´t want to create a subscription for each target number, and the documentation tells me that i can send for a number without register it.
Any help?
When sending SMS you don't need TopicArn. Just do like this:
First install aws/aws-sdk-php. Using composer:
composer require aws/aws-sdk-php
Create a php file with:
require './vendor/autoload.php';
error_reporting(E_ALL);
ini_set("display_errors", 1);
$params = array(
'credentials' => array(
'key' => 'YOUR_KEY_HERE',
'secret' => 'YOUR_SECRET_HERE',
),
'region' => 'us-east-1', // < your aws from SNS Topic region
'version' => 'latest'
);
$sns = new \Aws\Sns\SnsClient($params);
$args = array(
"SenderID" => "SenderName",
"SMSType" => "Transational",
"Message" => "Hello World! Visit www.tiagogouvea.com.br!",
"PhoneNumber" => "FULL_PHONE_NUMBER"
);
$result = $sns->publish($args);
echo "<pre>";
var_dump($result);
echo "</pre>";
The result must have one array with many data, including MessageId.

AWS PHP SDK Signature V4

I'm using the following code to generate my signature for a direct to S3 upload (using sig v4 because the bucket is in Frankfurt):
$s3 = S3Client::factory(array(
'key' => Configure::read('Aws.key'),
'secret' => Configure::read('Aws.secret'),
'region' => Configure::read('Aws.region'),
'signature' => 'v4'
)
);
$postObject = new \Aws\S3\Model\PostObject($s3, Configure::read('Aws.bucket'),
array('acl' => 'public-read'));
$form = $postObject->prepareData()->getFormInputs();
$this->set('policy', $form['policy']);
$this->set('signature', $form['signature']);
However, the end result of a POST is always an XML response containing this message:
The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.
Can anyone see what I might be doing wrong?

Categories