30min
aihara
  1. 1. Information
    1. 1.1. Ingredients
    2. 1.2. Functions
  2. 2. Create the application
    1. 2.1. Frontend
    2. 2.2. Backend
  3. 3. Customize the application
    1. 3.1. Frontend
    2. 3.2. Backend
  4. 4. Deploy the application
    1. 4.1. Backend
    2. 4.2. Frontend
  5. 5. Download
  6. 6. Version

This application can chat with people who visited your facebook page using Facebook Messenger Platform API.

Information

Ingredients

  • Template: Chat
  • API Loigcs: MongoDB, Facebook Messenger Platform, Request

Functions

  • Storing messages in MongoDB.
  • Providing UI for you to chat with Facebook Messenger.

Create the application

Frontend

  1. Choose the Chat Template.

  2. Customize the UI in K5 Playground.

Backend

  1. Add a WebAPI named webhook and activate GET and POST.

  2. Edit the API Logic of POST message endpoint.

    1. Select the POST message endpoint.

    2. Find the Facebook Messenger Platform Send Message API Logic from Messaging menu at the right pane.

    3. Add the logic after the Stream Send Message API Logic.

    4. Edit accessToken, text, recipient.

      1
      2
      3
      4
      5
      6
      7
      var accessToken = '[ACCESS_TOKEN]';
      var recipient = {
      id: req.body.stream_id,
      };
      var message = {
      text: req.body.message,
      };
  3. Edit the API Logic of GET webhook endpoint.

    1. Select the GET webhook endpoint.

    2. Add the Facebook Messenger Platform Verify Webhook Token API Logic from Messaging menu at the right pane.

    3. Edit the code for verification.

      1
      2
      // @todo set Verification Token
      var verificationToken = '[VERIFICATION_TOKEN]';
  4. Edit the API Logic of POST webhook endpoint.

    1. Select the POST webhook endpoint.

    2. Add the Facebook Messenger Platform Receive Message API Logic from Messaging menu at the right pane.

    3. Edit the code for signature and error handle.

      1
      2
      3
      4
      5
      // ~~ code omitted ~~

      var appSecret = '[APP_SECRET]';

      // ~~ code omitted ~~
    4. Add the Request HTTP Client: GET API Logic from Custom menu at the right pane.

    5. Edit the code to get profile image and id.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      var accessToken = '[ACCESS_TOKEN]';

      function getProfile(senderId) {
      var options = {
      url: 'https://graph.facebook.com/v2.6/' + senderId + '?access_token=' + accessToken,
      json: true,
      };
      return new Promise(function(resolve, reject) {
      Request.get(options, function(error, response, body) {
      if (!error && response.statusCode == 200) {
      resolve(body);
      }
      });
      });
      }

      var promises = [];
      results.entry.forEach(function(entry) {
      if (entry.messaging) {
      entry.messaging.forEach(function(messaging) {
      if (messaging.message && !messaging.message.is_echo) {
      promises.push(getProfile(messaging.sender.id).then(function(profile) {
      return Object.assign(messaging, { profile: profile });
      }));
      }
      });
      }
      });
      Promise.all(promises).then(function(profiles) {
      next(profiles);
      });
    6. Add the MongoDB Save Document API Logic from Database menu at the right pane.

    7. Edit the code for save the stream.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      results.forEach(function(messaging) {
      var collectionName = 'sample_stream';
      var url = 'mongodb://' + config.datasource.user + ':' + config.datasource.password + '@' + config.datasource.host + ':' + config.datasource.port + '/' + config.datasource.database;

      MongoClient.connect(url, function(err, db) {
      if (err) {
      throw err;
      }
      db.collection(collectionName).updateOne(
      { stream_id: document.stream_id },
      {
      stream_id: messaging.sender.id,
      name: messaging.profile.first_name + ' ' + messaging.profile.last_name,
      image: messaging.profile.profile_pic,
      },
      { upsert: true },
      function(err, result) {
      db.close();
      if (err) {
      throw err;
      }
      return;
      }
      );
      });
      });

      next(results);
    8. Add the MongoDB Save Document API Logic from Database menu at the right pane.

    9. Edit the code for save the message.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      function saveMessage(document) {
      var collectionName = 'sample_message';
      var url = 'mongodb://' + config.datasource.user + ':' + config.datasource.password + '@' + config.datasource.host + ':' + config.datasource.port + '/' + config.datasource.database;

      MongoClient.connect(url, function(err, db) {
      if (err) {
      throw err;
      }
      db.collection(collectionName).save(document, function(err, result) {
      db.close();
      if (err) {
      throw err;
      }
      return;
      });
      });
      }

      results.forEach(function(messaging) {
      saveMessage({
      stream_id: messaging.sender.id,
      user_id: messaging.profile.first_name + ' ' + messaging.profile.last_name,
      message: messaging.message.text,
      });
      });

      next({});
  5. Download the application.

Customize the application

Frontend

  1. Change _id tostream_id.

    1. Edit app\components\StreamList\StreamList.js for replacing stream._id with stream.stream_id.

    2. Edit the app\components\StreamContent\StreamContent.js for replacing currentStream._id with currentStream.stream_id.

  2. Add <img> tag to display facebook user profile image.

    1. Edit the app\components\StreamContent\StreamContent.js.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      // ~~ code omitted ~~ 

      stream_id: PropTypes.string,
      name: PropTypes.string,
      image: PropTypes.string.isRequired, // <- add

      // ~~ code omitted ~~

      <VerticalLayout style={styles.streamTitle}>
      {currentStream.name}
      <img src={currentStream.image} alt={currentStream.user_id} style={{ width: 100 }} /> // <- add
      </VerticalLayout>

      // ~~ code omitted ~~

Backend

  1. Edit swagger(api/swagger.json) to receive Facebook events.

    Add parameter property to /webhook.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    "/webhook": {

    // ~~ code omitted ~~

    "post": {
    "description": "",
    "parameters": [{
    "name": "data",
    "in": "body",
    "schema": {
    "type": "string"
    }
    }],
  2. Edit the config.js to set the datasource to connect to MongoDB.

Deploy the application

Finally, all you need to do is deploying backend and frontend.

Backend

1
2
cd backend
cf push [APP_NAME]

Frontend

1
2
3
4
5
6
cd frontend
npm install
set API_URL=[Backend URL] # for Windows
export API_URL=[Backend URL] # for Mac/Linux
npm run build
cf push [APP_NAME] -p public

Download

NOTE: Removed all actions and components not in use.

Version

  • Chat Template: v1.0.0