- 1 代码引入
- 2 定义便于项目中使用的类
- 3 使用
在rails(python、java、go等语言的代码示例可以在腾讯云的调试工具中查看,地址:https://console.cloud.tencent.com/api/explorer?Product=captcha&Version=2019-07-22&Action=DescribeCaptchaMiniResult )后端项目中,使用腾讯云滑块验证码SDK来校验小程序前端发送的票据(ticket)的结果。
腾讯云验证码的文档地址:https://cloud.tencent.com/document/api/1110/369261 代码引入
采用源码引入的方式将部分sdk代码引入到项目中
源码地址: https://github.com/TencentCloud/tencentcloud-sdk-ruby
将代码中的tencentcloud-sdk-common和tencentcloud-sdk-captcha的部分导入自己的项目中。
定义一个公共类,便于在项目中使用。
require 'tencentcloud_common/tencentcloud-sdk-common' # 自定义的目录
require 'tencentcloud_captcha/tencentcloud-sdk-captcha' # 自定义的目录
class TencentCaptcha
# 在config/environment/中的不同环境中定义部分固定的参数,如CaptchaAppId、AppSecretKey、SecretId、SecretKey等
@@tencentcloud_captcha = Rails.configuration.tencentcloud_captcha
# 定义方法
# params[:ticket] 验证码返回给用户的票据
# params[:user_ip] 业务侧获取到的验证码使用者的外网IP
def self.describe_captcha_mini_result(params)
userIp = params[:user_ip] || "127.0.0.1"
# 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
cre = TencentCloud::Common::Credential.new(@@tencentcloud_captcha[:SecretId], @@tencentcloud_captcha[:SecretKey])
# 实例化一个http选项
httpProfile = TencentCloud::Common::HttpProfile.new()
# httpProfile.scheme = "https" # 在外网互通的网络环境下支持http协议(默认是https协议),建议使用https协议
# httpProfile.req_method = "GET" # get请求(默认为post请求)
# httpProfile.req_timeout = 30 # 请求超时时间,单位为秒(默认60秒)
httpProfile.endpoint = "captcha.tencentcloudapi.com" # 指定接入地域域名(默认就近接入)
# 实例化一个client选项,可选的,没有特殊需求可以跳过。
clientProfile = TencentCloud::Common::ClientProfile.new()
# clientProfile.sign_method = "TC3-HMAC-SHA256" # 指定签名算法
# clientProfile.language = "en-US" # 指定展示英文(默认为中文)
# clientProfile.sign_method = "TC3-HMAC-SHA256" # 指定签名算法
clientProfile.http_profile = httpProfile
# clientProfile.debug = true # 打印debug日志
# 实例化要请求产品Captcha的client对象,clientProfile是可选的。
# Client.new(credential, region, profile = nil)
cli = TencentCloud::Captcha::V20190722::Client.new(cre, '', clientProfile)
# 实例化一个Captcha实例信息查询请求对象,每个接口都会对应一个request对象DescribeCaptchaMiniResultRequest。
# CaptchaType: 9, Ticket: params["ticket"], UserIp: '127.0.0.1', CaptchaAppId: 1234567890, AppSecretKey: 'xxxxxxxx'
req = TencentCloud::Captcha::V20190722::DescribeCaptchaMiniResultRequest.new(9, params["ticket"], userIp, @@tencentcloud_captcha[:CaptchaAppId], @@tencentcloud_captcha[:AppSecretKey])
# 通过client对象调用DescribeCaptchaMiniResult方法发起请求。注意请求方法名与请求对象是对应的。
# 返回的resp是一个DescribeCaptchaMiniResultResponse类的实例,与请求对象对应。
resp = cli.DescribeCaptchaMiniResult(req)
resp
end
end
3 使用
desc "校验验证码的结果" params do requires :ticket, type: String, desc: "验证码返回给用户的票据" optional :user_ip, type: String, desc: "业务侧获取到的验证码使用者的外网IP" end get "/validate_captcha", root: "questionnaires" do # logger.debug(params["ticket"]) # 前端encode一下ticket,后端decode一下(防止前后端传递参数的过程中对ticket的改变导致,一直返回 “15 ticket decryption failed 票据解密失败”) params["ticket"] = URI::decode(params["ticket"]) res = TencentCaptcha.describe_captcha_mini_result(params) res end



