微信公众号加密传输

书接上文,自己写微信接口是很蠢的一种行为(指昨天的自己)。我们隆重介绍微信官方API——wechatpy。它可以用来专门对接自己的服务器和微信公众号。

直接介绍干货吧:

验证

之前我们需要自己进行加密然后再做操作,这里就不需要了:


from wechatpy.crypto import WeChatCrypto
from wechatpy import parse_message, create_reply, replies
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.exceptions import InvalidAppIdException

WECHAT_TOKEN = WECHAT_TOKEN 
ENCODING_AESKEY = ENCODING_AESKEY 
APPID = APPID 
app = Flask(__name__)
@app.route('/wechat', methods=["GET", "POST"])
def wechat():
"""对接微信公众号服务器"""
        signature = request.args.get("signature")
        timestamp = request.args.get("timestamp")
        nonce = request.args.get("nonce")
        echo_str = request.args.get("echostr")
        msg_signature = request.args.get("msg_signature")

        # get和post都需要验证身份
        try:
            check_signature(WECHAT_TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            abort(403)

        if request.method == "GET":
            return echo_str

是不是很简单?

发送接收加密消息

crypto = WeChatCrypto(WECHAT_TOKEN, ENCODING_AESKEY, APPID)
            # 解密
            try:
                msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce)
                msg = parse_message(msg)
            except (InvalidSignatureException, InvalidAppIdException):  # 解密错误
                abort(403)

            # msg已经为解构的消息
            if msg.type == "text":
                reply = create_reply("回复消息", msg)
            else:
                reply = create_reply('非法信息', msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp)

是不是很简单??
甚至没什么好讲的。

你可能感兴趣的:(微信公众号加密传输)