This topic describes how to use sample code in the PHP SDK to create a topic, create a subscription, enable an HTTP endpoint, publish a message, view the received message on the HTTP server, and delete the topic.

Step 1: Prepare the environment

  1. Download the latest version of the PHP SDK, decompress the package, and go to the php_sdk/Samples/Topic sub-directory.
  2. Open the CreateTopicAndSendMessage.php file, and configure the AccessKey ID, AccessKey secret, endpoint, and the IP address and port of the destination HTTP server in the last rows of the file.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to access the Alibaba Cloud API.
      • If you are using an Alibaba Cloud account, go to the Security Management page of the Alibaba Cloud console to create and view AccessKey pairs.
      • If you are a RAM user, log on to Alibaba Cloud RAM console to view AccessKey pairs.
    • Endpoint
      • The endpoint that is used to access MNS. Log on to the MNS console, and click Get Endpoint in the upper-right corner to view endpoints.
      • The endpoint of MNS changes based on regions.
    • IP address
      • The IP address that can be accessed from the Internet.
  3. Include the SDK into your code by using a single include (or require) statement.
    //Include an SDK autoloader file.
    require_once(dirname(dirname(dirname(__FILE__))).'/mns-autoloader.php');
    
    //Declare required PHP classes.
    use AliyunMNS\Client;
    use AliyunMNS\Model\SubscriptionAttributes;
    use AliyunMNS\Requests\PublishMessageRequest;
    use AliyunMNS\Requests\CreateTopicRequest;
    use AliyunMNS\Exception\MnsException;       

Step 2: Create a topic

If no topic is available, you must create a topic. The default name of the new queue is CreateTopicAndPublishMessageExample. You can also specify a topic name.

// 1. Generate a request to create a topic. You can specify the parameters of a topic.
$request = new CreateTopicRequest($topicName);
try
{
        $res = $this->client->createTopic($request);
        echo "TopicCreated! \n";
}
catch (MnsException $e)
{
        // 2. The topic may fail to be created if a network error occurs or the topic already exists. You can query the cause and solve the problem.
        echo "CreateTopicFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}           

Step 3: Enable an HTTP endpoint

  • Run the following command to enable a built-in HTTP server to receive requests from the MNS server:

    php -S $ip:$port http_server_sample.php

    Note The ip parameter specifies an IP address that can be accessed from the Internet.
  • Procedure

    • Signs the request that is sent from MNS for verification. The sample code includes an authentication method. However, HTTP endpoints still have the possibility to receive forged MNS requests. To defend against request forgery attacks, you must use a high-security method to verify requests that are received by HTTP endpoints.
    • Verifies the MD5 hash of the message.
    • Parses the request body.
    • Returns the HTTP status code 200.
  • For more information about the sample code, see the http_server_sample.php file in the SDK.

Step 4: Create a subscription

Create a subscription so that the MNS server can push messages to a specified endpoint. In this example, the specified endpoint is an HTTP endpoint.

$subscriptionName = "SubscriptionExample";
// 1. You can specify the parameters of a subscription. The second parameter specifies the endpoint that is used to receive messages.
// 1.1 In this example, the HTTP endpoint that has been enabled in Step 3 is used.
// 1.2 For more information about supported endpoint types, see help.aliyun.com/document_detail/27479.html.
$attributes = new SubscriptionAttributes($subscriptionName, 'http://' . $this->ip . ':' . $this->port);

try
{
        $topic->subscribe($attributes);
        // 2. A subscription is created.
        echo "Subscribed! \n";
}
catch (MnsException $e)
{
        // 3. The subscription may fail to be created if a network error occurs or the subscription already exists. You can query the cause and solve the problem.
        echo "SubscribeFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}          

Step 5: Publish a message

You can publish a message to the topic. MNS automatically pushes the message from the topic to the HTTP endpoint.

$messageBody = "test";
// 1. Create a request to publish the message.
// 1.1 If you need to send a message to an email address, you must specify the parameters of the message. For more information, see the testPublishMailMessage() function in the Tests/TopicTest.php file.
$request = new PublishMessageRequest($messageBody);
try
{
        $res = $topic->publishMessage($request);
        // 2. The message is published.
        echo "MessagePublished! \n";
}
catch (MnsException $e)
{
        // 3. The message may fail to be published if a network error occurs. You can query the cause and solve the problem.
        echo "PublishMessage Failed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}            

Step 6: View the received message on the HTTP server

  • In Step 5, a message has been published to the topic. MNS automatically pushes the message to the HTTP endpoint that has been enabled in Step 3.
  • The error_log() function is used to return the response whether the message is received by the HTTP server. The response is printed in your IDE console.

Step 7: Delete the subscription

If you do not need to receive messages from the topic, you can delete the subscription.

try
{
        $topic->unsubscribe($subscriptionName);
        echo "Unsubscribe Succeed! \n";
}
catch (MnsException $e)
{
        echo "Unsubscribe Failed: " . $e;
        return;
}           

Step 8: Delete the topic

You can use the following sample code to delete the topic.

try
{
        $this->client->deleteTopic($topicName);
        echo "DeleteTopic Succeed! \n";
}
catch (MnsException $e)
{
        echo "DeleteTopic Failed: " . $e;
        return;
}