This article describes how to use MNS SDK for PHP to create a topic, create a subscription, enable an HTTP endpoint, and publish messages.

Step 1: Prepare the environment

  1. Download the latest version of the SDK for PHP, decompress the package, and then go to the aliyun-mns-php-sdk-master/Samples/Topic subdirectory.
  2. Open the CreateTopicAndSendMessage.php file and specify the following information:
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to call the API operations of Alibaba Cloud.
      • If you are using an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view your AccessKey pair.
      • If you are a Resource Access Management (RAM) user, log on to the RAM console to view your AccessKey pair.
    • Endpoint
      • The endpoint that is used to access Message Service (MNS). To view the endpoint of MNS, log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint varies by region.
  3. Modify the settings of the SDK

    Use the sample code at the beginning of the CreateTopicAndSendMessage.php file to specify the SDK.

    // Include an SDK autoload 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 topic is CreateTopicAndPublishMessageExample. You can also specify another 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 name already exists. You can call the CatchException or Catch TopicAlreadyExistException operation to identify and resolve the failure. 
        echo "CreateTopicFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;

Step 3: Enable an HTTP endpoint

  • Run the http_server_sample.php command to enable a built-in HTTP server to receive requests from MNS.
    php -S $ip:$port http_server_sample.php
    Note The ip parameter must be set to an IP address that can be accessed from the Internet.
  • Features of the HTTP endpoint

    • 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 body.
    • 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 MNS 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. For more information, see Subscription. 
$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 name already exists. You can call the CatchException operation to identify and resolve the failure. 
        echo "SubscribeFailed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}          

Step 5: Publish a message

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

$messageBody = "test";
// 1.Generate a PublishMessage request. 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 call the CatchException operation to identify and resolve the failure. 
        echo "PublishMessage Failed: " . $e . "\n";
        echo "MNSErrorCode: " . $e->getMnsErrorCode() . "\n";
        return;
}            

Step 6: View the received messages on the HTTP server

  1. In Step 5, multiple messages have been published to the topic. MNS pushes the messages to the endpoint that is enabled in Step 3.
  2. After the message is pushed, the error_log() function indicates whether the message is received in the console.

Step 7: Delete the subscription

If you no longer 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

Deletes the topic that is created in Step 2.

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