Skip to content

Commit

Permalink
Billing base
Browse files Browse the repository at this point in the history
  • Loading branch information
MJafarMashhadi committed Feb 28, 2016
1 parent 97d387f commit 9b525f0
Show file tree
Hide file tree
Showing 11 changed files with 214 additions and 0 deletions.
5 changes: 5 additions & 0 deletions AIC_site/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@
"django.contrib.staticfiles",
"import_export",
"2016_template",
'billing',
'storages',
'queued_storage',
"mezzanine.boot",
Expand Down Expand Up @@ -432,3 +433,7 @@
},
}
}

BANK_USERNAME = os.environ.get('BANK_USERNAME', '')
BANK_PASSWORD = os.environ.get('BANK_PASSWORD', '')
BANK_GROUP_ID = os.environ.get('BANK_GROUP_ID', '')
21 changes: 21 additions & 0 deletions base/migrations/0039_auto_20160228_1113.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import base.models
import django.core.files.storage


class Migration(migrations.Migration):

dependencies = [
('base', '0038_auto_20160227_1942'),
]

operations = [
migrations.AddField(
model_name='team',
name='paid',
field=models.BooleanField(default=False),
),
]
1 change: 1 addition & 0 deletions base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class Team(models.Model):

will_come = models.PositiveSmallIntegerField(verbose_name=_("will come to site"), choices=WILL_COME_CHOICES,
default=2)
paid = models.BooleanField(default=False)

def __unicode__(self):
return 'Team%d(%s)' % (self.id, self.name)
Expand Down
Empty file added billing/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions billing/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib import admin
from .models import Transaction


@admin.register(Transaction)
class TransactionAdmin(admin.ModelAdmin):
readonly_fields = ['user', 'amount', 'status', 'our_id', 'order_id', 'bank', 'reference_id', 'created', 'updated']
list_display = ['user', 'amount', 'status', 'bank', 'reference_id', 'updated']
30 changes: 30 additions & 0 deletions billing/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Transaction',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('amount', models.PositiveSmallIntegerField()),
('status', models.CharField(max_length=1, choices=[(b'u', b'unknown'), (b'v', b'valid'), (b'c', b'cancelled')])),
('our_id', models.CharField(max_length=100)),
('order_id', models.CharField(max_length=100, null=True, blank=True)),
('bank', models.CharField(max_length=1, choices=[(b'2', b'tejarat'), (b'1', b'mellat')])),
('reference_id', models.CharField(max_length=100)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(related_name='transactions', to=settings.AUTH_USER_MODEL)),
],
),
]
Empty file added billing/migrations/__init__.py
Empty file.
115 changes: 115 additions & 0 deletions billing/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
from django.db import models
from base.models import Member
from django.utils.crypto import get_random_string
from suds.client import Client
from django.core.urlresolvers import reverse


class Transaction(models.Model):
STATE = (
('u', 'unknown'),
('v', 'valid'),
('c', 'cancelled')
)
BANK = {
'mellat': 1, 'tejarat': 2
}

user = models.ForeignKey(Member, related_name='transactions')
amount = models.PositiveSmallIntegerField()
status = models.CharField(choices=STATE, max_length=1)
our_id = models.CharField(max_length=100)
order_id = models.CharField(max_length=100, null=True, blank=True)
bank = models.CharField(max_length=1, choices=[(str(v), k) for k,v in BANK.items()])
reference_id = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

@classmethod
def begin_transaction(cls, user, code_melli, amount, bank='mellat'):
"""
:param user:
:param amount: in rials
:param bank: 'mellat' or 'tejarat'
:return: (url, transaction)
"""
random_string = get_random_string(length=100)
t = Transaction.objects.create(
user=user,
amount=amount,
status='u',
bank=bank,
our_id=random_string
)
from django.conf import settings
username = settings.BANK_USERNAME
password = settings.BANK_PASSWORD
group_id = settings.BANK_GROUP_ID

phone = user.phone_number
if len(phone) < 7:
phone = '%s%s' % ('0'*(7-len(phone)), phone)
elif len(phone) > 7:
phone = phone[:7]

mobile = user.phone_number
if mobile[:2] != '09':
mobile = '09{}'.format(mobile)

params = {
'groupid': group_id,
'username': username,
'password': password,
'bankid': cls.BANK[bank],
'id2': random_string,
'callbackurl': reverse('bank_callback') + '?',
'nc': code_melli,
'name': user.first_name,
'family': user.last_name,
'tel': phone,
'mobile': mobile,
'email': user.email,
'amount': amount,
'memo': t.pk,
}

def call_webservice(params):
cl = Client('http://payment.sharif.ir/research/ws.asmx')
return cl.service.Request(params)

rescode, order_id = call_webservice(params).split(',')
t.order_id = order_id
t.save()
if rescode == '0':
return 'http://payment.sharif.ir/research/submit.aspx?orderid={}'.format(order_id), t
else:
t.status = 'c'
t.save()
return '', t

def update_status(self):
from django.conf import settings
username = settings.BANK_USERNAME
password = settings.BANK_PASSWORD
group_id = settings.BANK_GROUP_ID

params = {
'groupid': group_id,
'username': username,
'password': password,
'bankid': self.BANK[self.bank],
'orderid': self.order_id
}
def call_webservice(params):
cl = Client('http://payment.sharif.ir/research/ws.asmx')
return cl.service.Status(params)

vercode, reference_id = call_webservice(params).split(':')
self.reference_id = reference_id
if vercode == '0':
self.status = 'v'
else:
self.status = 'c'
self.save()

return reference_id
8 changes: 8 additions & 0 deletions billing/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-

from django.conf.urls import patterns, url

urlpatterns = patterns(
'billing.views',
url("^bankcb$", 'bank_callback', name='bank_callback'),
)
25 changes: 25 additions & 0 deletions billing/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.core.exceptions import PermissionDenied
from .models import Transaction
from django.shortcuts import redirect


def bank_callback(request):
our_id = request.GET.get('id2', None)
if not our_id:
raise PermissionDenied()

try:
transaction = Transaction.objects.get(our_id=our_id)
except Transaction.DoesNotExist:
raise PermissionDenied()

transaction.update_status()
success = True
if transaction.status == 'v':
transaction.user.team.set_paid(True)
else:
success = False

# TODO: save success somewhere in session or messages or something

return redirect('my_team')
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,4 @@ tqdm==3.8.0
tzlocal==1.2
websocket-client==0.35.0
wsgiref==0.1.2
suds==0.4

0 comments on commit 9b525f0

Please sign in to comment.