Last active
August 1, 2021 10:12
-
-
Save huacnlee/5b859337f66b0597453825215df6aeea to your computer and use it in GitHub Desktop.
实现钉钉扫描登录 Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 实现钉钉扫描登录 | |
# | |
# 从钉钉 “移动应用接入 - 扫码登录” 开通,并获得 app_id 和 app_secret | |
# 开通:https://open-dev.dingtalk.com/#/loginMan | |
# | |
# 这个流程只能实现简单登录,拿到用户 nick,dingId, openid, unionid | |
# 文档:https://ding-doc.dingtalk.com/doc#/serverapi2/etaarr | |
require "openssl" | |
require "base64" | |
require "faraday" | |
require "json" | |
require "cgi" | |
app_id = "dingxxxxx" | |
app_secret = "xxxxx" | |
def login | |
login_url = "https://oapi.dingtalk.com/connect/qrconnect?appid=#{app_id}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://localhost:5000/login/callback" | |
redirect_to login_url | |
end | |
def callback | |
t = (Time.now.to_f * 1000).to_i.to_s | |
raw_sign = Base64.encode64(OpenSSL::HMAC.digest("SHA256", app_secret, t)).strip | |
sign = CGI.escape(raw_sign) | |
url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=#{app_id}×tamp=#{t}&signature=#{sign}" | |
data = { | |
tmp_auth_code: params[:code] | |
} | |
resp = Faraday.post(url) do |req| | |
req.params['limit'] = 100 | |
req.headers['Content-Type'] = 'application/json' | |
req.body = data.to_json | |
end | |
puts resp.body | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment