SQS SendMessage & $_POST Issue - php

If I put $author='Steven King'; it works without issue, however it does not work with a post variable.
To be "clear" if I hard code the the author in the JSON it will in fact post the message to the SQS queue. This is the expected result, however if I pass the string from the Post Variable e.g. $author=$_POST['author], the message is never delivered.
$message = array(
// Associative array of custom 'String' key names
'Author' => array(
'StringValue' =>$author,
'DataType' => 'String'
),
);
Any thoughts or help on this I would be grateful.
<?php
$author =$_POST["author"];
require 'vendor/autoload.php';
use Aws\Common\Aws;
use Aws\Sqs\SqsClient;
use Aws\Exception\AwsException;
// Get the client from the builder by namespace
$client = SqsClient::factory(array(
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2012-11-05'
));
$queueUrl ='https://sqs.us-west-2.amazonaws.com/blahblahblah';
$message = array(
// Associative array of custom 'String' key names
'Author' => array(
'StringValue' =>$author,
'DataType' => 'String'
),
);
var_dump($message);
$result = $client->sendMessage(array(
'QueueUrl' => $queueUrl,
'MessageBody' => 'An awesome message!',
'MessageAttributes' =>$message,
));

So the issue was caused by the credential provider, which is why it worked in the cli e.g. php posts.php and not in the browser. Because in the CLI it has the correct environment and permissions.
Note: However on AWS SDK example does not include the credential provider only a reference to 'profile' => 'default' which would be thought to grab your default credentials, however that is not the case.
Thank you apache logs!
The fix was to set the right permissions on the /.aws/credentials and ensure
that your $HOME path is set correctly.
On to the next piece. Thanks community.

Related

Firebase PHP Adding Map to Array

I'm trying to use the Firebase PHP API to update/append a document field's array with a map
I have the following code in Python that works fine
ref = db.collection(u'jobs').document(jobId)
ref.update({
u'messages': firestore.ArrayUnion([{
u'category': u'0',
u'message': u'TEST',
u'sender': u'TEAM',
}])
})
Though when I try to replicate it in PHP, it doesn't work. I tried a lot of different ways to view the errors, but all I get is 500 INTERNAL SERVER ERROR.
require 'vendor/autoload.php';
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FieldValue;
$firestore = new FirestoreClient([
'projectId' => 'XXX-XX',
'credentials' => 'key.json'
]);
$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->update([
'messages' => FieldValue::arrayUnion([{
'category' : '0',
'message' : 'TEST',
'sender' : 'TEAM',
}])
]);
I looked up samples of Array Union in PHP, adding data with PHP. I've tried a lots of variations of : or => or arrayUnion([]) or arrayUnion({[]}) to no avail.
Any idea what is causing this?
Looks like there's a few things going wrong here.
First, PHP uses arrays for both maps and "normal" arrays. There is no object literal ({}) in PHP. Array values are specified using the => operator, not :.
Second, DocumentReference::update() accepts a list of values you wish to change, with the path and value. So an update call would look like this:
$docRef->update([
['path' => 'foo', 'value' => 'bar']
]);
You can use DocumentReference::set() for the behavior you desire. set() will create a document if it does not exist, where update() will raise an error if the document does not exist. set() will also replace all the existing fields in the document unless you specify merge behavior:
$docRef->set([
'foo' => 'bar'
], ['merge' => true]);
Therefore, your code can be re-written as either of the following:
$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->set([
'messages' => FieldValue::arrayUnion([[
'category' => '0',
'message' => 'TEST',
'sender' => 'TEAM',
]])
], ['merge' => true]);
$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->update([
[
'path' => 'messages', 'value' => FieldValue::arrayUnion([[
'category' => '0',
'message' => 'TEST',
'sender' => 'TEAM',
]])
]
]);
One final thing to note: arrayUnion will not append duplicate values. So if the value you provide (including all keys and values in the nested map) already exists, it will not be appended to the document.
If you haven't already, turn up error reporting in your development environment to receive information about why your code is failing. PHP will inform you about the parse errors your snippet included, and the Firestore client will give you errors which can often be quite useful.
From Firebase Documentation:
$cityRef = $db->collection('cities')->document('DC');
// Atomically add a new region to the "regions" array field.
$cityRef->update([
['path' => 'regions', 'value' => FieldValue::arrayUnion(['greater_virginia'])]
]);
I would assume you would like something like this:
$docRef = $firestore->collection('jobs')->document($jobId);
// Atomically add new values to the "messages" array field.
$docRef->update([
['path' => 'messages', 'value' => FieldValue::arrayUnion([[
'category' : '0',
'message' : 'TEST',
'sender' : 'TEAM',
]])]
]);

API Error 401 - Error connecting to the API

We began seeing these DocuSign exceptions 09/24/2019:
DocuSign \ eSign \ ApiException (401)
[401] Error connecting to the API (https://NA3.docusign.net/restapi/v2/login_information)
None of the code surrounding our DocuSign logic has been touched for almost six months. So I'm at a loss as to why this exception is being thrown.
We're using the following packages (relating to this):
laravel/framework v5.8.35
docusign/esign-client 3.0.1
tucker-eric/docusign-rest-client 1.0.0
tucker-eric/laravel-docusign 0.1.1
I've tried to update the packages with composer thinking they might have made updates to fix something, but it didn't change anything other than throw USER_AUTHENTICATION_FAILED instead of the exceptions' message above.
As I said, no code has been touched, and I have very little experience with the DocuSign API, and making matters worse this was an old developer's code...
I am able to hit the endpoint, and authenticate with our credentials, using Postman and it seems to work fine. So again, I'm not sure how this just started happening.
The code from our controller:
$parcel = request('parcel_id');
$subdivision = $user->subdivision_id;
$subEmail = Subdivision::where('id', $user->subdivision_id)->pluck('email')->first();
$move = Move::create([
'full_name' => request('full_name'),
'email' => request('email'),
'phone_number' => request('phone_number'),
'parcel_id' => $parcel,
'direction' => request('direction'),
'action_date' => request('action_date'),
'user_id' => auth()->id(),
'subdivision_id' => $subdivision
]);
$residentTabs = array(
array(
'tabLabel' => env('MOVE_IN_ADDRESS_FIELD'),
'value' => $move->parcel->MailingAddress
),
array(
'tabLabel' => env('MOVE_IN_DATE_RESIDENT_FIELD'),
'value' => $move->action_date->format('m/d/Y')
),
array(
'tabLabel' => env('MOVE_IN_EMAIL_FIELD'),
'value' => $move->email
),
array(
'tabLabel' => env('MOVE_IN_PRIMARY_PHONE_FIELD'),
'value' => $move->phone_number
),
array(
'tabLabel' => env('MOVE_IN_FULL_NAME_FIELD'),
'value' => $move->full_name
)
);
$pmTabs = array(
array(
'tabLabel' => env('MOVE_IN_PM_ADDRESS_FIELD'),
'value' => $move->parcel->MailingAddress
),
array(
'tabLabel' => env('MOVE_IN_PM_DATE_FIELD'),
'value' => $move->action_date->format('m/d/Y')
),
);
$templateRoles = array(
array(
'email' => $move->email,
'name' => $move->full_name,
'roleName' => 'Resident',
'tabs' => array(
'textTabs' => $residentTabs
)
),
array(
'email' => $subEmail,
'name' => $user->name,
'roleName' => 'Property Manager',
'tabs' => array(
'textTabs' => $pmTabs
)
)
);
$envelopeDefinition = array(
'status' => 'sent',
'templateId' => env("DOCUSIGN_TEMPLATE_ID"),
'templateRoles' => $templateRoles
);
$contract = DocuSign::get('envelopes')->createEnvelope($envelopeDefinition);
The last line is where the exception is thrown, and the function throwing the exceptions is:
vendor/docusign/esign-client/src/ApiClient.php::callApi
We expect it to work as it has, throwing no exceptions and creating the envelope successfully.
However, we have been seeing USER_AUTHENTICATION_FAILED and general 401 exceptions.
Any help is appreciated!
Your token may have expired. Not sure how it was created and what authentication mechanism you are using. You need to check where is the token and the header in the REST API calls that is using it. It may be that was hardcoded, or was there a refresh token used to keep obtaining new tokens and that process broke.
If you're getting an Authentication failure while trying to hit the login_information endpoint, it's likely that your application is using Legacy Header authentication with an invalid password.
I'd recommend the following:
Try to log in to the web console at www.docusign.net, and perform a Password Reset if necessary
Once you are able to log in, update the stored credentials in the application
2FA or forced Single Sign-On will both block Legacy Header auth. If either is in place, they will need to be disabled, or you will need to switch to one of the Account Server auth workflows.

Is it possible to add a subdomain to Route53 using the AWS PHP SDK?

I am working on a project where we will be creating both subdomains as well as domains in Route53. We are hoping that there is a way to do this programmatically. The SDK for PHP documentation seems a little light, but it appears that createHostedZone can be used to create a domain or subdomain record and that changeResourceRecordSets can be used to create the DNS records necessary. Does anyone have examples of how to actually accomplish this?
Yes, this is possible using the changeResourceRecordSets call, as you already indicated. But it is a bit clumsy since you have to structure it like a batch even if you're changing/creating only one record, and even creations are changes. Here is a full example, without a credentials method:
<?php
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\Route53\Route53Client;
use Aws\Common\Credentials\Credentials;
$client = Route53Client::factory(array(
'credentials' => $credentials
));
$result = $client->changeResourceRecordSets(array(
// HostedZoneId is required
'HostedZoneId' => 'Z2ABCD1234EFGH',
// ChangeBatch is required
'ChangeBatch' => array(
'Comment' => 'string',
// Changes is required
'Changes' => array(
array(
// Action is required
'Action' => 'CREATE',
// ResourceRecordSet is required
'ResourceRecordSet' => array(
// Name is required
'Name' => 'myserver.mydomain.com.',
// Type is required
'Type' => 'A',
'TTL' => 600,
'ResourceRecords' => array(
array(
// Value is required
'Value' => '12.34.56.78',
),
),
),
),
),
),
));
The documentation of this method can be found here. You'll want to take very careful note of the required fields as well as the possible values for others. For instance, the name field must be a FQDN ending with a dot (.).
Also worth noting: You get no response back from the API after this call by default, i.e. there is no confirmation or transaction id. (Though it definitely gives errors back if something is wrong.) So that means that if you want your code to be bulletproof, you should write a Guzzle response handler AND you may want to wait a few seconds and then run a check that the new/changed record indeed exists.
Hope this helps!
Yes, I done using changeResourceRecordSets method.
<?php
require 'vendor/autoload.php';
use Aws\Route53\Route53Client;
use Aws\Exception\CredentialsException;
use Aws\Route53\Exception\Route53Exception;
//To build connection
try {
$client = Route53Client::factory(array(
'region' => 'string', //eg . us-east-1
'version' => 'date', // eg. latest or 2013-04-01
'credentials' => [
'key' => 'XXXXXXXXXXXXXXXXXXX', // eg. VSDFAJH6KXE7TXXXXXXXXXX
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXX', //eg. XYZrnl/ejPEKyiME4dff45Pds54dfgr5XXXXXX
]
));
} catch (Exception $e) {
echo $e->getMessage();
}
/* Create sub domain */
try {
$dns = 'yourdomainname.com';
$HostedZoneId = 'XXXXXXXXXXXX'; // eg. A4Z9SD7DRE84I ( like 13 digit )
$name = 'test.yourdomainname.com.'; //eg. subdomain name you want to create
$ip = 'XX.XXXX.XX.XXX'; // aws domain Server ip address
$ttl = 300;
$recordType = 'CNAME';
$ResourceRecordsValue = array('Value' => $ip);
$client->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
"ResourceRecordSet" => [
'Name' => $name,
'Type' => $recordType,
'TTL' => $ttl,
'ResourceRecords' => [
$ResourceRecordsValue
]
]
]
]
],
'HostedZoneId' => $HostedZoneId
]);
}
If you get any error please check into server error.log file. If you get error from SDK library then there is might PHP version not supported.
if you run this code from your local machine then you might get "SignatureDoesNotMatch" error then Make sure run this code into same (AWS)server environment.

Laravel return array value from app/config/package folder

Hi I am using a laravel package https://github.com/greggilbert/recaptcha and I have published the config files where I need to store my public and private keys for my recaptcha. I want to call this elsewhere in my app in an attempt to process this via AJAX . I've tried to call this as
dd(Config::get('packages.greggilbert.recaptcha')['public_key']);
however this returns as null. The array is kept in the following folder:
app/config/packages/greggilbert/recaptcha/config.php
the array is built as so:
<?php
return array(
'public_key' => 'publickey',
'private_key' => 'privatekey',
'template' => '',
'driver' => 'curl',
'options' => array(
'curl_timeout' => 1,
),
'version' => 2,
);
Any ideas how I can retrieve the public_key value??
Retrieving configs from a package works a bit different. You use a so-called namespace:
Config::get('recaptcha::public_key');

Amazon AWS putBucketLogging parameters in PHP

I am writing script that connects to amazon S3 storage. The script is supposed to create 2 buckets:
Bucket is for data
Bucket is for logs
I successfully created both buckets but I can't set up logging. Below is shown code I use for enabling bucket logging
$result = $client->putBucketLogging(array(
'Bucket' => $bucket,
'LoggingEnabled' => array(
'TargetBucket' => $bucket . '-LOG',
'TargetGrants'=>array(
'Grantee'=>array(
'DisplayName'=>'user.name',
'Type'=>'CanonicalUser'
),
),
'TargetPrefix' => 'LOG-',
),
));
In amazon AWS API for PHP version 2 is written that Bucket, LoggingEnabled and Type are mandatory. But the documentation does not say how to exactly implement there parameters.
Could you please help me with structure of config array for putBucketLogging method?
You can also use the service's API documents as a reference, which sometimes contain more details about how to specifically structure some of the data types for requests. The S3 API docs for PUT Bucket Logging have more details about how to specify the grantee.
Also, you should not use capital letters in bucket names (See Rules for Bucket Naming).
After searching in manuals the php array for method putBucketLogging is
$result = $client->putBucketLogging(array(
'Bucket' => $bucket,
'LoggingEnabled' => array(
'TargetBucket' => $bucket . '-log',
'TargetGrants' => array(
'Grant' => array(
'Grantee' => array(
'Type' => 'AmazonCustomerByEmail',
'EmailAddress' => 'email#email.com',
),
'Permission' => 'FULL_CONTROL',
),
),
'TargetPrefix' => 'log-',
),
));
However enabling logging fails with exception that tells me I have to set permissions on log bucket...

Categories