Hey there, fellow Ruby enthusiast! Ready to supercharge your app with WhatsApp messaging capabilities? You're in the right place. We're going to dive into integrating the WhatsApp API using the nifty whatsapp_sdk
package. This powerhouse combo will let you send messages, handle incoming communications, and leverage WhatsApp's massive user base. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that whatsapp_sdk
gem installed:
gem install whatsapp_sdk
Easy peasy, right?
Now, let's set up those API credentials and get our WhatsApp client ready to roll:
require 'whatsapp_sdk' client = WhatsApp::Client.new( access_token: 'your_access_token', phone_number_id: 'your_phone_number_id' )
Replace those placeholder values with your actual credentials, and you're good to go!
Sending a text message is a breeze:
client.messages.send( to: '1234567890', body: 'Hello from Ruby!' )
Want to spice things up with an image?
client.messages.send( to: '1234567890', media: { type: 'image', url: 'https://example.com/image.jpg' } )
For those pre-approved templates:
client.messages.send( to: '1234567890', template: { name: 'hello_world', language: { code: 'en_US' } } )
To handle incoming messages, you'll need to set up a webhook. Here's a quick Sinatra example:
require 'sinatra' post '/webhook' do # Process the incoming webhook payload # Don't forget to verify the webhook signature! end
Once your webhook is set up, you can process incoming messages like this:
post '/webhook' do payload = JSON.parse(request.body.read) message = payload['entry'][0]['changes'][0]['value']['messages'][0] # Handle the message based on its type case message['type'] when 'text' # Handle text message when 'image' # Handle image message end end
Keep tabs on your messages:
client.messages.status(message_id: 'your_message_id')
Create a group and send a message:
group = client.groups.create(name: 'Ruby Devs') client.messages.send( to: group.id, body: 'Welcome to the Ruby Devs group!' )
Manage your contacts like a pro:
client.contacts.create( name: 'John Doe', phone: '1234567890' )
Always wrap your API calls in a begin/rescue block:
begin client.messages.send(to: '1234567890', body: 'Hello!') rescue WhatsApp::Error => e puts "Oops! #{e.message}" end
And don't forget about rate limits – be a good API citizen!
Unit testing is your friend. Mock those API responses:
RSpec.describe WhatsAppService do it 'sends a message' do allow_any_instance_of(WhatsApp::Client).to receive(:send).and_return(true) # Your test code here end end
When deploying, remember to:
And there you have it! You're now armed with the knowledge to build a robust WhatsApp API integration in Ruby. Remember, the whatsapp_sdk
docs are your best friend for diving deeper. Now go forth and build something awesome!
Happy coding, Rubyist! 🚀💎