local function temp_code_get_unionid(code) --时间戳 local timestamp = ngx.now()*1000 --签名计算 local app_secret = appsecret local hmac_sha256 = hmac:new(app_secret, hmac.ALGOS.SHA256) if not hmac_sha256 then return false,"failed to create the hmac_sha1 object" end local ok = hmac_sha256:update(tostring(timestamp)) if not ok then return false,"failed to add data" end local mac = hmac_sha256:final() -- binary mac local signature=ngx.encode_base64(mac) if not hmac_sha256:reset() then return false,"failed to reset hmac_sha256" end local sign = urlEncode(signature) -- appid 是创建扫码登陆中的appid --获取用户信息 local user_info_url = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='..sign..'×tamp='..timestamp..'&accessKey='..appid local data={tmp_auth_code = code } local res,err=post(user_info_url,cjson.encode(data)) if res == nil or cjson.decode(res.body)['errcode']~=0 then return false,"获取用户unionid失败" end return true,cjson.decode(res.body)["user_info"]["unionid"] end
python版本
import requests import json import time import hmac import hashlib import base64 import urllib.parse #计算签名 timestamp = str(round(time.time() * 1000)) #相当于(钉钉后台->登陆->扫码登录->appid) app_key='adfadfadfasdf' #相当于app_secret(钉钉后台->登陆->扫码登录->appSecret) app_secret = 'this is secret' app_secret_enc = app_secret.encode('utf-8') hmac_code = hmac.new(app_secret_enc, timestamp.encode("utf-8"), digestmod=hashlib.sha256).digest() #转urlencode sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) #VxX%2BHojnQ9N7svwrDN8HsztRtbhHYwRxaW%2BSIVE%2BkOI%3D #请求用户信息 url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature={}×tamp={}&accessKey={}".format(sign,timestamp,app_key) #code来自于回掉地址 payload_j={ 'tmp_auth_code':'7a084e1b50d2361ab4d04cd7a9199063' } headers = { 'Content-Type':"application/json;charset=UTF-8" } response = requests.request("POST", url, headers=headers, data = json.dumps(payload_j)) print(response.text)