예제 #1
0
def instamojo_response(request):
    user = request.user
    payment_id = request.GET.get('payment_id')
    payment_request_id = request.GET.get('payment_request_id')

    api_key = settings.API_KEY
    auth_token = settings.AUTH_TOKEN

    api = Instamojo(api_key=api_key,auth_token=auth_token)
    response = api.payment_request_payment_status(payment_request_id,payment_id)
    if response['payment_request']['status'] == "Completed":
        paid_amount = response['payment_request']['payment']['amount']
        order = Order.objects.get(pk=payment_request_id)
        if order.amount == float(paid_amount) and order.order_id == payment_request_id:
            order.tracking_id = response['payment_request']['payment']['payment_id']
            order.save()
            cart_itmes = CourseEnrollment.objects.filter(order=order)
            for item in cart_itmes:
                setattr(item,'course_enrolled',True)
                item.save()
                send_mail('emails/checkout_success.html', {'user': item.owner_of_item(), 'item': item.course.course_name },
                          '*****@*****.**', [item.owner_of_item().email])
                send_mail('emails/notify_mentor.html',
                          {'user': item.owner_of_item(), 'mentor':item.course.course_user.user_first_name, 'item': item.course.course_name },
                          '*****@*****.**', [item.course.course_user.email, '*****@*****.**'])

            return render_to_response('portal/cart/checkout_result.html', {'success': 'success'})
        else:
            return render_to_response('portal/cart/checkout_result.html', {'failure': 'failure'})
    else:
        return render_to_response('portal/cart/checkout_result.html', {'failure': 'fail'})
예제 #2
0
def add_user():
    api = Instamojo(api_key='4dcb3d45a65808a290e7b79336b4c5be',
                auth_token='bade10ebfbac041b362a82611d0d194f')
    try:
        token = api.auth(request.form['username'],request.form['password'])
    except:
        token = 'bade10ebfbac041b362a82611d0d194f'
    try:
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
        twitter_id = str(api.get_user(request.form['username']).id_str)
        conn = opendb()
        c = conn.cursor()
        c.execute('SELECT * FROM Users')
        users = c.fetchall()
        flag = True
        for user in users:
            if str(user[1]) == twitter_id:
                flag = False
        if flag:
            c.execute("INSERT INTO Users VALUES ('%s','%s','%s')"%(request.form['twitter_handle'],twitter_id,token))
        closedb(conn)
        herokuapp.processes['worker'][0].restart()
        return 'Thanks. User created : <a href="/"> Home </a>'
    except:
        return 'Sorry. Some Error : <a href="/"> Home </a>'
예제 #3
0
def checkout_items(request):
    user = request.user
    total_cost = 0

    for item_order in request.POST.getlist('order'):
        item = CourseEnrollment.objects.get(pk=item_order)
        total_cost = total_cost + item.course.course_fees

    if total_cost > 0:
        api_key = settings.API_KEY
        auth_token = settings.AUTH_TOKEN

        api = Instamojo(api_key=api_key,auth_token=auth_token)
        api_request = api.payment_request_create(
            purpose="ThinkFOSS transaction",
            send_email=True,
            email=user.email,
            amount=total_cost,
            redirect_url="http://www.thinkfoss.com/register/user/portal/student/instamojoresponse/"
        )

        order_id = api_request['payment_request']['id']
        current_order = Order.objects.start_checkout(order_id, total_cost, user)
        for item_order in request.POST.getlist('order'):
            item = CourseEnrollment.objects.get(pk=item_order)
            item.order = current_order
            item.save()

        return redirect(api_request['payment_request']['longurl'])
    else:
        # Free course
        for item_order in request.POST.getlist('order'):
            item = CourseEnrollment.objects.get(pk=item_order)
            setattr(item,'course_enrolled',True)
            item.save()
            send_mail('emails/checkout_success.html', {'user': request.user, 'item': item.course.course_name },
                      '*****@*****.**', [user.email])
            send_mail('emails/notify_mentor.html',
                      {'user': request.user, 'mentor':item.course.course_user.user_first_name , 'item': item.course.course_name },
                      '*****@*****.**', [item.course.course_user.email, '*****@*****.**'])

            return render_to_response('portal/cart/checkout_result.html', {'success': 'success'})
예제 #4
0
    def on_status(self, status):
        
        text = status.text.encode('ascii','ignore')

        if "#sell " in text:
            twitter_id = str(status.author.id_str)
            twitter_handle = str(status.author.screen_name)
            try:
                m = re.match(pattern, text)
                params =  m.groups()
                instamojo_auth = user_details[twitter_id]["instamojo_auth"]
                
                api = Instamojo(api_key='4dcb3d45a65808a290e7b79336b4c5be',
                            auth_token=instamojo_auth)

                # Create a Instamojo Link.
                response = api.link_create(title=params[0],
                                   description=params[1],
                                   base_price=params[2],
                                   currency=params[3])
                
                # URL of the created link
                url =  str(response['link']['url'])

                #Printing to console
                print twitter_handle
                print text
                print url
                
                # Saving details to Tweets database
                conn = opendb()
                c = conn.cursor()
                c.execute("INSERT INTO Tweets VALUES ('%s','%s','%s')"%(twitter_handle,text,url))
                closedb(conn)
                print "Database Updated"
                
            except:
                pass
        return True
예제 #5
0
class TestApi(unittest.TestCase):

    def setUp(self):
        self.api = Instamojo(
            api_key='foo',
            auth_token='bar'
        )

    def test_debug(self):
        response = self.api.debug()

        self.assertEqual(isinstance(response, dict), True)
        self.assertEqual('success' in response, True)
        self.assertEqual(response.get('success'), False)
예제 #6
0
	def __init__(self):

		self.api = Instamojo(app_id=conf.api_id, token=conf.token)
		
		self.TITLE = 0
		self.BASE_PRICE = 1
		self.CURRENCY = 2
		self.DESCRIPTION = 3
		self.QUANTITY = 4
		self.START_DATE = 5
		self.END_DATE = 6
		self.VENUE = 7
		self.TIMEZONE = 8
		self.REDIRECT_URL = 9
		self.WEBHOOK_URL = 10
		self.NOTE = 11
예제 #7
0
from django.shortcuts import render, redirect, render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from tracker.models import basictracker, bisceptracker, chesttracker, userprofile_extended, backtracker, hiptracker, thightracker, shouldertracker, photos, subscription
from tracker.forms import basictrackerForm, bisceptrackerForm, chesttrackerForm, userprofile_extended_goalsettings_Form, userprofile_extended_profilesettings_Form, backtrackerForm, hiptrackerForm, thightrackerForm, shouldertrackerForm, photosForm, subscriptionForm
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from datetime import datetime, timedelta, timezone
from instamojo import Instamojo
from django.contrib import messages

api = Instamojo(api_key='b01a80d566585ce4c10fd76e72ee052d',
                auth_token='3d03b6076af55593df904d15f255a3e6',
                endpoint='https://test.instamojo.com/api/1.1/')


def indexpage(request):
    context = {}
    return render(request, "index.html", context)


def homepage(request):
    if request.user.is_authenticated():
        template = "loggedin_base.html"
        registered_user = '******'

        date_now = datetime.now(timezone.utc)
        obj = subscription.objects.filter(user_id=request.user)
        for i in obj:
            print("*********")
            print(i.subscription_startdate)
예제 #8
0
 def setUp(self):
     self.api = Instamojo(
         api_key='foo',
         auth_token='bar'
     )
예제 #9
0
    def get_redirect_url(self, *args, **kwargs):
        # get payment details from payment id
        payment_id = self.request.GET.get('payment_id', '')
        if not payment_id:
            return reverse('profile_membership') + "?status=fail"

        im = PaymentGateway.objects.get(name='Instamojo')
        api = Instamojo(
            api_key=im.api_key,
            auth_token=im.auth_token
        )
        resp = api.payment_detail(payment_id=payment_id)
        print(resp)
        payment_resp = resp.get('payment', {})
        print(payment_resp)

        if not resp.get('success', False) or not payment_resp:
            return reverse('profile_membership') + "?status=fail"

        # create payment instance
        payment, created = Payment.objects.get_or_create(
            gateway=im,
            payment_id=payment_id,
            ptype=PaymentType.objects.get(name__iexact='membership'),
        )
        payment.user_id = self.request.user.pk
        payment.amount = float(payment_resp.get('amount'))
        payment.status = 'r'  # received
        payment.status_pg = payment_resp.get('status')
        payment.raw_details = json.dumps(payment_resp)
        payment.save()

        # check pament status
        success = (self.request.GET.get('status') == 'success' and
                   payment_resp.get('status') == 'Credit')
        # if success create membership instance
        if success:
            now = timezone.now()
            profile = self.request.user.profile
            membership = Membership(
                profile=profile,
                from_date=now,
                to_date=now + timedelta(days=365 * 2),
                payment=payment
            )
            membership.save()

            membershipapplication = profile.membershipapplication
            membershipapplication.status = 'a'
            membershipapplication.save()

            messages.info(
                self.request, 'Your payment has been successfully received.')

            # send email to staff and user
            emailer.send_payment_confirmation_email(
                user=self.request.user, instance=payment)
            return reverse('profile_membership') + "?status=success"
        # else show error
        else:
            messages.info(
                self.request, 'Something went wrong when processing your payment. Please contact us at [email protected]')
            return reverse('profile_membership') + "?status=fail"
예제 #10
0
class InstamojoHelper:


	def __init__(self):

		self.api = Instamojo(app_id=conf.api_id, token=conf.token)
		
		self.TITLE = 0
		self.BASE_PRICE = 1
		self.CURRENCY = 2
		self.DESCRIPTION = 3
		self.QUANTITY = 4
		self.START_DATE = 5
		self.END_DATE = 6
		self.VENUE = 7
		self.TIMEZONE = 8
		self.REDIRECT_URL = 9
		self.WEBHOOK_URL = 10
		self.NOTE = 11


	def create_offers_from_file(self,inp_file):

		status_list = []

		with open(inp_file, mode='r',buffering=1) as offer_file:

			reader = csv.reader(offer_file,delimiter=',')
			row_number = 1

			for row in reader:
				validated_line = self._validate_line(row,row_number)
				status_list.append(validated_line)

				if validated_line['status']:
					response = self._create_offer(row)
					print response
				row_number += 1

		print status_list


	def _validate_line(self,line,row_number):

		status_dict = {}

		CURRENCIES = ['INR','USD']
		MAX_COLUMN_LENGTH = 11

		status_dict['row_number'] = row_number

		# check if the row is empty
		if len(line) == 0: 
			status_dict['status'] = False 
			status_dict['message'] = 'offer line is empty '	


		# check if the all the columns are present
		elif len(line) < 12:
			status_dict['status'] = False 
			status_dict['message'] = 'offer line does not have all the columns '	

		# check if the all the columns are present
		elif len(line[self.TITLE]) == 0 or len(line[self.BASE_PRICE]) == 0 or len(line[self.CURRENCY]) == 0:

			status_dict['status'] = False 
			status_dict['message'] = 'required columns does not exist'	

		# check if the title has 200 characters
		elif len(line[self.TITLE].strip()) > 200:
			status_dict['status'] = False 
			status_dict['message'] = 'offer line does not have title or base price or currency type mentioned'	

		# check currency 
		elif line[self.CURRENCY] not in CURRENCIES:
			status_dict['status'] = False 
			status_dict['message'] = 'right currency is not mentioned'	

		# check quantity
		elif len(line[self.QUANTITY]) > 0 and int(line[self.QUANTITY]) < 0:
			status_dict['status'] = False 
			status_dict['message'] = 'Quantity mentioned is < than 0'	


		# check start date
		elif len(line[self.START_DATE]) > 0:
			try:
				check_start_date = datetime.strptime(line[self.START_DATE],'%Y-%m-%d %H:%M')
			except ValueError as e:
				status_dict['status'] = False 
				status_dict['message'] = 'start date in invalid format'

		# check end date
		elif len(line[self.END_DATE]) > 0:
			try:
				check_end_date = datetime.strptime(line[self.END_DATE],'%Y-%m-%d %H:%M')
			except ValueError as e:
				status_dict['status'] = False 
				status_dict['message'] = 'end date in invalid format'
		else:
			status_dict['status'] = True 
			status_dict['message'] = ''
		
		return status_dict 	

	def _create_offer(self,offer):

		title = offer[self.TITLE]
		base_price = offer[self.BASE_PRICE]
		currency = offer[self.CURRENCY]
		description = offer[self.DESCRIPTION]
		quantity = offer[self.QUANTITY]
		start_date = offer[self.START_DATE]
		end_date = offer[self.END_DATE]
		venue = offer[self.VENUE]
		timezone = offer[self.TIMEZONE]
		redirect_url = offer[self.REDIRECT_URL]
		webhook_url = offer[self.WEBHOOK_URL]
		note = offer[self.NOTE]
	
		api_response = self.api.offer_create(title,base_price,currency,description,quantity,start_date,end_date,venue,timezone,redirect_url,webhook_url,note)
		return api_response