假设您在 https://lalaland.shinyapps.io/mail-form/ 上有一个简单的应用程序用作联系表格。您想在发送电子邮件之前测试发件人不是机器人。这可能看起来像:
全局 :
library(shiny)
library(shinyAce)
library(mailR)
ui.R :
ui<-shinyUI(
fluidPage(
fluidRow(
column(2
,textInput("contact_name", "Name*", placeholder = "Ed Snow")
),
column(2, offset = 0
,textInput("contact_email", "Email*", placeholder = "eddie@lubyanka.com")
)
),
fluidRow(
column(4,
aceEditor(outputId = "contact_message", value = "...", fontSize = 13)
)
),
fluidRow(
column(2,
checkboxInput("contact_not_a_robot", "I'm not a robot*", value = FALSE), # !!! <---
actionButton("contact_click_send", "Send")
))
)
)
server.R :
server <- shinyServer(function(session,input, output) {
observeEvent(input$contact_click_send, {
if( is.null(input$contact_click_send) || input$contact_click_send==0
|| !input$contact_not_a_robot){ # !!! <---
return(NULL)
}
send.mail(from = "kremlin@gmail.com",
to = "trumptower@gmail.com",
subject = "Shower time!",
body = input$contact_message,
smtp = list(host.name = "smtp.gmail.com"
, port = 465
, user.name = "kremlin@gmail.com"
, passwd = "DONALD_BIG_HANDS123"
, ssl = TRUE),
authenticate = TRUE,
html = TRUE, send = TRUE)
# reset form
updateTextInput(session, "contact_name", value = "")
updateTextInput(session, "contact_email", value = "")
updateAceEditor(session, "contact_message", value = "Message sent succesfully!")
updateCheckboxInput(session, "contact_not_a_robot", value = FALSE)
updateActionButton(session, "contact_click_send", icon = icon("check"))
})
})
问题提出了不同的方式:如何将(重新/)验证码编织到这个 R/Shiny 联系表中?
最佳答案
对于 reCAPTCHAv3,使用 https://github.com/sarthi2395/shinygCAPTCHAv3
devtools::install_github("sarthi2395/shinygCAPTCHAv3")
将此添加到您的 global.R :
library(shinygCAPTCHAv3)
ui.R :
ui<-shinyUI(
fluidPage(
GreCAPTCHAv3Ui(<your site key>,"homepage","responseReceived"),
#Rest of your code
)
)
您必须输入在 reCAPTCHA 管理控制台中为您注册的域生成的 SiteKey。在这里,我已将操作指定为“主页”,但您可以选择适合您目的的操作 ( https://developers.google.com/recaptcha/docs/v3 )。
responseReceived 是我们将在此处使用的对象,用于将收到的 token 传递给 Shiny 的服务器,以便与 Google 进行验证。
server.R
server <- shinyServer(function(session,input, output) {
observeEvent(input$responseReceived, {
result <- GreCAPTCHAv3Server(<your secret key>,input$responseReceived)
if(result$success){
#Rest of your server logic.
}
})
})
在这里,您必须输入在 reCAPTCHA 管理控制台中为您注册的域生成的 SecretKey。
如果一切顺利,当您启动网页时,您将在右下角看到 reCAPTCHA 框。希望这可以帮助。
关于r - 如何在 R/Shiny 中使用(重新/)验证码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41681184/