404hub
1/4/2020 - 11:02 AM

钉钉机器人加签示例代码

# 示例1:参照钉钉文档中python2代码修改的python3加签代码示例

import time
import hmac
import hashlib
import base64
import urllib

timestamp = int(round(time.time()*1000))
secret = 'SECxxx...'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

print(timestamp)
print(sign)


# 示例2: https://www.caorui.net/blog/38.html 中的钉钉加签python3代码示例
import hmac
import hashlib
import base64
import re
import time
import urllib

# secret:密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串,例如:SECxxxxxxxx
secret = 'SECxxx'
# timestamp:当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时
timestamp = int(round(time.time() * 1000))
# 加密,获取sign和timestamp
data = (str(timestamp) + '\n' + secret).encode('utf-8')
secret = secret.encode('utf-8')
# 使用HmacSHA256算法计算签名,然后进行Base64 encode
signature = base64.b64encode(hmac.new(secret, data, digestmod=hashlib.sha256).digest())
reg = re.compile(r"'(.*)'")
signature = str(re.findall(reg, str(signature))[0])
# 最后进行urlEncode
urlencode = urllib.parse.quote_plus(signature)
print(timestamp)
print(urlencode)