コード例 #1
0
def createTransaction(request, goods):
    isMobile = request.mobile
    if isWechatBrowser(request.META['HTTP_USER_AGENT']):
        paymethod = Pay.getPayMethod(PayAccount.Nowpay)
    else:
        paymethod = Pay.getPayMethod()
    account = paymethod.getAccount(isMobile)
    nativetime = datetime.utcnow()
    localtz = pytz.timezone(settings.TIME_ZONE)
    localtime = localtz.localize(nativetime)
    extendtime = localtime + timedelta(days=-15)
    transaction, created = Transaction.objects.get_or_create(
        payaccount=account,
        subject=goods.name,
        user=request.user,
        goods=goods,
        fee=goods.price,
        state=1,
        createdDate__gt=extendtime,
        defaults={
            'createdDate': datetime.utcnow(),
            'payaccount': account,
            'subject': goods.name,
            'user': request.user,
            'goods': goods,
            'fee': goods.price,
            'state': 1
        })
    if created == True:
        transaction.save()

    return (transaction,
            paymethod.getPayUrl(request, account, isMobile, transaction))
コード例 #2
0
def alipay_wapreturn(request):
    paymethod = Pay.getPayMethod()
    account = paymethod.getAccount(True)
    pay = alipay.WapAlipay(pid=account.pid,
                           key=account.key,
                           seller_email=account.email)
    parameters = {k: unquote(v) for k, v in request.GET.iteritems()}
    if pay.verify_notify(**parameters):
        tradenum = request.GET.get('out_trade_no')
        try:
            transaction = Transaction.objects.get(
                id=getIdFromTradeNum(tradenum))
            if transaction.state != 2 and transaction.state != 5:
                transaction.paytradeNum = request.GET.get('trade_no')
                transaction.tradeStatus = 'TRADE_SUCCESS'
                transaction.paidDate = datetime.now().replace(
                    tzinfo=utc).astimezone(pytz.timezone(TIME_ZONE))
                transaction.state = 2
                transaction.save()

                transactionSuccessNotification(transaction)
        except Transaction.DoesNotExist:
            #TODO handle error case
            pass
        # add a page here
        if transaction.goods.type == 2:
            return redirect('user_assistant_order')
        return HttpResponse("Payment completed.")
    return HttpResponse("Error.")
コード例 #3
0
def pay_return(request):
    paymethod = Pay.getPayMethod(PayAccount.Nowpay)
    account = paymethod.getAccount(True)
    pay = Nowpay()
    parameters = {k: unquote(v) for k, v in request.GET.iteritems()}
    if parameters['appId'] == account.pid and parameters['signature'] ==\
        pay.doSign(parameters, ('signType', 'signature'), account.key):
        tradenum = request.GET.get('mhtOrderNo')
        try:
            transaction = Transaction.objects.get(id=getIdFromTradeNum(tradenum))
            if transaction.state != 2 and transaction.state != 5 and parameters['tradeStatus'] == 'A001':
                transaction.tradeStatus = 'TRADE_SUCCESS'
                transaction.paidDate = datetime.now().replace(tzinfo=utc).astimezone(pytz.timezone(TIME_ZONE))
                transaction.state = 2
                transaction.save()
                
                transactionSuccessNotification(transaction)
            
            #might add a page
            if transaction.goods.type == 2:
                return redirect('user_assistant_order')
            return HttpResponse("Payment completed.")
        except Transaction.DoesNotExist:
            #TODO handle error case
            pass
    return HttpResponse("Error.")
コード例 #4
0
def alipay_notify(request):
    try:
        paymethod = Pay.getPayMethod()
        account = paymethod.getAccount(True)
        pay = alipay.Alipay(pid=account.pid,
                            key=account.key,
                            seller_email=account.email)
        parameters = {k: v for k, v in request.POST.iteritems()}
        logger.info(
            "Received alipay notify at %s with parameters '%s'." %
            (datetime.now(), '&'.join(
                ['%s=%s' % (key, v) for key, v in request.POST.iteritems()])))
        if pay.verify_notify(**parameters):
            tradenum = request.GET.get('out_trade_no')
            try:
                transaction = Transaction.objects.get(
                    id=getIdFromTradeNum(tradenum))
                if transaction.tradeStatus == 'TRADE_FINISHED' or transaction.tradeStatus == 'TRADE_CLOSED':
                    # already completed transaction
                    return HttpResponse("success")
                if transaction.paytradeNum is None:
                    transaction.paytradeNum = request.GET.get('trade_no')
                transaction.tradeStatus = request.GET.get('trade_status')
                transaction.notifyid = request.GET.get('notify_id')
                transaction.buyerEmail = request.GET.get('buyer_email')
                transaction.buyeid = request.GET.get('buyer_id')
                if transaction.tradeStatus == 'TRADE_FINISHED' or transaction.tradeStatus == 'TRADE_SUCCESS':
                    transaction.paidDate = datetime.strptime(
                        request.GET.get('gmt_payment'),
                        TRANSACTION_TIME_FORMAT).replace(
                            tzinfo=pytz.timezone(TIME_ZONE))
                    transaction.state = 2
                    transactionSuccessNotification(transaction, False)
                elif transaction.tradeStatus == 'TRADE_CLOSED':
                    transaction.closedDate = datetime.strptime(
                        request.GET.get('gmt_close'),
                        TRANSACTION_TIME_FORMAT).replace(
                            tzinfo=pytz.timezone(TIME_ZONE))
                    transaction.state = 4
                transaction.save()
                return HttpResponse("success")
            except Transaction.DoesNotExist:
                #TODO handle error case
                pass
        else:
            logger.warn("alipay notify is invalid.")
    except Exception:
        logger.exception(
            "exception occurred when processing alipay notification.")
    return HttpResponse("Error.")
コード例 #5
0
def alipay_wapnotify(request):
    try:
        paymethod = Pay.getPayMethod()
        account = paymethod.getAccount(True)
        pay = alipay.WapAlipay(pid=account.pid,
                               key=account.key,
                               seller_email=account.email)
        parameters = {k: v for k, v in request.POST.iteritems()}
        logger.info(
            "Received alipay wap notify at %s with parameters '%s'." %
            (datetime.now(), '&'.join(
                ['%s=%s' % (key, v) for key, v in request.POST.iteritems()])))
        if pay.verify_notify(**parameters):
            tree = ElementTree.ElementTree(
                ElementTree.fromstring(
                    unquote(parameters['notify_data']).encode("utf-8")))
            notifydata = {node.tag: node.text for node in tree.iter()}
            tradenum = notifydata['out_trade_no']
            try:
                transaction = Transaction.objects.get(
                    id=getIdFromTradeNum(tradenum))
                if transaction.tradeStatus == 'TRADE_FINISHED' or transaction.tradeStatus == 'TRADE_CLOSED':
                    # already completed transaction
                    return HttpResponse("success")
                transaction.paytradeNum = notifydata['trade_no']
                transaction.tradeStatus = notifydata['trade_status']
                transaction.notifyid = notifydata['notify_id']
                transaction.buyeid = notifydata['buyer_id']
                transaction.paidDate = datetime.now().replace(tzinfo=utc).astimezone(pytz.timezone(TIME_ZONE)) if 'gmt_payment' not in notifydata else \
                    datetime.strptime(notifydata['gmt_payment'], TRANSACTION_TIME_FORMAT).replace(tzinfo=pytz.timezone(TIME_ZONE))
                transaction.state = 2 if notifydata[
                    'trade_status'] == 'TRADE_SUCCESS' else 5
                transaction.save()

                transactionSuccessNotification(transaction)
                return HttpResponse("success.")
            except Transaction.DoesNotExist:
                #TODO handle error case
                pass
        else:
            logger.warn("alipay wap notify is invalid.")
    except Exception:
        logger.exception(
            "exception occurred when processing alipay wap notification.")
    return HttpResponse("Error.")
コード例 #6
0
def pay_notify(request):
    try:
        paymethod = Pay.getPayMethod(PayAccount.Nowpay)
        account = paymethod.getAccount(True)
        pay = Nowpay()
        logger.info("Received nowpay asynchronized pure notify '%s'" %(request.body))
        parameters = {k: v[0] for k, v in parse_qs(request.body).iteritems()}
        parameters['mhtOrderName'] = unicode(parameters['mhtOrderName'], "utf-8")
        logger.info("Received nowpay asynchronized notify at %s with parameters '%s'." %(datetime.now(), 
            '&'.join(['%s=%s' % (key, v) for key,v in parameters.iteritems()])))
        if parameters['appId'] == account.pid:
#             and parameters['signature'] ==\
#             pay.doSign(parameters, ('mhtSignType', 'mhtSignature'), account.key):
            tradenum = parameters['mhtOrderNo']
            try:
                transaction = Transaction.objects.get(id=getIdFromTradeNum(tradenum))
                if transaction.tradeStatus == 'TRADE_FINISHED' or transaction.tradeStatus == 'TRADE_CLOSED':
                    # already completed transaction
                    return HttpResponse("success=Y")
                elif parameters['tradeStatus'] == 'A001':
                    if 'nowPayAccNo' in parameters:
                        transaction.paytradeNum = parameters['tradeStatus']
                    transaction.tradeStatus = 'TRADE_SUCCESS'
                    transaction.paidDate = datetime.now().replace(tzinfo=utc).astimezone(pytz.timezone(TIME_ZONE))
                    transaction.state = 2
                    transaction.save()
                
                    transactionSuccessNotification(transaction)
                    return HttpResponse("success=Y")
                logger.warn('Notify the transcation with error code %s.' %(parameters['tradeStatus']))
            except Transaction.DoesNotExist:
                #TODO handle error case
                pass
        else:
            logger.warn("nowpay notify is illegal.")
    except Exception, e:
        logger.error("exception occurred when processing nowpay notification.")
        logger.exception(e)
コード例 #7
0
def alipay_return(request):
    paymethod = Pay.getPayMethod()
    account = paymethod.getAccount(True)
    pay = alipay.Alipay(pid=account.pid,
                        key=account.key,
                        seller_email=account.email)
    parameters = {k: v for k, v in request.GET.iteritems()}
    if pay.verify_notify(**parameters):
        if request.GET.get('is_success') == 'T':
            tradenum = request.GET.get('out_trade_no')
            try:
                transaction = Transaction.objects.get(
                    id=getIdFromTradeNum(tradenum))
                if transaction.state != 2 and transaction.state != 5:
                    transaction.paytradeNum = request.GET.get('trade_no')
                    transaction.tradeStatus = request.GET.get('trade_status')
                    transaction.notifyid = request.GET.get('notify_id')
                    transaction.buyerEmail = request.GET.get('buyer_email')
                    transaction.buyeid = request.GET.get('buyer_id')
                    if transaction.tradeStatus == 'TRADE_FINISHED' or transaction.tradeStatus == 'TRADE_SUCCESS':
                        transaction.paidDate = datetime.strptime(
                            request.GET.get('notify_time'),
                            TRANSACTION_TIME_FORMAT).replace(
                                tzinfo=pytz.timezone(TIME_ZONE))
                        transaction.state = 2
                    transaction.save()

                    transactionSuccessNotification(transaction, False)
            except Transaction.DoesNotExist:
                #TODO handle error case
                pass
            # TODO add a page for it
            if transaction.goods.type == 2:
                return redirect('user_assistant_order')
            return HttpResponse("Payment completed.")
    return HttpResponse("Error.")