Exemplo n.º 1
0
def sdk_m4399_callback():
    cfg = settings.SDK["m4399"]
    sdktype = poem_pb.SDK_M4399
    MAX_BODY = 2048
    import urllib
    from yy.sdk.pay import JSONResponse
    rawmsg = request.body.read(MAX_BODY) if request.method == 'POST'\
        else request.query_string
    params = dict(request.params)
    values = [
        params.get(f, "") for f in [
            'orderid', 'uid', 'money', 'gamemoney', 'serverid', 'mark',
            'roleid', 'time'
        ]
    ]
    values.insert(5, cfg['appkey'])
    values[6] = urllib.unquote(values[6])
    tosign = ''.join(values)
    if params['sign'] != md5(tosign).hexdigest():
        logger.error('[sdk m4399] verify failed')
        return JSONResponse({
            "status": 1,
            "code": 'sign_error',
        })
    worldID, orderID = params['mark'].split('_')
    # {{
    # 万不得已的做法, FIXME
    # 4399透传参数不能超过32位,所以entityID得不到
    # 只能本地查
    from session.utils import sdk_username
    from sdk.payment import get_payment
    payment = get_payment(sdk_username(sdktype, orderID))
    if not payment:
        return JSONResponse({"status": 1, "code": 'other_error'})
    entityID = payment["entityID"]
    # }}
    money = float(params['money'])
    result = do_pay(int(worldID),
                    int(entityID),
                    orderID,
                    money,
                    rawmsg,
                    sdktype=sdktype)
    if 'success' in result:
        return JSONResponse({
            "status": 2,
            "code": None,
            "money": money,
            "gamemoney": money * 10,
            "msg": u"充值成功",
        })
    else:
        logger.error('[sdk m4399] pay failed')
        return JSONResponse({"status": 1, "code": 'other_error'})
Exemplo n.º 2
0
def sdk_egame_callback():
    MAX_BODY = 2048
    rawmsg = request.body.read(
        MAX_BODY) if request.method == 'POST' else request.query_string

    label = 'egame'
    cfg = settings.SDK[label]
    sdktype = sdk_types[label]

    worldID, orderID = request.params['cp_order_id'].split('_')
    if request.params['method'] == 'callback':
        tpl = '<cp_notify_resp><h_ret>%s</h_ret><cp_order_id>%s</cp_order_id></cp_notify_resp>'
        fields = [
            'cp_order_id', 'correlator', 'result_code', 'fee', 'pay_type',
            'method'
        ]
        signed = md5(''.join(request.params[f]
                             for f in fields) + cfg['appkey']).hexdigest()
        if signed != request.params['sign']:
            logger.error('[sdk egame] verify failed')
            return tpl % (-1, orderID)
        result = do_pay(int(worldID),
                        0,
                        orderID,
                        float(request.params['fee']),
                        rawmsg,
                        sdktype=sdktype)
        if 'success' in result:
            return tpl % (0, orderID)
        else:
            logger.error('[sdk egame] pay failed')
            return tpl % (-1, orderID)
    else:
        fields = ['cp_order_id', 'correlator', 'order_time', 'method']
        signed = md5(''.join(request.params[f]
                             for f in fields) + cfg['appkey']).hexdigest()
        if signed != request.params['sign']:
            logger.error('[sdk egame] verify failed2')
            return tpl % (-1, orderID)
        info = get_payment(sdk_username(sdktype, orderID))
        return '''<sms_pay_check_resp>
                    <cp_order_id>%s</cp_order_id>
                    <correlator>%s</correlator>
                    <game_account>%s</game_account>
                    <fee>%s</fee>
                    <if_pay>0</if_pay>
                    <order_time>%s</order_time>
                  </sms_pay_check_resp>''' % (
            request.params['cp_order_id'], request.params['correlator'],
            request.params['order_time'], info['price'],
            datetime.now().strftime('%Y%m%d%H%M%S'))
Exemplo n.º 3
0
def do_pay(worldID, entityID, order_id, amount, sdata, sdktype=0, delay=0):
    '支付接口'
    if not entityID or not sdktype:
        payment = get_payment(sdk_username(sdktype, order_id))
        if not entityID:
            entityID = int(payment.get('entityID', 0))
        if not sdktype:
            sdktype = int(payment.get('sdktype', 0))
    params = dict(entityId=int(entityID),
                  orderid=order_id,
                  amount=str(amount * 10),
                  sdata=sdata,
                  rechargegold=str(amount * 10),
                  sdktype=sdktype,
                  goods=0,
                  delay=delay)
    rsp = get_proxy(worldID).post("sdk_pay/%d?regionID=%d" %
                                  (int(entityID), int(worldID)),
                                  fields=params)
    return rsp.data
Exemplo n.º 4
0
 def itunes_iap_validation_handle(self, msgtype, req):
     from itunesiap import Request, set_verification_mode
     from itunesiap.exceptions import InvalidReceipt, ItunesServerNotAvailable
     from session.utils import sdk_username
     from sdk.payment import end_payment, get_payment, gen_payment
     player = self.player
     try:
         # set_verification_mode('sandbox')
         request = Request(req.receipt)
         with request.verification_mode('review'):
             receipt = request.verify()
         logger.info(receipt)
         configs = get_config(RechargeConfig)
         goods = filter(
             lambda item: item.goodsid == receipt.product_id and item.
             sdktype == poem_pb.SDK_APP_IOS, configs.values())
         if len(goods) != 1:
             logger.error('Invalid goodsid: {},{}'.format(
                 player.entityID, receipt.product_id))
             return False
         goods = goods[0]
         logger.debug(goods)
         sdkorderid = sdk_username(poem_pb.SDK_APP_IOS,
                                   receipt.transaction_id)
         payment = get_payment(sdkorderid)
         if not payment:
             result = gen_payment(sdkorderid, player.entityID,
                                  poem_pb.SDK_APP_IOS, receipt.product_id)
             payment = get_payment(sdkorderid)
         if payment.get('status', None) != 'SUCCESS':
             if not end_payment(sdkorderid):
                 logger.error('insert callback pay record failed %s' %
                              sdkorderid)
                 return False
             payment = get_payment(sdkorderid)
             logger.debug(payment)
             data = {
                 "clientVersion": "",
                 "amount": goods.amount,
                 "orderNO": sdkorderid,
                 "_level": "",
                 "_username": "",
                 "_userID": 0,
                 "_entityID": player.entityID,
                 "result": 1
             }
             username = player.username
             userID = player.userID
             idfa = player.idfa
             appid = player.appid
             rs = pay_handler(player.entityID,
                              username,
                              payment["goodsid"],
                              amount=int(goods.amount))
             if not rs:
                 return False
             logger.debug(rs)
             get_gold = rs["get_gold"]
             username = rs["username"]
             level = rs["level"]
             rsp = poem_pb.PayResult(success=True,
                                     roleID=player.entityID,
                                     userID=0,
                                     payID=receipt.transaction_id,
                                     goods=0,
                                     count=get_gold,
                                     data=req.receipt)
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgid.SDK_PAY_RESULT, rsp))
             data.update(_username=username, _level=level)
             data.update(_gold=get_gold)
             role_credit(**data)
             gm_logger.info({
                 'pay': {
                     'transaction_id': receipt.transaction_id,
                     'userID': userID,
                     'entityID': player.entityID,
                     'channel': player.channel,
                     'amount': goods.amount,
                     'gold': get_gold,
                     'idfa': idfa,
                     'appid': appid,
                     'username': username
                 },
                 'payID': sdkorderid
             })
         if payment.get('status', None) == 'SUCCESS':
             response = poem_pb.iTunesStoreReceiptResponse()
             response.transaction_id = receipt.transaction_id
             response.successed = True
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgtype, response))
     except InvalidReceipt:
         logger.warning('invalid receipt')
Exemplo n.º 5
0
def sdk_pay(entityID,
            orderid,
            amount,
            rechargegold,
            sdata,
            sdktype,
            goods,
            delay=0):
    from session.utils import sdk_username
    from sdk.payment import end_payment, get_payment
    GOOD_GOLD = 0

    if orderid:
        sdkorderid = sdk_username(sdktype, orderid)
        payment = get_payment(sdkorderid)
        if len(payment) == 0:
            logger.error('orderid {} not exists.'.format(orderid))
            return False
        # 如果交易完成直接返回成功
        if payment.get('status', None) == 'SUCCESS':
            return True

        if not end_payment(sdkorderid):
            logger.error('insert callback pay record failed %s' % sdkorderid)
            return False
        goodsid = payment["goodsid"]

    elif sdktype == poem_pb.SDK_YYB:
        sdkorderid = sdk_username(sdktype, '')
        ids = get_config(RechargeBySdktypeConfig).get(sdktype, [])
        configs = [get_config(RechargeConfig)[e.id] for e in ids]
        goodsid = max(configs, key=lambda o: o.amount).goodsid

    else:
        logger.error('orderid {} is empty.'.format(orderid))
        return False

    amount = amount / 10.0
    gold = rechargegold
    if goods == GOOD_GOLD:
        data = {
            "clientVersion": "",
            "amount": gold,
            "orderNO": sdkorderid,
            "_level": "",
            "_username": "",
            "_userID": 0,
            "_entityID": entityID,
            "result": 1
        }
        player = g_entityManager.get_player(entityID)
        if player:
            username = player.username
            userID = player.userID
            playername = player.name
            channel = player.channel
        else:
            p = Player.simple_load(entityID,
                                   ["username", "userID", "name", "channel"])
            username = p.username
            userID = p.userID
            playername = p.name
            channel = p.channel
        rs = pay_handler(entityID, username, goodsid, amount=amount)
        if not rs:
            return False
        get_gold = rs["get_gold"]
        username = rs["username"]
        level = rs["level"]
        if player:
            rsp = poem_pb.PayResult(success=True,
                                    roleID=entityID,
                                    userID=userID,
                                    payID=orderid,
                                    goods=0,
                                    count=get_gold,
                                    data=sdata)
            if delay == 0:
                g_playerManager.sendto(player.entityID,
                                       success_msg(msgid.SDK_PAY_RESULT, rsp))
            else:

                def do_send():
                    gevent.sleep(delay)
                    g_playerManager.sendto(
                        player.entityID, success_msg(msgid.SDK_PAY_RESULT,
                                                     rsp))

                gevent.spawn(do_send)
        data.update(_username=username, _level=level)
        data.update(_gold=get_gold)
        role_credit(**data)
        gm_logger.info({
            'pay': {
                'entityID': entityID,
                'amount': amount,
                'userID': userID,
                'playername': playername,
                'channel': channel,
                'gold': get_gold,
                'username': username,
                'transaction_id': orderid
            },
            'payID': sdkorderid
        })
        return True
    logger.error('unknown goods %d', goods)
    return False