当一个接口需要将请求参数拼接并进行MD5加密后转换成大写生成sign验签,利用python请求方式实现验签加密并实现自动调用接口
拼接规则: Secret + "appId" + appId + 'data' + str(str_data) + "timestamp" + MD5_sign().timetamp()
密钥: appId = 433f96c852211a42b12b1111
Secret = “d12717a5cf-3824e-422ca-9260a-88c124527103a341112
” 请求data需要作为先拼接后再进行MD5加密 散列值最后转为"⼤写"赋给sign
import hashlib
import json
import requests
import timeclass MD5_sign : def calculate_md5 ( self, input_string) : """MD5加密:param input_string::return:""" md5 = hashlib. md5( ) md5. update( input_string. encode( 'utf-8' ) ) return md5. hexdigest( ) . upper( ) def timetamp ( self) : """获取当前时间戳毫秒级别:return:""" timestamp = int ( time. time( ) * 1000 ) timestamp = str ( timestamp) return timestampdef format_parameter ( self, data) : """传参进行拼接:param data::return:""" str_data = json. dumps( data, ensure_ascii= False , separators= ( ',' , ':' ) ) sign = Secret + "appId" + appId + 'data' + str ( str_data) + "timestamp" + MD5_sign( ) . timetamp( ) return signdef sign_json ( self, data) : """参数化json数据:param data::return:""" sign = self. format_parameter( data) md5_sign = MD5_sign( ) . calculate_md5( sign) print ( md5_sign) json_data = { "appId" : f" { appId} " , "timestamp" : self. timetamp( ) , "secret" : f" { Secret} " , "sign" : f" { md5_sign} " , "data" : data} return json_datadef run_main ( self, method, url, json= None , header= None ) : """请求方式:param method: 请求类型:param url: url:param json: 请求数据:param header: 请求头:return:""" if method == "post" : res = requests. request( method= "post" , url= url, json= json) elif method == "get" : res = requests. request( method= "get" , url= url, params= data, headers= header, verify= False ) return resif __name__ == '__main__' : url = "http://XXXX/union/" appId = "433f96c852211a42b12b1111" Secret = "d12717a5cf-3824e-422ca-9260a-88c124527103a341112" data = { "adCode" : "110000" , "orderNo" : "C" + MD5_sign( ) . timetamp( ) , "isRetailerId" : 1 , "fromId" : "21342135FDSG34" , "fromAreaName" : "宝安区" , "fromAddress" : "博彦科技大厦" , "fromAddressDetail" : "4层101" , "fromSenderName" : "小张" , "fromMobile" : "13800000000" , "fromLatitude" : 40.054759 , "fromLongitude" : 116.289086 , "toAddress" : "望京" , "toAddressDetail" : "4楼" , "toLatitude" : 40.004532 , "toLongitude" : 116.475304 , "toReceiverName" : "朱家帅" , "toMobile" : "13545880179" , "requireReceiveTime" : "2024-11-01 11:11" , "goodType" : 1 , "weight" : 5 , "remarks" : "不要加蒜 取餐号:P10222菜品1" , "preDeliveryAmount" : 14000 , "preDeliveryDuration" : 120 , "appointType" : 0 , "appointmentDate" : "" , "totalAmount" : 4000 , "goodsCount" : 2 , "goods" : [ { "name" : "鱿鱼炒饭" , "qty" : 2 , "amount" : 2000 } ] , "fiveRate" : 0 , "orderFrom" : "饿了么" , "orderDistance" : 9000 , "contractType" : "EM_DISCOUNT" } md5_data = MD5_sign( ) . sign_json( data) res = MD5_sign( ) . run_main( method= "post" , url= url, json= md5_data) print ( res. json( ) )