Set up payments in a Slack bot

This tutorial walks you through the process of setting up direct and recurring payments within a Slack bot. The following configuration and setup steps show you how to create and run a bot on your local machine.

To skip the tutorial and set up a simple payment bot with both direct and recurring payments, see the code and setup instructions on our Slack bot sample application on Github.

Create and configure your apps

To start this bot, set up a few apps:

  • A Slack bot app with a few customized features.
  • A PayPal REST app for the OAuth credentials. Follow this information for details on that process.

For the Slack app, use the following steps:

  • Go to the Slack app page and create a new app.
  • Add in a name, the team you want to use this on, and description information.
  • Under "Redirect URI(s)", add http://localhost:3000/oauth. This will be needed when you're logging in to the bot to add it to your Slack team.
  • Click on "Create App".

Now that your app is created, complete these steps to configure the bot:

  • From the left nav, click on Bot Users. On that page, click on the button to Add a bot to this app and add in a default handle. For example, ppapp.
  • From the left nav, click on Interactive Messages. On that page, click on the button to Enable Interactive Messages, then add in https://paypalbot.localtunnel.me/slack/receive within the Request URL field. This URI will be tied to a local tunnel that you set up later, in order to expose our localhost environment to the web.

Lastly, you need the app credentials. Go to App Credentials in the left nav, and take note of the client ID and client secret, you'll need them later.

Step 1: Set up the bot

Botkit provides an easy-to-use set of tools for working with Slack bots. To include the payment components, use the PayPal Node REST SDK.

To get Botkit and the SDK, run the following command in a Terminal window or a command prompt:

npm install --save botkit@0.2.2
npm install --save paypal-rest-sdk@">=1.6.9 <2.0.0"

Now create a new bot file. Our first task is to set up our configuration variables.

var Botkit = require('botkit');
var paypal = require('paypal-rest-sdk');

// PayPal application credentials and payment redirect
var pp_client_id = 'YOUR PAYPAL CLIENT ID';
var pp_client_secret = 'YOUR PAYPAL CLIENT SECRET';
var redirect = 'YOUR APPLICATION URI';

// Check for valid bot setup information
if (!process.env.clientId || !process.env.clientSecret || !process.env.port) {
  console.log('Error: Specify clientId clientSecret and port in environment');
  process.exit(1);
}

// Configure PayPal environment
paypal.configure({
  mode: 'sandbox', //sandbox or live
  client_id: pp_client_id,
  client_secret: pp_client_secret
});

Include the references for BotKit and the PayPal SDK, then set up the PayPal OAuth credentials, obtained when you created your PayPal app. In the case of this example, when you start the Node server you will specify the Slack OAuth credentials on the command line, so if those are not found an error is produced. Lastly, configure the PayPal environment for the bot to start making payment calls.

Next, initialize the Slack bot and set up the server.

// Initialize Slack bot
var controller = Botkit.slackbot({
  // Interactive_replies: true, // tells botkit to send button clicks into conversations
  json_file_store: './db_slackbutton_bot/',
}).configureSlackApp({
  clientId: process.env.clientId,
  clientSecret: process.env.clientSecret,
  scopes: ['bot'],
});

// Initialize web server
controller.setupWebserver(process.env.port,function(err,webserver) {
  controller.createWebhookEndpoints(controller.webserver);

  controller.createOauthEndpoints(controller.webserver,function(err,req,res) {
    if (err){ res.status(500).send('ERROR: ' + err); } 
    else{ res.send('Success!'); }
  });
});

//make sure we don't connect to the RTM twice for the same team
var _bots = {};
function trackBot(bot) {
  _bots[bot.config.token] = bot;
}

Initialize the bot and include a local JSON file storage location, which will be used for some basic data storage. In the case of a production bot, this should be your secured data store. Pass in the Slack OAuth credentials and the bot scope, then initialize the Node server.

Finally, add the bot to Slack.

/****************************************************************
* Handle adding the bot to a team
****************************************************************/
controller.on('create_bot',function(bot,config) {
  if (_bots[bot.config.token]) {
    // Bot already online, no action needed
  } else {
    bot.startRTM(function(err){
      if (!err){ trackBot(bot); }

      bot.startPrivateConversation({user: config.createdBy},function(err,convo) {
        if (err) { 
          console.log(err);  
        } else { 
          convo.say('I am a bot that has just joined your team');
          convo.say('You must now /invite me to a channel');
        }
      });
    });
  }
});

/****************************************************************
* Bot team connection
****************************************************************/
controller.storage.teams.all(function(err,teams){
  if (err){ throw new Error(err); }

  // Connect all teams with bots up to slack!
  for (var t  in teams) {
    if (teams[t].bot) {
      controller.spawn(teams[t]).startRTM(function(err, bot) {
        if (err){ console.log('Error connecting bot to Slack:',err); } 
        else{ trackBot(bot); }
      });
    }
  }
});

When the bot is created, the create_bot event handler runs and sends you a message to invite it to your team.

The last block handles connecting the bot up to teams on Slack.

With that, the basic foundation of the bot is set up, and you're ready to start including interactive messaging features for payment commands.

Step 2: Add payment functions to the bot

With the core application created, you can build functionality to listen for user commands. Use the following code walkthroughs to add specific payment commands to your bot:

  • Simple Pay: Listens for a user to say pay in a direct message, then processes a payment for the bot owner.
  • Direct Pay: Listens for a user to say "pay @USER 10 USD" in a direct message, or something of the like, to process a direct payment to a specific user who has previously registered their PayPal email with the bot.
  • Subscription: Listens for a user to say subscribe in a direct message, then creates a recurring subscription for the user and bot owner, based on a previously created billing plan.

Step 3: Activate the bot

With the bot set up and running on localhost, a tool is needed for exposing localhost to the web. You can use localtunnel for that. Set up the tunnel like so:

  • In a terminal window in the application directiory, install localtunnel by typing npm install localtunnel.
  • Once installed, create a localtunnel to expose localhost port 3000 to the web by typing the following command: lt --port 3000 --subdomain paypalbot.

Now anything running at http://localhost:3000 will be accessible at https://paypalbot.localtunnel.me.

In another terminal window, in the application directory, run the following command to launch the bot, making sure you replace the respective values with the client id and secret that you obtained when creating your Slack app:

clientId=YOUR_SLACK_CLIENT_ID clientSecret=YOUR_SLACK_CLIENT_SECRET port=3000 node bot_paypal.js

That starts your bot on localhost, and with localtunnel it is exposed to the web, allowing you to add it to Slack.

Add the bot the Slack

The last step is to add the bot to Slack. All you need to do is, in a browser, go to http://localhost:3000/login. You will be taken through the process of adding the bot to Slack. Once you see a success message go to Slack and you should see a new message from a bot with the same handle that you set up when creating your Slack app. You can now communicate directly with the bot using the available commands.

Reference: Available commands

The following commands are available for DMs with the Slack bot, which are activated by adding their respective payment features into the bot.

  • Add PayPal EMAIL: Add a PayPal sandbox account email to your account. This email is used when making a peer to peer payment. You can create sandbox accounts on the PayPal dashboard.
  • pay: Issue a simple payment to the creator of the bot.
  • pay @USER AMOUNT CURRENCY (e.g. pay @jcleblanc 100 USD): This is a peer to peer payment. When this command is used, you can make a payment from the email associated with your Slack account to the email associated with the person being paid.
  • subscribe: Subscribe to a regular payment schedule with the bot owner for services.