def decrypt_message(self, timestamp, nonce, msg_signature, encrypt_msg): """ 解密收到的微信消息 :param timestamp: 请求 URL 中收到的 timestamp :param nonce: 请求 URL 中收到的 nonce :param msg_signature: 请求 URL 中收到的 msg_signature :param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 ) :return: 解密后的 XML 文本 """ signature = get_signature(self.token, timestamp, nonce, encrypt_msg) print signature if signature != msg_signature: raise InvalidSignature(msg_signature) return self.prp_crypto.decrypt(encrypt_msg, self.app_id)
def encrypt_message(self, reply, timestamp=None, nonce=None): """ 加密微信回复 :param reply: 加密前的回复 :type reply: WeChatReply 或 XML 文本 :return: 加密后的回复文本 """ if hasattr(reply, "render"): reply = reply.render() timestamp = timestamp or to_binary(int(time.time())) nonce = nonce or generate_token(5) encrypt = to_text(self.prp_crypto.encrypt(reply, self.app_id)) signature = get_signature(self.token, timestamp, nonce, encrypt) return to_text(self.ENCRYPTED_MESSAGE_XML.format( encrypt=encrypt, signature=signature, timestamp=timestamp, nonce=nonce ))