Exemplo n.º 1
0
def wechatHome(request):
    # get signature, timestamp and nonce
    signature = request.GET.get('signature')
    timestamp = request.GET.get('timestamp')
    nonce = request.GET.get('nonce')
    encrypt_type = request.GET.get('encrypt_type')
    msg_signature = request.GET.get('msg_signature')

    try:
        check_signature(TOKEN, signature, timestamp, nonce)
        if request.method == 'GET':
            response = request.GET.get('echostr')
            return HttpResponse(response, content_type="application/json")

# POST request
        if encrypt_type != None:
            # encryption mode
            print("request is encrypt")
            from wechatpy.crypto import WeChatCrypto
            crypto = WeChatCrypto(TOKEN, AES_KEY, APPID)
            try:
                # now msg is xml
                msg = crypto.decrypt_message(request.body, msg_signature,
                                             timestamp, nonce)
            except (InvalidSignatureException, InvalidAppIdException):
                HttpResponseBadRequest("decrypt message error")
        else:
            msg = request.body
        # plaintext mode
        print("before parse_message")
        pprint.pprint(msg)
        msg = wechatpy.parse_message(msg)
        print("after parse_message")
        pprint.pprint(msg)
        if msg.type == 'text':  # text message
            reply = TextReply(message=msg)
            reply.content = 'text reply'
        elif msg.type == 'image':
            reply = ImageReply(message=msg)
            reply.media_id = msg.media_id
        elif msg.type == 'voice':
            reply = VoiceReply(message=msg)
            reply.media_id = 'voice media id'
        elif msg.type == 'video':
            reply = VideoReply(message=msg)
            reply.media_id = 'video media id'
            reply.title = 'video title'
            reply.description = 'video description'
        elif msg.type == 'music':
            reply = MusicReply(message=msg)
            reply.thumb_media_id = 'thumb media id'
            reply.title = 'music title'
            reply.description = 'music description'
            reply.music_url = 'music url'
            reply.hq_music_url = 'hq music url'
        elif msg.type == 'news':
            reply = ArticlesReply(message=msg,
                                  articles=[
                                      {
                                          'title': u'标题1',
                                          'description': u'描述1',
                                          'url': u'http://www.qq.com',
                                      },
                                  ])
        else:
            reply = create_reply('Sorry, can not handle this for now', msg)
        return HttpResponse(reply.render(), content_type="application/json")
    except InvalidSignatureException as e:
        print("check_signature failed")
        HttpResponseBadRequest(e)