使用params从PHP调用AWS Lambda

时间:2018-03-15 21:48:41

标签: php amazon-s3 aws-lambda

我正在尝试创建一个Lambda函数,该函数将创建一个空白图像,其尺寸从PHP文件传递。由于我是AWS的新手,我开始使用不涉及参数的测试功能,只创建了一个空白的200x300图像:

'use strict';


const http = require('http');
const https = require('https');
const querystring = require('querystring');

const AWS = require('aws-sdk');
const S3 = new AWS.S3({
  signatureVersion: 'v4',
});
const Sharp = require('sharp');

// set the S3 and API GW endpoints
const BUCKET = 'MY_BUCKET_ID';
exports.handler = (event, context, callback) => {
  let request = event.Records[0].cf.request;

  Sharp({
    create: {
      width: 300,
      height: 200,
      channels: 4,
      background: { r: 255, g: 0, b: 0, alpha: 128 }
    }
  })
  .png()
  .toBuffer()
  .then(buffer => {
    // save the resized object to S3 bucket with appropriate object key.
    S3.putObject({
        Body: buffer,
        Bucket: BUCKET,
        ContentType: 'image/png',
        CacheControl: 'max-age=31536000',
        Key: 'test.png',
        StorageClass: 'STANDARD'
    }).promise()
    // even if there is exception in saving the object we send back the generated
    // image back to viewer below
    .catch(() => { console.log("Exception while writing resized image to bucket")});

    // generate a binary response with resized image
    response.status = 200;
    response.body = buffer.toString('base64');
    response.bodyEncoding = 'base64';
    response.headers['content-type'] = [{ key: 'Content-Type', value: 'image/png' }];
    callback(null, response);
  })
  // get the source image file

  .catch( err => {
    console.log("Exception while reading source image :%j",err);
  });
};

我使用Lambda仪表板中的测试功能运行此操作,并看到我的test.png显示在我的S3存储桶中。所以下一步是从PHP调用它。我将这一行添加到我的lambda中,我从另一个教程中获取,以获取请求以解析查询字符串等等:

let request = event.Records[0].cf.request;

然后在我的PHP中我添加了:

require '../vendor/autoload.php';
$bucketName = 'MY_BUCKET_ID';

$IAM_KEY = 'MY_KEY';
$IAM_SECRET = 'MY_SECRET_ID';

use Aws\Lambda\LambdaClient;
$client = LambdaClient::factory(
    array(
        'credentials' => array(
            'key' => $IAM_KEY,
            'secret' => $IAM_SECRET
        ),
        'version' => 'latest',
        'region'  => 'us-east-1'
    )
);
$result = $client->invoke([
  // The name your created Lamda function
  'FunctionName' => 'placeHolder',
]);
echo json_decode((string) $result->get('Payload'));

where" placeHolder"是我的lambda函数的正确名称。

PHP中的echo返回: " 可捕获的致命错误:类stdClass的对象无法转换为字符串"

如果我再次尝试在Lambda上运行测试功能,我会得到:

TypeError:无法读取属性' 0'未定义的     在exports.handler(/var/task/index.js:17:30) 参考新添加的请求行。

所以我的问题是,如何从PHP成功调用此Lambda函数并从PHP请求获取请求到Lambda?

编辑:我回复了整个结果而不是Payload这是结果

{
  "Payload": {

  },
  "StatusCode": 200,
  "FunctionError": "Unhandled",
  "LogResult": "",
  "ExecutedVersion": "$LATEST",
  "@metadata": {
    "statusCode": 200,
    "effectiveUri": "https:\/\/lambda.us-east-1.amazonaws.com\/2015-03-31\/functions\/placeHolder\/invocations",
    "headers": {
      "date": "Thu, 15 Mar 2018 22:01:34 GMT",
      "content-type": "application\/json",
      "content-length": "107",
      "connection": "close",
      "x-amzn-requestid": "6cbc2a0e-289c-11e8-a8a4-d91e9d73438a",
      "x-amz-function-error": "Unhandled",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amzn-trace-id": "root=1-5aaaed3d-d3088eb6e807b2cd712a5383;sampled=0"
    },
    "transferStats": {
      "http": [
        [

        ]
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您需要调用__toString()方法。它对我有用。

因此,执行echo json_decode($result->get('Payload')->__toString(), true);以获取包含statusCode和主体的数组。

还有另一种从GuzzleHttp\Psr7\Stream类型获取数据的方法。像$result['Payload']->getContents()