本文介绍如何使用SDK提供的接口执行HTTP触发器(需要身份认证)函数。

背景信息

函数计算服务会根据请求头部的Authorization字段来校验每一个请求是否合法。
说明 设置了HTTP触发器的允许匿名访问的函数不可以校验。

您须使用与函数计算服务端一致的签名算法才能通过验证,未包含签名字段或者签名错误的请求,函数计算服务将会返回HTTP 403错误。具体信息,请参见签名认证

函数计算提供的SDK中有签名认证的方法,具体信息,请参见 SDK列表

Java

  1. 执行以下代码将Maven依赖项添加到pom.xml中。
    ```
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-fc</artifactId>
        <version>1.7.1</version></dependency>
    ```
  2. 代码示例。更多接口入参,请参见SDK源码
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.fc.client.FunctionComputeClient;
    import com.aliyuncs.fc.model.HttpAuthType;
    import com.aliyuncs.fc.model.HttpMethod;
    import com.aliyuncs.fc.request.*;
    import com.aliyuncs.fc.response.*;
    import java.io.IOException;
    import java.security.InvalidKeyException;
    
    public class testJavaSDK {
        private static final String REGION = "cn-hangzhou";
        private static final String SERVICE_NAME = "XXX";
        private static final String FUNCTION_NAME = "XXX";
        public static void main(final String[] args) throws IOException, InvalidKeyException, IllegalStateException {
            String accountId = "XXX";
            String accessKey = "XXX";
            String accessSecretKey = "XXX";
            FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);
            HttpInvokeFunctionRequest request = new HttpInvokeFunctionRequest(SERVICE_NAME,FUNCTION_NAME, HttpAuthType.FUNCTION, HttpMethod.POST, null);
            JSONObject object = new JSONObject();
            object.put("string","string");
            object.put("int","123");
            String payload = object.toJSONString();
            request.setPayload(payload.getBytes());
            request.setHeader("Content-Type", "application/json");
            InvokeFunctionResponse invkResp = fcClient.invokeFunction(request);
            System.out.println(new String(invkResp.getContent()));
        }
    }

Python

  1. 执行以下代码安装依赖。
    pip install aliyun-fc2
  2. 代码示例。更多接口入参,请参见SDK源码
    # -*- coding: utf-8 -*-
    
    import fc2
    client = fc2.Client(
        endpoint='<Your Endpoint>',
        accessKeyID='<Your AccessKeyID>',
        accessKeySecret='<Your AccessKeySecret>')
    req = client.do_http_request( "method", "serviceName", "functionName", "path", headers={}, params=None, body=bytes('hello_world'.encode('utf-8')))
    print (req.status_code)

PHP

  1. 您可以通过以下两种方式安装依赖。
    • 执行Composer命令安装依赖。
      composer require aliyunfc/fc-php-sdk
    • composer.json文件中声明对Alibaba Cloud FC SDK for PHP的依赖关系。
      "require":{
          "aliyunfc/fc-php-sdk": "~1.2"
      }
  2. 运行composer install——no dev安装依赖项。安装Composer依赖关系管理器后,在PHP代码中导入依赖关系。
    require_once __DIR__ . '/vendor/autoload.php';
  3. 代码示例。更多接口入参,请参见SDK源码
    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    use AliyunFC\Client;
    $fcClient = new Client([
      "endpoint" => '<Your Endpoint>',
      "accessKeyID" =>'<Your AccessKeyID>',
      "accessKeySecret" =>'<Your AccessKeySecret>'
    ]);
    $res = $fcClient->doHttpRequest("method", "serviceName", "functionName", "path", $headers = [], $unescapedQueries = [], $data = null);
    $s = $res->getStatusCode();
    $data = $res->getBody()->getContents();
    var_dump($s);
    var_dump($data);

Node.js

  1. 执行以下代码安装依赖。
    npm install @alicloud/fc2 --save
  2. 代码示例。GET请求调用示例如下,更多接口入参,请参见 SDK源码
    'use strict';
    var FCClient = require('@alicloud/fc2');
    var client = new FCClient('<account id>', {
      accessKeyID: '<access key id>',
      accessKeySecret: '<access key secret>',
      region: 'cn-shanghai',
    });
    async function test () {
      try {
          var resp = await client.get('/proxy/${serviceName}/${functionName}/${path}',null,headers )
          console.log('invoke function: %j', resp);
      } catch (err) {
          console.error(err);
        }
    }
    test().then();

.NET Core

  1. 执行以下代码,在.csproj文件中添加如下package安装依赖。
    <ItemGroup>
        <PackageReference Include="Aliyun.FC.SDK.NetCore" Version="1.0.0" />
    </ItemGroup>
  2. 代码示例。更多接口入参,请参见SDK源码
    using System;
    using System.Collections.Generic;
    using Aliyun.FunctionCompute.SDK.Client;
    using Aliyun.FunctionCompute.SDK.Request;
    
    namespace mynetcore{
        class Program
        {
            static void Main(string[] args)
            {
                var fcClient = new FCClient("region", "<account id>", "<access key id>", "<access key secret>");
                var customHeaders = new Dictionary<string, string> {
    
                };
                Dictionary<string, string[]> unescapedQueries = new Dictionary<string, string[]> 
               {
    
                };
               var resposnse = fcClient.InvokeHttpFunction(new HttpInvokeFunctionRequest(string serviceName, string functionName, string method, string path = null,  string qualifier = null, byte[] payload = null, unescapedQueries , Dictionary<string, string> customHeaders = null));
                Console.WriteLine(resposnse.StatusCode);
            }
        }
    }