def post(self):

        self.set_header("Content-Type", "application/json")
        print self.request.body
        json_data = xml2json(self.request.body.encode('utf8'), options)
        data = json.loads(json_data)['xml']
        return_code = data['return_code']
        if return_code == 'SUCCESS':
            openid = data['openid']
            out_trade_no = data['out_trade_no']
            cash_fee = data['cash_fee']
            where = " openid='%s' and id=%s and (status<>'payed' or status is null) " % (openid, out_trade_no)
            from webpy_db import SQLLiteral
            count = pg.update('pay', status='payed', wexin_return=json_data, stat_date=SQLLiteral('NOW()'), where=where)
            if count != 1:
                error_info = 'update failure: count=%s where=%s' % (count, where)
                print error_info
                raise Exception(error_info)
            else:
                wechat = wechat_oper.getWechat()
                content = '''您支付的 %s 元已进入充值系统,正在向您的油卡充值,请耐心等候......''' % (int(cash_fee) / 100.00)
                wechat.send_text_message(openid, content)
        else:
            print data['return_msg']
#{u'openid': u'oGXiIwHwx_zB8ekXibYjdt3Xb_fE', u'trade_type': u'JSAPI', u'cash_fee': u'1', u'nonce_str': u'798243e4902342c83e833c71141385f', u'return_code': u'SUCCESS', u'is_subscribe': u'Y', u'bank_type': u'CFT', u'mch_id': u'1308443701', u'out_trade_no': u'86', u'result_code': u'SUCCESS', u'total_fee': u'1', u'appid': u'wx907d8a3f50de65db', u'fee_type': u'CNY', u'time_end': u'20160215113326', u'transaction_id': u'1002230516201602153283628055', u'sign': u'CAD12073F45232BB600B8F066B434A30'}

        success = '''
        <xml>
          <return_code><![CDATA[SUCCESS]]></return_code>
          <return_msg><![CDATA[OK]]></return_msg>
        </xml>
        '''
        self.write(success)
    def put(self):
        self.set_header("Content-Type", "application/json")
        parm = json.loads(self.request.body)
        id = parm.get("id")
        status = parm.get("status")

        user_id = self.get_secure_cookie("user_id")
        count = self.pg.update("pay", where="id=%s and status<>'%s' " % (id, status), status=status, user_id=user_id)
        if count != 1:
            raise Exception("占位失败")
        if status == "recharged":  # 完成充值,向微信发送
            pay_info = public_db.getPayInfo(id=id)[0]
            wechat = wechat_oper.getWechat()
            content = """ %s 元已已成功冲入油卡,可以使用了!""" % (int(pay_info.total_fee) / 100.00)
            wechat.send_text_message(pay_info.openid, content)

        self.write(json.dumps({"error": "0"}, cls=public_bz.ExtEncoder))
    def post(self):
        self.set_header("Content-Type", "application/json")

        wechat = wechat_oper.getWechat()

        wechat.parse_data(self.request.body)
        message = wechat.get_message()

        response = None
        if isinstance(message, TextMessage):
            # count = public_db.updateDescription(openid=message.source, desc=message.content)
            # if count == 1:
            #    response = wechat.response_text(content=u'描述已经添加,感谢您的举报.')
            # else:
            #    response = wechat.response_text(content=u'请先发送需要举报的照片')
            response = wechat.response_text(content=u'文字信息')

        elif isinstance(message, VoiceMessage):
            response = wechat.response_text(content=u'语音信息')
        elif isinstance(message, ImageMessage):

            # 需要下载图片
            def downloadImageFile():
                http_client = tornado.httpclient.AsyncHTTPClient()
                http_client.fetch(message.picurl, callback=done)

            def done(response):
                with open("static/upload/images/" + message.media_id + '.jpg', "w") as f:
                    f.write(response.body)
                print "DONE"
            downloadImageFile()
            # 检查用户是否存储了,没有的话存之
            wechat_user_info = public_db.getWechatUserByOpenid(message.source)
            if wechat_user_info:
                pass
            else:
                wechat_user_info = wechat.get_user_info(message.source)
                pg.db.insert('wechat_user', **wechat_user_info)
            pg.db.insert('upload_info', openid=message.source, media_id=message.media_id)

            response = wechat.response_text(content=u'图片已经保存,请继续向我们发送对图片的描述')
        elif isinstance(message, VideoMessage):
            response = wechat.response_text(content=u'视频信息')
        elif isinstance(message, LinkMessage):
            wechat_user_info = wechat.get_user_info(message.source)
            print wechat_user_info
            response = wechat.response_text(content=u'链接信息')
        elif isinstance(message, LocationMessage):
            response = wechat.response_text(content=u'地理位置信息')
        elif isinstance(message, EventMessage):  # 事件信息
            if message.type == 'subscribe':  # 关注事件(包括普通关注事件和扫描二维码造成的关注事件)
                print message.source
                if message.key and message.ticket:  # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件
                    response = wechat.response_text(content=u'用户尚未关注时的二维码扫描关注事件')
                else:
                    response = wechat.response_text(content=u'普通关注事件')
            elif message.type == 'unsubscribe':
                response = wechat.response_text(content=u'取消关注事件')
            elif message.type == 'scan':
                response = wechat.response_text(content=u'用户已关注时的二维码扫描事件')
            elif message.type == 'location':
                response = wechat.response_text(content=u'上报地理位置事件')
            elif message.type == 'click':
                response = wechat.response_text(content=u'自定义菜单点击事件')
            elif message.type == 'view':
                response = wechat.response_text(content=u'自定义菜单跳转链接事件')

        self.write(response)
    web_class = tornado_bz.getAllWebBzRequestHandlers()
    web_class.update(globals().copy())

    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 9000
    print port

    url_map = tornado_bz.getURLMap(web_class)
    # 机器人
    url_map.append((r'/robots.txt()', tornado.web.StaticFileHandler, {'path': "./static/robots.txt"}))
    # sitemap
    url_map.append((r'/sitemap.xml()', tornado.web.StaticFileHandler, {'path': "./static/sitemap.xml"}))
    #url_map.append((r'/static/(.*)', tornado.web.StaticFileHandler, {'path': "./static"}))

    settings = tornado_bz.getSettings()
    settings["pg"] = pg
    settings["domain"] = 'yinmore.follow.center'
    settings["appid"] = wechat_oper.appid
    settings["appsecret"] = wechat_oper.appsecret
    settings["wechat"] = wechat_oper.getWechat()

    application = tornado.web.Application(url_map, **settings)

    application.listen(port)
    ioloop = tornado.ioloop.IOLoop().instance()

    tornado.autoreload.start(ioloop)
    ioloop.start()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wechat_oper
if __name__ == '__main__':
    wechat = wechat_oper.getWechat()
    menu_data = {
        'button': [
            {
                'type': 'view',
                'name': '油卡冲值',
                'url': 'http://yinmore.follow.center/app'
            },
            {
                'type': 'view',
                'name': '油卡管理',
                'url': 'http://yinmore.follow.center/app#!/card_manager/'
            },
        ]
    }
    print wechat.create_menu(menu_data)
Exemplo n.º 6
0
 def initialize(self):
     super(WechatBaseHandler, self).initialize()
     self.wechat = wechat_oper.getWechat()