#wechat.py
from flask import Flask,request,make_response
import hashlib
app = Flask(__name__)
@app.route('/wechat8000')
def wechat():
#設置token
token = 'python'
#獲取參數
data = request.args
signature = data.get('signature')
timestamp = data.get('timestamp')
nonce = data.get('nonce')
echostr = data.get('echostr')
#對參數進行字典排序,拼接字符串
temp = [timestamp,nonce,token]
temp.sort()
temp = ''.join(temp)
#加密
if (hashlib.sha1(temp).hexdigest()==signature):
return make_response(echostr)
else:
return 'error',403
if __name__ == '__main__':
app.run(port=8000)
[2019-12-28 00:08:34,931] ERROR in app: Exception on /wechat8000 [GET]
Traceback (most recent call last):
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/app.py”, line 2446, in wsgi_app
response = self.full_dispatch_request()
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/app.py”, line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/app.py”, line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/_compat.py”, line 39, in reraise
raise value
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/app.py”, line 1949, in full_dispatch_request
rv = self.dispatch_request()
File “/root/.virtualenvs/weixin/lib/python3.7/site-packages/flask/app.py”, line 1935, in dispatch_request
return self.view_functionsrule.endpoint
File “wechat.py”, line 23, in wechat
if (hashlib.sha1(temp).hexdigest()==signature):
TypeError: Unicode-objects must be encoded before hashing
解決更新加密前的編碼
s1 = sha1()
s1.update(temp.encode(“utf8”))
sign = s1.hexdigest()
# coding:utf-8
from flask import Flask,request,make_response,abort
from hashlib import sha1
app = Flask(__name__)
@app.route('/wechat8000')
def wechat():
#設置token
token = 'python'
#獲取參數
data = request.args
signature = data.get('signature')
timestamp = data.get('timestamp')
nonce = data.get('nonce')
echostr = data.get('echostr')
#對參數進行字典排序,拼接字符串
temp = [timestamp,nonce,token]
temp.sort()
temp = ''.join(temp)
#加密
s1 = sha1()
s1.update(temp.encode("utf8"))
sign = s1.hexdigest()
if sign !=signature:
abort(403)
else:
return echostr
if __name__ == '__main__':
app.run(port=8000)