API Verifikasi SMS dengan Ruby

Version – 1.0

Siapkan Akun Anda untuk Verifikasi SMS

a. Buat Akun MessageCentral: Mendaftar untuk Pusat Pesan akun untuk memulai. Anda akan menerima ID pelanggan, yang akan Anda gunakan dalam aplikasi Anda.


Unduh Ruby:

Kunjungi halaman unduhan Ruby resmi: https://www.ruby-lang.org/en/downloads/

Unduh versi terbaru Ruby untuk sistem operasi Anda (Windows, macOS, atau Linux).

Instal Ruby:

Windows: Klik dua kali penginstal yang diunduh dan ikuti instruksi di layar.

macOS: Buka paket yang diunduh dan ikuti petunjuk instalasi.

Linux: Gunakan manajer paket Anda untuk menginstal Ruby. Misalnya, di Ubuntu, Anda dapat menggunakan

sudo apt-get update
sudo apt-get install ruby-full

Verifikasi Instalasi:

Buka command prompt (pada Windows) atau terminal (di MacOS/Linux).

Jalankan perintah berikut untuk memverifikasi instalasi:

ruby --version

Ini harus mencetak versi Ruby yang diinstal. Jika diinstal dengan benar, Anda akan melihat sesuatu seperti:

ruby 3.1.0p0 (2021-12-25 revision abcdef1234567890)

Setelah Ruby diinstal, Anda dapat mulai menggunakannya untuk mengembangkan aplikasi Ruby.

Untuk mengatur variabel lingkungan PATH untuk Ruby, Anda dapat mengikuti langkah-langkah berikut:

Jendela:

Klik kanan pada “PC ini” atau “My Computer” dan pilih “Properties”.

Klik “Pengaturan sistem lanjutan” dan kemudian “Variabel Lingkungan”.

Di bagian “Variabel sistem”, pilih variabel “Path” dan klik “Edit”.

Tambahkan path ke direktori yang dapat dieksekusi Ruby (misalnya, C:\Ruby27\bin) jika belum ada.

Klik “OK” untuk menyimpan perubahan.

MacOS/Linux:

Buka terminal.

Buka atau buat file.bash_profile di direktori home Anda.

nano ~/.bash_profile

Tambahkan baris berikut, ganti /path/to/ruby dengan path aktual ke direktori yang dapat dieksekusi Ruby Anda:

export PATH=$PATH:/path/to/ruby

Simpan file dan keluar dari editor teks.

Sumber file.bash_profile untuk menerapkan perubahan:

Setelah mengikuti langkah-langkah ini, Ruby yang dapat dieksekusi harus dapat diakses dari mana saja di sesi terminal Anda.

Langkah Integrasi

Proses ini melibatkan tiga langkah penting berikut:

  1. Rincian Pusat Pesan
  2. Menambahkan Detail Pusat Pesan dalam Kode
  3. Kirim Test Otp untuk verifikasi

a. Rincian Pusat Pesan

Setelah membuat akun di Pusat Pesan, Anda memerlukan detail berikut

  • ID Pelanggan - Anda bisa mendapatkan ID pelanggan dari Message Central Home Console
  • Kredensi Login: Anda memerlukan email dan perlu membuat kata sandi

b. Menambahkan Detail MessageCentral dalam Kode

Untuk menambahkan detail MessageCentral pada kode cari tahu definisi variabel dengan nama “CustomerID”, “email” dan “password”:

customer_id = "C-45539F39A4*****"
email = "abhishek*****k68@gmail.com"
password = "*****"
base_url = "https://cpaas.messagecentral.com"
auth_token = nil
verification_id = nil
verification_status = nil

Sekarang, Anda perlu membuat file Ruby bernama program.rb dan menambahkan kode Ruby yang disediakan ke dalam file ini.

require 'json'
require 'net/http'

customer_id = "C-45539F39A449437"
email = "abhishekkaushik68@gmail.com"
password = "Wesee@123"
base_url = "https://cpaas.messagecentral.com"
auth_token = nil
verification_id = nil
verification_status = nil

def parse_json(json_string, key)
  begin
    json = JSON.parse(json_string)
    return json[key]
  rescue JSON::ParserError => e
    puts e
    return nil
  end
end

def generate_auth_token(customer_id, email, password, base_url)
  begin
    base64_string = Base64.strict_encode64(password)
    url = "#{base_url}/auth/v1/authentication/token?country=IN&customerId=#{customer_id}&email=#{email}&key=#{base64_string}&scope=NEW"
    uri = URI(url)
    response = Net::HTTP.get_response(uri)
    if response.code == '200'
      auth_token = parse_json(response.body, 'token')
      return auth_token
    else
      puts "Error generating auth token. Response code: #{response.code}"
      return nil
    end
  rescue StandardError => e
    puts e
    return nil
  end
end

def send_otp(country_code, mobile_number, base_url, auth_token)
  begin
    url = "#{base_url}/verification/v3/send?countryCode=#{country_code}&customerId=#{customer_id}&flowType=SMS&mobileNumber=#{mobile_number}"
    uri = URI(url)
    request = Net::HTTP::Post.new(uri)
    request['Accept'] = '*/*'
    request['authToken'] = auth_token

    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(request)
    end

    if response.code == '200'
      verification_id = parse_json(parse_json(response.body, 'data'), 'verificationId')
      return verification_id
    else
      puts "Error sending OTP. Response code: #{response.code}"
      return nil
    end
  rescue StandardError => e
    puts e
    return nil
  end
end

def validate_otp(otp_code, country_code, mobile_number, verification_id, base_url, auth_token)
  begin
    url = "#{base_url}/verification/v3/validateOtp?countryCode=#{country_code}&mobileNumber=#{mobile_number}&verificationId=#{verification_id}&customerId=#{customer_id}&code=#{otp_code}"
    uri = URI(url)
    request = Net::HTTP::Get.new(uri)
    request['Accept'] = '*/*'
    request['authToken'] = auth_token

    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(request)
    end

    if response.code == '200'
      verification_status = parse_json(response.body, 'verificationStatus')
      return verification_status
    else
      puts "Error validating OTP. Response code: #{response.code}"
      return nil
    end
  rescue StandardError => e
    puts e
    return nil
  end
end

def run_server(customer_id, email, password, base_url)
  server = TCPServer.new('localhost', 3000)
  puts "Server running at http://localhost:3000/"

  loop do
    Thread.start(server.accept) do |client|
      request = client.gets
      method, path = request.split(' ')
      path_segments = path.split('/')

      if method == 'POST' && path.start_with?('/sendotp/')
        country_code = path_segments[-2]
        mobile_number = path_segments[-1]

        auth_token = generate_auth_token(customer_id, email, password, base_url)
        verification_id = send_otp(country_code, mobile_number, base_url, auth_token)

        response_body = verification_id ? 'Otp sent! Successfully' : 'Bad Request'
        client.puts "HTTP/1.1 200 OK"
        client.puts "Content-Type: text/plain"
        client.puts
        client.puts response_body
      elsif method == 'GET' && path.start_with?('/validateOtp/')
        country_code = path_segments[-3]
        mobile_number = path_segments[-2]
        otp_code = path_segments[-1]

        auth_token = generate_auth_token(customer_id, email, password, base_url)
        verification_status = validate_otp(otp_code, country_code, mobile_number, verification_id, base_url, auth_token)

        response_body = verification_status == 'VERIFICATION_COMPLETED' ? 'Otp verification Done!' : 'Bad Request'
        client.puts "HTTP/1.1 200 OK"
        client.puts "Content-Type: text/plain"
        client.puts
        client.puts response_body
      else
        client.puts "HTTP/1.1 404 Not Found"
        client.puts "Content-Type: text/plain"
        client.puts
        client.puts "Not Found"
      end

      client.close
    end
  end
end

run_server(customer_id, email, password, base_url)

c. Kirim SMS Test Otp untuk Verifikasi

Jika Anda perlu menguji layanan tanpa kode, Anda dapat pergi ke verifikasi SMS gratis halaman di situs web Pusat Pesan.
Untuk memastikan integrasi berhasil, kirim SMS OTP uji sebagai berikut:

  1. Untuk menjalankan kode Ruby, Anda perlu mengeksekusinya menggunakan penerjemah Ruby. Berikut cara Anda melakukannya:

    Simpan kode Ruby Anda dalam file bernama program.rb.
    Buka terminal atau command prompt.
    Arahkan ke direktori tempat program.rb disimpan.
    Jalankan file Ruby menggunakan perintah ruby:

    Ruby Program.rb
    Ini akan menjalankan program Ruby Anda dan menampilkan output apa pun yang dihasilkannya.
  1. Buka Postman dan atur Metode Permintaan sebagai POST dan
    URL sebagai http://localhost:3000/sendotp/<countryCode>/<phone_number>
    Inilah port 3000, itu default dan didefinisikan dalam kode, dapat diubah.
    Contoh, Untuk URL Nomor Telepon India:
    http://localhost:3000/sendotp/91/123****123
    • Gambar 1: Mengirim Otp
Image 1 : Sending Otp
  1. Sekarang Anda memiliki otp di kotak masuk sms Anda. Coba validasi Otp API Anda sendiri untuk memvalidasi OTP.
    Buka Postman dan atur Metode Permintaan sebagai GET dan
    URL sebagai http://localhost:3000/validateOtp/<countryCode>/<phone_number>/<otp>
    Inilah port 3000, itu default dan didefinisikan dalam kode, dapat diubah.
    Contoh, Untuk Nomor Telepon IndiaURL:
    http://localhost:3000/validateOtp/91/123****123/ **** 
    • Gambar 2: Memverifikasi Otp
Image 2 : Verifying Otp
Share this article
verification code

Boost your sales and customer engagement with Message Central now!

Message Central Logo Blue
Close Icon
Tim Pusat Pesan
Halo
Bagaimana kami bisa membantu Anda hari ini?
WhatsApp Icon
Mulai Obrolan Whatsapp
Obrolan WhatsApp
WhatsApp Icon