Search code examples
smooch

Smooch: How to trigger postback when user clicks a button?


I have some questions about the postback button.

We are developing independent-built, own Web Messenger using Smooch.

I am making an API call using Smooch-core. ( like below )

this.smooch = await new SmoochCore({
    keyId: SMOOCH_KEY_ID,
    secret: SMOOCH_SECRET,
    ....
  });
...
await this.smooch.appUsers.sendMessage(this.appId, this.userId, message);

The problem is that it works differently from our intent when we render and tap the button.

To create a button in the Messenger window, app maker sends a message with a postback type action, receives the payload of the message from webhook, and then renders the button and handles the click action according to our system policy.

Here is message code that app maker sends

{
"role": "appMaker",
"type": "text",
"text": "check in/out infos",
"actions": [
    {
        "text": "Check In Info",
        "type": "postback",
        "payload": "{\"text\": \"Check in info\", \"type\": \"start\", \"flow\": \"checkInOut\", \"message_id\": \"MESSAGEID001\", \"data\": {\"intent\": \"info_check_in\"}}"
    },
    {
        "text": "Check Out Info",
        "type": "postback",
        "payload": "{\"text\": \"Check out info\", \"type\": \"start\", \"flow\": \"checkInOut\", \"message_id\": \"MESSAGEID001\", \"data\": {\"intent\": \"info_check_out\"}}"

    },
    {
        "text": "Early Check In Info,
        "type": "postback",
        "payload": "{\"text\": \"Early check in\", \"type\": \"start\", \"flow\": \"checkInOut\", \"message_id\": \"MESSAGEID001\", \"data\": {\"intent\": \"info_early_check_in\"}}"

    }
]
}

My system renders actions (buttons) of the message using ReactJS.

<ul className={b('button-group')}>
      {
        actions.map((action, index) => {
          return (
            <li
              key={index}
              onClick={this.onChoiceButtonClick(action)}
            >
              <span>{action.text}</span>
            </li>
          );
        })
      }
    </ul>

Since I am handling the button click event in our system, I want to make the same action as tapping the postback button provided by Smooch.

(That is, "trigger": "postback" , like "trigger":"message:appUser" for smooch.appUsers.sendMessage )

How can I handle this?

Would greatly appreciate it if you kindly give me some advice. :)


Solution

  • You should call the triggerPostback method in response to the user clicking your custom button. According to the code snippet you posted above, you are calling a method onChoiceButtonClick. The implementation of that method should look something like this:

    function onChoiceButtonClick(action) {
        Smooch.triggerPostback(action._id);
    }