Beispiel #1
0
def p2p_transfer_withdraw(Req, CurrencyTitle, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 10:
        raise TransError("pay_requirments")
    if CurrencyTitle != "UAH":
        raise TransError("pay_requirments")

    Dict = {}
    CurrencyIn = Currency.objects.get(title=CurrencyTitle)
    Dict["amnt"] = str(Amnt)
    Dict["currency"] = CurrencyTitle

    try:
        Last = CardP2PTransfers.objects.filter(user=Req.user, status="processed").order_by('-id')[0]
        Dict["CardNumber"] = Last.CardNumber
        Dict["CardName"] = Last.CardName
    except:
        pass

    t = loader.get_template("ajax_form.html")
    Dict["action"] = "/finance/p2p_transfer_withdraw_submit"
    Dict["action_title"] = settings.p2p_transfer
    Dict["common_help_text"] = settings.p2p_attention_be_aware
    Form = CardP2PTransfersForm(initial=Dict, user=Req.user)
    Dict["form"] = Form.as_p()
    return tmpl_context(Req, t, Dict)
Beispiel #2
0
def liqpay_transfer_withdraw(Req, CurrencyTitle, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 10:
        raise TransError("pay_requirments")
    if CurrencyTitle != "UAH":
        raise TransError("pay_requirments")

    Dict = {}
    CurrencyIn = Currency.objects.get(title=CurrencyTitle)

    Account = get_account(user=Req.user, currency=CurrencyIn)
    Acc = Account.acc()
    if Acc.reference is None or len(Acc.reference) == 0:
        Account.reference = generate_key(settings.BANK_KEY_SALT)
        Account.save()

    Dict["amnt"] = str(Amnt)
    Dict["currency"] = "UAH"
    try:
        Last = LiqPayTrans.objects.filter(user=Req.user, status="processed").order_by('-id')[0]
        Dict["phone"] = Last.phone
    except:
        pass

    t = loader.get_template("ajax_form.html")
    Dict["action"] = "/finance/liqpay_transfer_withdraw_submit"
    Dict["action_title"] = settings.withdraw_transfer
    Dict["common_help_text"] = settings.liqpay_attention_be_aware
    Form = LiqPayTransferForm(initial=Dict, user=Req.user)

    Dict["form"] = Form.as_p()
    return tmpl_context(Req, t, Dict)
Beispiel #3
0
    def records(self, FromYear, FromMonth):
        url = self.__api_url + "p24api/rest_yur"
        Data = "<oper>cmt</oper><wait>10</wait><test>0</test><payment id=\"\" ><prop name=\"year\" value=\"%s\" /><prop name=\"month\" value=\"%s\" /></payment>\"" % (
            FromYear, FromMonth)
        signature = self.signature(Data)
        PrePostData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <request version=\"1.0\">\
<merchant><id>%s</id>\
<signature>%s</signature>\
</merchant><data>%s</data>\
</request>" % (self.__public_id, signature, Data)

        #$sign=encode_base64(sha1($merch_sign.$xml.$merch_sign));

        # Send HTTP POST request
        headers = {'User-Agent': 'Mozilla 5.10', 'Content-Type': 'text/xml'}
        request = urllib2.Request(Url, PrePostData, headers)

        response = urllib2.urlopen(request)
        xml = response.read()
        doc = minidom.parseString(xml)
        print xml
        Data = xml.split("<data>")[1].split("</data>")[0]
        CalcSign = self.signature(Data)
        if CalcSign != Sign:
            raise TransError("Invalid Signature %s calculated %s" %
                             (CalcSign, Sign))

        return Decimal(Balance)
Beispiel #4
0
def confirm_withdraw_emoney(Req, S, PrivateKey):
    Transfer = TransOut.objects.get(user=Req.user,
                                    confirm_key=S,
                                    status='created')

    IsCancel = Req.REQUEST.get("do", None)
    if Transfer.status == "created" and IsCancel is not None:
        Transfer.status = "canceled"
        Transfer.save()
        order = Transfer.order
        order.status = "canceled"
        order.save()
        add_trans(order.transit_2, Transfer.amnt, Transfer.currency, order.transit_1,
                  order, "canceled", S, False)

        t = loader.get_template("simple_msg.html")
        Dict = {}
        Dict["title"] = settings.withdraw_cancel
        Dict["simple_msg"] = settings.withdraw_msg_cancel
        caching().delete("balance_" + str(Req.user.id))
        return tmpl_context(Req, t, Dict)

    if Transfer.status != "created":
        raise TransError("hacker " + Req.user.username)
        ##add trans may be there
    Transfer.status = "processing"
    Transfer.sign_record(PrivateKey)
    Transfer.save()
    t = loader.get_template("ajax_simple_msg.html")
    Dict = {}
    Dict["title"] = settings.withdraw_ok
    Dict["simple_msg"] = settings.withdraw_msg_ok
    return tmpl_context(Req, t, Dict)
Beispiel #5
0
    def api_callback_pay(self, Params, callback):
        #<input type="hidden" name="PAYEE_ACCOUNT" value="U9007123">
        #<input type="hidden" name="PAYMENT_AMOUNT" value="109.99">
        #<input type="hidden" name="PAYMENT_UNITS" value="USD">
        #<input type="hidden" name="PAYMENT_BATCH_NUM" value="680">
        #<input type="hidden" name="PAYER_ACCOUNT" value="U110007">
        #<input type="hidden" name="TIMESTAMPGMT" value="1212244190">
        #<input type="hidden" name="ORDER_NUM" value="9801121">
        #<input type="hidden" name="CUST_NUM" value="2067609">
        #<input type="hidden" name="PAYMENT_ID" value="NULL">
        #<input type="hidden"
        #name="V2_HASH" value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
        perfectmoney = PerfectMoney(self.__public_id, self.__password)

        #def check(self, payee, payer, amount, units, batch_number, secret, timestamp, payment_id, v2_hash):
        if not perfectmoney.check(
                Params["PAYEE_ACCOUNT"], Params["PAYER_ACCOUNT"],
                float(Params["PAYMENT_AMOUNT"]), Params["PAYMENT_UNITS"],
                Params["PAYMENT_BATCH_NUM"], self.__password2,
                Params["TIMESTAMPGMT"], Params["PAYMENT_ID"],
                Params["V2_HASH"]):
            raise TransError("Invalid Signature")
        callback(int(Params["ORDER_NUM"]), self.comis, self.__password)
        Response = HttpResponse(json.JSONEncoder().encode({
            "status": True,
            "signature": True
        }))
        Response['Content-Type'] = 'application/json'
        return Response
Beispiel #6
0
def auth(s_secret, nstr):
    # raise if nstr contains anything but numbers
    int(nstr)
    Time = time.time()
    tm = int(Time / 30)
    secret = base64.b32decode(s_secret)
    # try 30 seconds behind and ahead as well
    codes = []
    for ix in [-6,-5,-4,-3,-2,-1, 0, 1, 2,3,4,5,6]:
        # convert timestamp to raw bytes
        b = struct.pack(">q", tm + ix)
        # generate HMAC-SHA1 from timestamp based on secret key
        hm = hmac.HMAC(secret, b, hashlib.sha1).digest()
        # extract 4 bytes from digest based on LSB
        offset = ord(hm[-1]) & 0x0F
        truncatedHash = hm[offset:offset+4]
        # get the code from it
        code = struct.unpack(">L", truncatedHash)[0]
        code &= 0x7FFFFFFF
        code %= 1000000
        Res = "%06d" % code
        codes.append(Res)
        if Res == nstr:
            return True
    raise TransError("%s time -  %s" % (nstr, Time ) )
    return False
Beispiel #7
0
    def generate_pay_request(self, User, Amount):
        AmountStr = Decimal(Amount)
        user_account = Accounts.objects.get(user=User,
                                            currency=self.__currency)
        if AmountStr < 0:
            raise TransError("NegativeAmount")

        if AmountStr < self.__min_amnt:
            raise TransError("MinAmount")

        order = Orders(user=User,
                       currency1=self.__currency,
                       currency2=self.__currency,
                       sum1_history=AmountStr,
                       sum2_history=AmountStr,
                       sum1=AmountStr,
                       sum2=AmountStr,
                       transit_1=self.__transit_account,
                       transit_2=user_account,
                       trade_pair=self.__trade_pair,
                       status="processing")
        order.save()
        ResultUrl = self.generate_result_url(order, User, Amount)
        ServerResultUrl = self.generate_api_result_url(order, User, Amount)
        #
        Payment = "amt=%s&ccy=%s&details=%s&ext_details=%s&pay_way=privat24&order=%s&merchant=%s" % (
            str(AmountStr), self.__currency.title, self.description, "none",
            str(order.id), self.__public_id)
        signature = self.signature(Payment)
        Dict = {
            "signature": signature,
            "public_key": self.__public_id,
            "order_id": str(order.id),
            "result_url": ResultUrl,
            "type": "privat24",
            "ext_details": "none",
            "description": self.description,
            "currency": self.__currency.title,
            "server_url": ServerResultUrl,
            "amount": str(AmountStr)
        }

        Response = HttpResponse(json.JSONEncoder().encode(Dict))
        Response['Content-Type'] = 'application/json'
        return Response
Beispiel #8
0
    def pay2p(self, OrderId, ToCard, Amnt):
        self.__my_orderid = str(OrderId)

        Data = "<oper>cmt</oper><wait>10</wait>\
<test>0</test><payment id=\"%s\"><prop name=\"b_card_or_acc\" value=\"%s\" />\
<prop name=\"ccy\" value=\"%s\" />\
<prop name=\"amt\" value=\"%s\" />\
<prop name=\"phone\" value=\"%s\" />\
<prop name=\"details\" value=\"%s\" />\
</payment>" % (self.__my_orderid, ToCard, self.__currency.title, Amnt,
               self.__phone, self.description)

        signature = self.signature(Data)
        PrePostData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <request version=\"1.0\">\
                   <merchant><id>%s</id>\
                   <signature>%s</signature>\
                   </merchant><data>%s</data>\
                   </request>" % (self.__public_id, signature, Data)

        #$sign=encode_base64(sha1($merch_sign.$xml.$merch_sign));

        # Send HTTP POST request
        headers = {'User-Agent': 'Mozilla 5.10', 'Content-Type': 'text/xml'}
        request = urllib2.Request(self.__api_url + "p24api/pay_pb",
                                  PrePostData, headers)

        response = urllib2.urlopen(request)

        xml = response.read()
        doc = minidom.parseString(xml)
        Sign = doc.getElementsByTagName("signature")[0].childNodes[0].nodeValue

        Payment = doc.getElementsByTagName("payment")[0]
        Data = xml.split("<data>")[1].split("</data>")[0]

        CalcSign = self.signature(Data)
        if CalcSign != Sign:
            raise TransError("Invalid Signature %s calculated %s" %
                             (CalcSign, Sign))

        if Payment.getAttribute("state") == "1":
            return True

        raise TransError("Invalid State %s " % (xml))
Beispiel #9
0
    def check_payment(self, OrderId, verbose=False):
        self.__my_orderid = str(OrderId)
        #<?xml version="1.0" encoding="UTF-8"?>
        #<request version="1.0">
        #<merchant>    <id>99137</id>
        #<signature>b45d66d192cb258ba1661a978e08cfe1ca171535</signature>
        #</merchant>
        #<data>   <oper>cmt</oper>   <wait>0</wait>    <test>0</test>    <payment>
        #<prop name="order" value="PAY-15893" />    </payment> </data> </request>

        Data = "<oper>cmt</oper><wait>10</wait><test>0</test><payment><prop name=\"order\" value=\"%s\" /></payment>" % (
            self.__my_orderid)

        signature = self.signature(Data)
        PrePostData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <request version=\"1.0\">\
                   <merchant><id>%s</id>\
                   <signature>%s</signature>\
                   </merchant><data>%s</data>\
                   </request>" % (self.__public_id, signature, Data)

        if verbose:
            print " send data"
            print PrePostData
        #$sign=encode_base64(sha1($merch_sign.$xml.$merch_sign));

# Send HTTP POST request
        headers = {'User-Agent': 'Mozilla 5.10', 'Content-Type': 'text/xml'}
        request = urllib2.Request(self.__api_url + "p24api/ishop_pstatus",
                                  PrePostData, headers)
        response = urllib2.urlopen(request)
        #<payment order="PAY-15893" state="not found" />
        xml = response.read()
        if verbose:
            print xml
        doc = minidom.parseString(xml)
        Sign = doc.getElementsByTagName("signature")[0].childNodes[0].nodeValue
        Payment = doc.getElementsByTagName("payment")[0].getAttribute("state")
        Data = xml.split("<data>")[1].split("</data>")[0]
        if verbose:
            print "calc data"
            print "'%s' " % (Data)
        CalcSign = self.signature(Data)

        if CalcSign != Sign:
            raise TransError("Invalid Signature %s calculated %s" %
                             (CalcSign, Sign))

        if Payment == "ok":
            return 1
        if Payment == "fail":
            return 0
        if Payment == "not found":
            return 0
        return -1
Beispiel #10
0
def bank_transfer_withdraw(Req, CurrencyTitle, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 10:
        raise TransError("pay_requirments")
    if CurrencyTitle != "UAH":
        raise TransError("pay_requirments")

    Dict = {}
    CurrencyIn = Currency.objects.get(title=CurrencyTitle)
    # TODO add working with ref through Account class
    Account = Accounts.objects.get(user=Req.user, currency=CurrencyIn)
    if Account.reference is None or len(Account.reference) == 0:
        Account.reference = generate_key(settings.BANK_KEY_SALT)
        Account.save()
    Dict["amnt"] = str(Amnt)
    Dict["currency"] = "UAH"
    t = loader.get_template("ajax_form.html")
    Dict["action"] = "/finance/bank_transfer_withdraw_submit"
    Dict["action_title"] = settings.withdraw_transfer
    Dict["common_help_text"] = settings.attention_be_aware
    Form = BankTransferForm(initial=Dict, user=Req.user)
    Dict["form"] = Form.as_p()
    return tmpl_context(Req, t, Dict)
Beispiel #11
0
def p2p_deposit(Req, Cur, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 1:
        raise TransError("pay_requirments")
    Dict = {}
    t = loader.get_template("p2p_transfer_req.html")
    CurrencyIn = Currency.objects.get(title=Cur)
    Account = get_account(user=Req.user, currency=CurrencyIn)
    Dict["account"] = P2P_DEPOSIT_OPTS[Cur]
    Acc = Account.acc()
    if Acc.acc().reference is None or len(Acc.acc().reference) == 0:
        Account.reference = generate_key("bank_pp", 16)
        Account.save()
    Dict["description"] = _(u"Оплата информационных услуг в счет публичного договора #" + Acc.reference)
    Dict["amnt"] = str(Amnt)

    return tmpl_context(Req, t, Dict)
Beispiel #12
0
def bank_deposit(Req, Cur, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 1:
        raise TransError("pay_requirments")
    Dict = {}
    t = loader.get_template("bank_transfer_req.html")
    Dict["okpo"] = settings.BANK_UAH_OKPO
    Dict["mfo"] = settings.BANK_UAH_MFO
    Dict["account"] = settings.BANK_UAH_ACCOUNT
    CurrencyIn = Currency.objects.get(title=Cur)
    # TODO add working with ref through Account class
    Account = Accounts.objects.get(user=Req.user, currency=CurrencyIn)
    if Account.reference is None or len(Account.reference) == 0:
        Account.reference = generate_key(settings.BANK_KEY_SALT)
        Account.save()
    Dict["description"] = _(u"Оплата информационных услуг в счет публичного договора #%s" + Account.reference)
    Dict["amnt"] = str(Amnt)

    return tmpl_context(Req, t, Dict)
Beispiel #13
0
    def api_callback_pay(self, Params, OrderId):

        Payment = Params["payment"]
        signature = self.signature(Payment)
        Signature = Params["signature"]
        if signature != Signature:
            raise TransError("Invalid Signature")

        for Val in Payment.split("&"):
            [Name, Value] = Val.split("=")
            if Name == "state":
                Status = Value
                break

        if Status == "fail":
            order = Orders.objects.get(id=int(OrderId))
            order.status = "order_cancel"
            order.save()
            Response = HttpResponse(json.JSONEncoder().encode({
                "status": True,
                "signature": True
            }))
            Response['Content-Type'] = 'application/json'
            return Response

        if Status == "wait":
            Response = HttpResponse(json.JSONEncoder().encode({
                "status": True,
                "signature": True
            }))
            Response['Content-Type'] = 'application/json'
            return Response

        ##TODO add system message
        if Status == "ok":
            process_p24_in(int(OrderId), self.description, self.comis)
            Response = HttpResponse(json.JSONEncoder().encode({
                "status": True,
                "signature": True
            }))
            Response['Content-Type'] = 'application/json'
            return Response

        if Status == "test":
            order = Orders.objects.get(id=int(OrderId), status="created")
            order.status = "processing"
            order.save()
            add_trans(order.transit_1, order.sum1, self.__currency,
                      order.transit_2, order, "payin", OutOrderId, False)
            Comission = order.sum1 * self.comis
            add_trans(order.transit_2, Comission, self.__currency,
                      order.transit_1, order, "comission", OutOrderId, False)
            DebCred = P24TransIn(description=self.description,
                                 currency=self.__currency,
                                 amnt=order.sum1,
                                 user=order.user,
                                 comission=Comission,
                                 user_accomplished_id=1,
                                 status="processed",
                                 debit_credit="in",
                                 confirm_key=Signature,
                                 order=order)
            DebCred.save()
            order.status = "processed"
            order.save()
            Response = HttpResponse(json.JSONEncoder().encode({
                "status": True,
                "signature": True
            }))
            Response['Content-Type'] = 'application/json'
            return Response
Beispiel #14
0
def liqpay_deposit(Req, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 100:
        raise TransError("pay_requirments")
    pay_invoice = liqpay("ru", "UAH")
    return HttpResponse(pay_invoice.generate_button(Amnt))
Beispiel #15
0
def p24_deposit(Req, Amnt):
    amnt = Decimal(Amnt)
    if amnt < 100:
        raise TransError("pay_requirments")
    pay_invoice = p24("UAH", "https://api.privatbank.ua/", settings.P24_MERCHID2, settings.P24_PASSWD2)
    return HttpResponse(pay_invoice.generate_button(Amnt))
Beispiel #16
0
    def generate_pay_request(self, User, Amount):
        currency = ""
        if self.__currency.title == "USD":
            currency = "USD"
        elif self.__currency.title == perfect_money_sdk.str_class_name(
        ) + "_eur":
            currency = "EUR"
        elif self.__currency.title == "EUR":
            currency = "EUR"
        elif self.__currency.title == perfect_money_sdk.str_class_name(
        ) + "_usd":
            currency = "USD"

        AmountStr = Decimal(Amount)
        user_account = Accounts.objects.get(user=User,
                                            currency=self.__currency)
        if AmountStr < 0:
            raise TransError("NegativeAmount")

        if AmountStr < self.__min_amnt:
            raise TransError("MinAmount")

        order = Orders(user=User,
                       currency1=self.__currency,
                       currency2=self.__currency,
                       price=AmountStr,
                       sum1_history=AmountStr,
                       sum2_history=AmountStr,
                       sum1=AmountStr,
                       sum2=AmountStr,
                       transit_1=self.__transit_account,
                       transit_2=user_account,
                       trade_pair=self.__trade_pair,
                       status="processing")
        order.save()
        ResultUrl = self.generate_result_url(order, User, Amount)
        ServerResultUrl = self.generate_api_result_url(order, User, Amount)

        Dict = {
            "public_key":
            self.__public_id,
            "order_id":
            str(order.id),
            "result_url":
            ResultUrl,
            "type":
            "perfectmoney",
            "ext_details":
            "none",
            "description":
            self.description,
            "currency":
            currency,
            "server_url":
            ServerResultUrl,
            "server_url_fail":
            self.generate_api_result_url_fail(order, User, Amount),
            "amount":
            "%.2f" % float(AmountStr)
        }

        Response = HttpResponse(json.JSONEncoder().encode(Dict))
        Response['Content-Type'] = 'application/json'
        return Response