Using AWS SES API - php

I want to access the AWS SES Webservice to programmatically add new verified Email identities. The API reference does not give the relevant information or at least I can't find it there.
When I try to access the api I get an error due to the missing signature.
https://email.us-east-1.amazonaws.com?AWSAccessKeyId=EXAMPLEKeyId&Action=VerifyEmailIdentity&EmailAddress=someone#somewhere.org&Timestamp=2013-04-27T19:30:00Z&Version=2010-12-01&Signature=
How do I create this signature exactly, for example using php's hash_hmac()?
Do I need to hash the entire parameters using the SES secret key?
Is there a newer version of the SES API than the one documented (2010-12-01)?

You should really go through the documentation (again).
Take a look at the AWS PHP SDK which would help you a lot.
A sample implementation would be something like:
<?php
require 'aws.phar';
use Aws\Common\Enum\Region;
use Aws\Ses\SesClient;
try {
$ses = SesClient::factory(array(
'key' => 'YOUR_KEY',
'secret' => 'YOUR_SECRET',
'region' => Region::US_EAST_1
));
$ses->verifyEmailIdentity( array(
'EmailAddress' => 'the_mail_adress_to_verify#example.com'
));
}
catch( Exception $e )
{
echo $e->getMessage();
}

Related

Creating Client for Amazon Comprehend with AWS for PHP

I recently updated from version 1 of the AWS SDK for PHP to version 3 of the AWS SDK so that I could start testing scripts using the Comprehend and Textract applications. I was able to connect through version 3 and utilize S3 using the "new S3Client()" command. There's extensive documentation regarding functions for Comprehend and Textract, but I can't figure out what the similar new client string is for each service. I've tried:
$cc = new comprehendClient();
$cc = new AWSComprehend();
$cc = new createComprehend();
and more and none of these have worked. If anyone can recommend a fix that would be really helpful. Likewise, if there's an online code repository I should look at that would be helpful. I see plenty of code samples for S3, but none for other applications (at least with SDK for PHP).
Thanks!
From the AWS Comprehend PHP documentation provided, a Comprehend client can be instantiated and called like below :
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\Comprehend\ComprehendClient;
/**
* This code expects that you have AWS credentials set up per:
* https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
*/
$ComprehendClient = \Aws\Comprehend\ComprehendClient::factory(array(
'credentials' => [
'key' => 'AKIAXXXXXX',
'secret' => '+TsIDxxxxxxx',
],
'region' => 'us-east-1',
'version' => 'latest',
));
$result = $ComprehendClient->detectDominantLanguage([
'Text' => "Nakabibili pala ng durian sa U.S. supermarkets kasama ng mga epol. Galing siguro sa Thailand.", // REQUIRED
]);
echo $result;

Get AWS IAM credentials from PHP SDK

I use AWS Services regularly and have my PHP SDK automatically retrieve credentials from my ec2 instance when I connect with Amazon.
I now have a library that I want to use which also requires my AWS secret key and access key to be included when I instantiate the class.
How can I retrieve the current access token and secret key through the AWS PHP SDK so I don't hard code keys into my application?
Where are you storing your AWS Credentials? In a credentials file or IAM Role?
[EDIT after the OP provided specific use case details]
From the link that you provided modify the example to look like this. Note: I have not tested the code, but this will be close:
// Require Composer's autoloader
require_once __DIR__ . "/vendor/autoload.php";
use Aws\Credentials\Credentials
use Aws\Credentials\CredentialProvider;
use Aws\Exception\CredentialsException;
use EddTurtle\DirectUpload\Signature;
// Use the default credential provider
$provider = CredentialProvider::defaultProvider();
$credentials = $provider()->wait();
$upload = new Signature(
$credentials->getAccessKeyId(),
$credentials->getSecretKey(),
"YOUR_S3_BUCKET",
"eu-west-1"
);
[END EDIT]
The simplest answer if you are using a credentials file is to open ~/.aws/credentials in a text editor and extract them. Otherwise follow the details below.
See the bottom for the actual answer on how to extract your access key once you have them loaded.
The following example will create a DynamoDB client using credentials stored in ~/.aws/credentials (normally created by the AWS CLI) from the profile named 'project1':
$client = new DynamoDbClient([
'profile' => 'project1',
'region' => 'us-west-2',
'version' => 'latest'
]);
However, usually you will want the SDK to locate your credentials automatically. The AWS SDK will search for your credentials in the following order (not all cases included):
Environment Variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, etc.)
In the default profile section of ~/.aws/credentials
EC2 IAM Role
Normally just use this example and let the SDK find the credentials for you:
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;
// Use the default credential provider
$provider = CredentialProvider::defaultProvider();
// Pass the provider to the client
$client = new S3Client([
'region' => 'us-west-2',
'version' => '2006-03-01',
'credentials' => $provider
]);
The SDK has a number of credential providers so that you can control exactly where your credentials are coming from.
PHP Class CredentialProvider
One item is that you mention Access Token. This means that you are using STS Assume Role type of access. The PHP SDK supports this also. Just dig into the documentation for STS:
PHP STS Client
Once you have loaded your credentials into a provider you can use the class Credentials to extract the three components (AccessKeyId, AcessKeySecret, SecurityToken):
PHP Class Credentials

How can I verify amazon keys on correctness programmatically?

I'm connecting to Amazon SES via this php-code
$ses = new SesClient([
'credentials' => [
'key' => KEY,
'secret' => SECRET_KEY,
],
'region' => REGION,
'version' => SES_VERSION,
]);
How can I recognize here, whether constants KEY and SECRET_KEY are valid or invalid (such as wrong, inputed with typos and so on) ?
Is there any method in AWS SDK to verify it ?
I use the Python call get_user(). With no arguments, this call will return the user name based on the access key ID. This validates that the credentials are correct. This technique is not bulletproof, but does provide a simple, quick method. You can test this concept with the CLI aws iam get-user.
Python IAM get_user()

Facebook Marketing API PHP SDK - "Filtering field delivery_info is invalid"

I'm attempting to make a PHP-application that generates Facebook ad reports for a company, using the Facebook PHP Ads SDK. I'm following the Marketing API QuickStart that essentially generates code for you. I have all access I need to reach the company's ad account ID.
(I'm not showing the token- and ID-variables, unless absolutely necessary. If so, tell me).
require __DIR__ . '/vendor/autoload.php';
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdsInsights;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
$access_token;
$ad_account_id;
$app_secret;
$app_id;
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array(
'frequency',
'actions:link_click',
'call_to_action_clicks',
'actions:tab_view',
);
$params = array(
'level' => 'adset',
'filtering' => array(array('field' => 'delivery_info','operator' => 'IN','value' => array('inactive','active','limited','archived','permanently_deleted','completed','recently_completed','not_delivering','not_published','rejected','recently_rejected','rejected','pending_review','scheduled'))),
'breakdowns' => array('place_page_id'),
'time_range' => array('since' => '2017-09-20','until' => '2017-10-20'),
);
echo json_encode((new AdAccount($ad_account_id))->getInsights(
$fields,
$params
)->getResponse()->getContent(), JSON_PRETTY_PRINT);
However, when running the code I get the error message:
Fatal error: Uncaught exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'(#100) Filtering field delivery_info is invalid.
I try switching around in $fields and $params with parameters found in the documentation, but it switches the blame on other ones as I do, even claiming that some of them don't even exist as alternatives.
I've checked several times in the documentation, it should work.
Does the problem lie elsewhere, is it the wrong kind of ad account ID?
Any help would be very much appreciated.
Try adset.delivery_info instead of just delivery_info. That should work. I learned the hard way, seems like you need to append the object level separated by period for filtering options.

Can't pass my credentials to AWS PHP SDK

I installed AWS PHP SDK and am trying to use SES. My problem is that it's (apparently) trying to read ~/.aws/credentials no matter what I do. I currently have this code:
$S3_AK = getenv('S3_AK');
$S3_PK = getenv('S3_PK');
$profile = 'default';
$path = '/home/franco/public/site/default.ini';
$provider = CredentialProvider::ini($profile, $path);
$provider = CredentialProvider::memoize($provider);
$client = SesClient::factory(array(
'profile' => 'default',
'region' => 'us-east-1',
'version' => "2010-12-01",
'credentials' => [
'key' => $S3_AK,
'secret' => $S3_PK,
]
));
And am still getting "Cannot read credentials from ~/.aws/credentials" error (after quite a while).
I tried 'credentials' => $provider of course, that was the idea, but as it wasn't working I reverted to hardcoded credentials. I've dumped $S3_AK and $S3_PK and they're fine, I'm actually using them correctly for S3, but there I have Zend's wrapper. I've tried ~/.aws/credentials (no ".ini") to the same result. Both files having 777 permissions.
Curious information: I had to set memory limit to -1 so it would be able to var_dump the exception. The html to the exception is around 200mb.
I'd prefer to use the environment variables, all though the credentials file is fine. I just don't understand why it appears to be trying to read the file even though I've hardcoded the credentials.
EDIT: So a friend showed me this, I removed the profile and also modified the try/catch and noticed the client seems to be created properly, and the error comes from trying to actually send an email.
The trick is just remove 'profile' => 'default' from the factory params, if this is defined we can't use a custom credentials file or environment variables. Is not documented but just works.
I'm using Sns and Sdk v3.
<?php
use Aws\Credentials\CredentialProvider;
$profile = 'sns-reminders';
$path = '../private/credentials';
$provider = CredentialProvider::ini($profile, $path);
$provider = CredentialProvider::memoize($provider);
$sdk = new Aws\Sdk(['credentials' => $provider]);
$sns = $sdk->createSns([
// 'profile' => $profile,
'region' => 'us-east-1',
'version' => 'latest',
]);
This solution will probably only work if you're using version 3 of the SDK. I use something similar to this:
$provider = CredentialsProvider::memoize(CredentialsProvider::ini($profile, $path));
$client = new SesClient([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => $provider]);
I use this for S3Client, DynamoDbClient, and a few other clients, so I am assuming that the SesClient constructor supports the same arguments.
OK, I managed to fix it.
I couldn't read the credentials file but it wasn't exactly my idea.
What was happening was that the actual client was being created successfully, but the try/catch also had the sendEmail included. This was what was failing.
About creating the client with explicit credentials: If you specify region, it will try and read a credentials file.
About the SendEmail, this is the syntax that worked for me, I'd found another one also in the AWS docs site, and that one failed. It must've been for an older SDK.

Categories