繁体   English   中英

使用参数从 PHP 调用 AWS Lambda

[英]Invoke AWS Lambda from PHP with params

我正在尝试创建一个 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'));

其中“placeHolder”是我的 lambda 函数的正确名称。

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

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

TypeError: Cannot read property '0' of undefined at exports.handler (/var/task/index.js:17:30) 引用新添加的请求行。

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

编辑:我回显了 $result 作为一个整体而不是 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": [
        [

        ]
      ]
    }
  }
}

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

所以,做一个echo json_decode($result->get('Payload')->__toString(), true); 获取包含statusCode和 body 的数组。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM