用Ruby Call 语音验证码服务

elasticboy_123 2014-08-21 05:04:43
云通讯没有Ruby的API事例,因为业务需要编写一个,共享给大家。有问题可以讨论。

这里主要以语音验证码服务为事例

首先,注册和创建应用,获得应用ID "app_id",和帐号ID “account_sid”,和授权令牌 “auth_token"。

to 参数是测试的手机号,需要在应用中进行验证。

主要完成俩部分工作,
1、统一请求包头认证
2、接口的调用

填写正确app_id 、account_sid 、auth_token、to 即可完成调用。过程中有些小插曲,ruby 的base64位编码有用折行的情况,http header要求不能折行,云通讯的接口也是取的不能折行的数据。所以base64后需要对数据做一些处理,即

@authorization.gsub!("\n", '')


或者也也可以使用ruby中不折行的base64的编码方法,这个大家可以查一下google。下面是完整的代码事例。供参考,可以结合业务进行更改

require 'rubygems'



require 'net/http'
require 'net/https'
require 'base64'
require 'md5'



require 'rubygems'
require 'json'


# @host = 'sandboxapp.cloopen.com'
# @port = '8883'
@app_id = ""
@account_sid = ""
@auth_token = ""@to = ""


@time = Time.now.strftime('%Y%m%d%H%M%S')

puts @time

@authorization = Base64.encode64("#{@account_sid}:#{@time.to_s}")

@authorization.gsub!("\n", '')
# puts @authorization
# puts @authorization

# puts Base64.decode64(@authorization)

@sig_parameter = MD5.hexdigest("#{@account_sid}#{@auth_token}#{@time.to_s}").upcase


@post_ws = "/2013-12-26/Accounts/#{@account_sid}/Calls/VoiceVerify?sig=#{@sig_parameter}"


@url = URI.parse("https://sandboxapp.cloopen.com:8883")

@http=Net::HTTP.new(@url.host, @url.port)


@http.use_ssl = true if @url.scheme == 'https'

@http.verify_mode = OpenSSL::SSL::VERIFY_NONE

@payload ={
"appId" => "#{@app_id}",
"verifyCode" => "1a8d9u",
"playTimes" => "2",
"to"=>"#{@to}"
}.to_json

# def post
req = Net::HTTP::Post.new(@post_ws, initheader = {
"Content-Type" => "application/json;charset=utf-8",
"Accept" => "application/json",
'Authorization' => @authorization
})

# req.basic_auth @user, @pass
req.body = @payload
response = @http.start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:#{response.body}"
# end
...全文
935 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
程序员鼓励师 2014-08-23
  • 打赏
  • 举报
回复
finder_123 2014-08-22
  • 打赏
  • 举报
回复
学习了

2,245

社区成员

发帖
与我相关
我的任务
社区描述
OpenAPI
社区管理员
  • OpenAPI社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧