How can i confirm the subscription request HTTP from amazon SNS

后端 未结 5 1718
不思量自难忘°
不思量自难忘° 2020-12-30 21:20

I have been searching all over the web and nothing gives a clear answer to confirm the subscription request from amazon SNS. I already send the subscription from the amazon

5条回答
  •  情歌与酒
    2020-12-30 21:48

    Here is an express application (Node.js) which confirms the SNS subscription:

    const express = require('express')
    const request = require('request')
    // parse urlencoded request bodies into req.body
    const bodyParser = require('body-parser')
    const app = express()
    const port = 8080
    
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(bodyParser.json())
    
    app.post('/', (req, res) => {
      let body = ''
    
      req.on('data', (chunk) => {
        body += chunk.toString()
      })
    
      req.on('end', () => {
        let payload = JSON.parse(body)
    
        if (payload.Type === 'SubscriptionConfirmation') {
          const promise = new Promise((resolve, reject) => {
            const url = payload.SubscribeURL
    
            request(url, (error, response) => {
              if (!error && response.statusCode == 200) {
                console.log('Yess! We have accepted the confirmation from AWS')
                return resolve()
              } else {
                return reject()
              }
            })
          })
    
          promise.then(() => {
            res.end("ok")
          })
        }
      })
    })
    
    app.listen(port, () => console.log('Example app listening on port ' + port + '!'))
    

    To use it one needs to install required packages:

    yarn add express request body-parser
    

    Once you confirm the subscription AWS will send a POST request to the server with the following content:

    {
      "Type": "SubscriptionConfirmation",
      "MessageId": "XXXXXXXX-1ee3-4de3-9c69-XXXXXXXXXXXX",
      "Token": "SECRET_TOKEN",
      "TopicArn": "arn:aws:sns:us-west-2:XXXXXXXXXXXX:ses-test",
      "Message": "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:XXXXXXXXXXXX:ses-test. To confirm the subscription, visit the SubscribeURL included in this message.",
      "SubscribeURL": "https://sns.us-west-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:XXXXXXXXXXXX:ses-test&Token=SECRET_TOKEN",
      "Timestamp": "2018-11-21T19:48:08.170Z",
      "SignatureVersion": "1",
      "Signature": "SECRET",
      "SigningCertURL": "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.pem"
    }
    

    The payload contains SubscribeURL which is requested by the server.

提交回复
热议问题