示例#1
0
def successful_payment(request):
    """
    payment_id=MOJO0b10N05A12374905
    payment_status=Credit
    payment_request_id=1fb41cbaae844a8b88c970c081f71ba1
    website.com/cart?product_id=1
    """
    if request.user.is_authenticated:
        user = request.user
        cart = Cart.objects.get_or_create(user=user)[0]

        # Verifying the payments.
        payment_request_id = request.GET['payment_request_id']
        api = Instamojo(api_key=settings.API_KEY,
                        auth_token=settings.AUTH_TOKEN,
                        endpoint='https://test.instamojo.com/api/1.1/')
        response = api.payment_request_status(payment_request_id)

        if response['success']:
            order = Order.objects.create(payer=user, status='Accepted')

            for product in cart.products.all():
                product.quantity -= 1
                order.cart.add(product)

            # Everything was successful now, clear the existing cart.
            cart.products.clear()
            context = {'cart_count': cart.products.count()}
            return render(request, "store/success.html", context=context)
        return HttpResponse("OH! Man This is not how it works.")
        return HttpResponse("You're not logged In.")
示例#2
0
def payment_redirect(request):
    api = Instamojo(api_key='27fb8178a52dc8e02866df53267d016d',
                    auth_token='4c5d72dcdaa1e81b2ec37525609dd6b5',
                    endpoint='https://test.instamojo.com/api/1.1/')

    # Create a new Payment Request
    firstname = request.POST["first_name"]
    amount = request.POST["amount"]
    email = request.POST["email"]
    phone = request.POST["mobile"]
    project = request.POST["project"]
    print project
    response = api.payment_request_create(
        amount=amount,
        purpose=project,
        send_email=True,
        email=email,
        phone=phone,
        buyer_name=firstname,
        redirect_url="http://www.reimaginegiving.org/Success/")
    # print the long URL of the payment request.
    print response
    response1 = response['payment_request']['longurl']
    print response1
    # print the unique ID(or payment request ID)
    # print response['payment_request']['id']
    return redirect(response1)
示例#3
0
def payment_request(request):
    '''
    Creates a payment request and redirects to instamojo payments page and on completion returns to payment_response page.
    '''
    api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)
    eventid = request.GET['event']
    price = request.GET['price']
    variable = ''
    if eventid == 'all':
        variable = 'payment for acumen it registered events'
    else:
        eventdetail = Event.objects.get(event_id=eventid)
        variable = 'payment for acumen it ' + str(
            eventdetail.event_name) + ' event'
    response = api.payment_request_create(
        amount=price,
        purpose=variable,
        buyer_name=request.user.first_name,
        send_email=True,
        email=request.user.email,
        redirect_url="https://www.acumenit.in/payment_response/" +
        str(eventid) + "/",
    )

    print(response['payment_request']['id'])

    return redirect(response['payment_request']['longurl'])
    def __init__(self, name, *args, **kwargs):
        super(InstamojoBase, self).__init__(name)

        self.salt = kwargs['salt']
        self.instamojo_wrapper = Instamojo(
            kwargs['api_key'],
            auth_token=kwargs['auth_token'],
            endpoint=kwargs['endpoint']
            or "https://www.instamojo.com/api/1.1/")
示例#5
0
class TestPaymentRequests(BaseTestClass):
    def setUp(self):
        self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
        self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)

    @responses.activate
    def test_refund_create(self):
        data = refunds_payload['refund_create']
        endpoint = self.api_endpoint + 'refunds/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.refund_create(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_refund_detail(self):
        data = refunds_payload['refund_detail']
        endpoint = self.api_endpoint + 'refunds/{id}/'.format(**data['request'])
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.refund_detail(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_refunds_list(self):
        data = refunds_payload['refunds_list']
        endpoint = self.api_endpoint + 'refunds/'
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.refunds_list(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)
示例#6
0
def getPaymentStatus(payment_id, payment_request_id):
    # api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN, endpoint='https://test.instamojo.com/api/1.1/')
    api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)
    response = api.payment_request_payment_status(payment_request_id,
                                                  payment_id)
    if (response["success"]):
        if (response['payment_request']['payment']['status'] == "Credit"):
            status = True
        else:
            status = False
        return status
    else:
        return False
示例#7
0
def payment_record_handler(instance: Payment, sender, **kwargs):
    """
    Each time a payment record is saved, signal will check and update
    other payment records and payment request.
    :param instance: Instance that is being saved
    :param sender: Payment model
    :param kwargs: other parameters
    :return: None
    """
    from drf_instamojo.serializers import PaymentSerializer

    from instamojo_wrapper import Instamojo

    pr: PaymentRequest = instance.payment_request

    imojo = Instamojo(
        api_key=pr.configuration.api_key,
        auth_token=pr.configuration.auth_token,
        endpoint=pr.configuration.base_url,
    )

    pr_status = imojo.payment_request_status(id=pr.id)

    # Check if payment status request is successful
    if pr_status.get("success"):
        payment_request_imojo = pr_status.get("payment_request")

        # Hacky way to fix TypeError here.
        # As instamojo is sending modified_at as str here
        # We'll use strftime() to format PaymentRequest's modified_at to str
        if payment_request_imojo.get("modified_at") > (
            pr.modified_at.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        ):
            # Update payment request
            pr.status = payment_request_imojo.get("status")
            pr.modified_at = payment_request_imojo.get("modified_at")
            pr.sms_status = payment_request_imojo.get("sms_status")
            pr.email_status = payment_request_imojo.get("email_status")
            pr.save()

        # Save other payment details, if not already saved.
        # This may trigger more signals.
        # TODO: Check if there is any better way to do this.
        for payment in payment_request_imojo.get("payments"):
            id = payment.get("payment_id")
            try:
                Payment.objects.get(id=payment.get("payment_id"))
            except Payment.DoesNotExist:
                ps = PaymentSerializer(data={"id": id, "payment_request": pr.id})
                ps.is_valid(raise_exception=True)
                ps.save()
示例#8
0
 def get_form(self, payment, data=None):
     if not payment.id:
         payment.save()
     api = Instamojo(api_key=self.api_key, auth_token=self.auth_token, endpoint=self.endpoint)
     payment_request = api.payment_request_create(
         amount=payment.total,
         purpose=payment.description,
         send_email=False,
         redirect_url=self.base_url + payment.get_process_url(),
     )
     try:
         raise RedirectNeeded(payment_request['payment_request']['longurl'])
     except KeyError:
         raise PaymentError(
             'Error in processing payment. Contact developer. Output: %s' % (payment_request))
示例#9
0
def payment_request(name, amount, purpose, email, mobile):
    api = Instamojo(api_key=os.getenv('api_auth_key'),
                    auth_token=os.getenv('api_auth_token'))

    # Create a new Payment Request
    response = api.payment_request_create(
        buyer_name=name,
        amount=amount,
        purpose=purpose,
        send_email=True,
        email=email,
        phone=mobile,
        redirect_url="https://zeitgeist.org.in/payment_redirect/",
        webhook="https://zeitgeist.org.in/webhook/")
    return response
示例#10
0
def checkout(request):
    if request.user.is_authenticated:
        user = request.user
        cart = Cart.objects.get_or_create(user=user)[0]

        if cart.products.count() > 0:
            total_price = cart.total_price()
            api = Instamojo(api_key=settings.API_KEY,
                            auth_token=settings.AUTH_TOKEN,
                            endpoint='https://test.instamojo.com/api/1.1/')
            response = api.payment_request_create(
                amount=str(total_price),
                purpose="Buying Products from March Site.",
                redirect_url="http://localhost:8000/success")
            return redirect(response['payment_request']['longurl'])
    return HttpResponse("You're not logged In.")
示例#11
0
def payment_record_handler(instance: Payment, sender, **kwargs):
    """
    Each time a payment record is saved, signal will check and update
    other payment records and payment request.
    :param instance: Instance that is being saved
    :param sender: Payment model
    :param kwargs: other parameters
    :return: None
    """
    from drf_instamojo.serializers import PaymentSerializer

    from instamojo_wrapper import Instamojo

    pr: PaymentRequest = instance.payment_request

    imojo = Instamojo(api_key=pr.configuration.api_key,
                      auth_token=pr.configuration.auth_token,
                      endpoint=pr.configuration.base_url)

    pr_status = imojo.payment_request_status(id=pr.id)

    # Check if payment status request is successful
    if pr_status.get('success'):
        payment_request_imojo = pr_status.get('payment_request')

        if payment_request_imojo.get('modified_at') > pr.modified_at:
            # Update payment request
            pr.status = payment_request_imojo.get('status')
            pr.modified_at = payment_request_imojo.get('modified_at')
            pr.sms_status = payment_request_imojo.get('sms_status')
            pr.email_status = payment_request_imojo.get('email_status')
            pr.save()

        # Save other payment details, if not already saved.
        # This may trigger more signals.
        # TODO: Check if there is any better way to do this.
        for payment in payment_request_imojo.get('payments'):
            id = payment.get('payment_id')
            try:
                Payment.objects.get(id=payment.get('payment_id'))
            except Payment.DoesNotExist:
                ps = PaymentSerializer(data={
                    'id': id,
                    'payment_request': pr.id
                })
                ps.is_valid(raise_exception=True)
                ps.save()
示例#12
0
    def handle(self, *args, **options):
        api = Instamojo(api_key=settings.INSTAMOJO['API_KEY'],
                        auth_token=settings.INSTAMOJO['AUTH_TOKEN'])
        for payment in Payment.objects.filter(status=''):
            if payment.payment_request_id == '':
                continue
            response = api.payment_request_status(payment.payment_request_id)
            payment.status = response['payment_request']['status']
            payment.longurl = response['payment_request']['longurl']
            payment.shorturl = response['payment_request']['shorturl']
            if len(response['payment_request']['payments']) > 0:
                payresp = response['payment_request']['payments'][0]
                if payment.payment_id == '':
                    payment.payment_id = payresp['payment_id']
                payment.status = payresp['status']
                payment.fees = payresp['fees']

            payment.save()
示例#13
0
def getPaymentLink(id):
    try:
        # api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN, endpoint='https://test.instamojo.com/api/1.1/')
        api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)
        response = api.payment_request_status(id)
        if (response['payment_request']['status'] == "Completed"):
            status = True
        else:
            status = False

        data = {
            "status": status,
            "link": response['payment_request']['longurl'],
            "error": False
        }
        return data
    except Exception:
        return {"error": True}
class InstamojoBase(PaymentProcessorBase):
    payment_method_class = InstamojoPaymentMethod
    transaction_view_class = InstamojoTransactionView
    allowed_currencies = ('INR', )

    instamojo_wrapper = None
    salt = None

    def __init__(self, name, *args, **kwargs):
        super(InstamojoBase, self).__init__(name)

        self.salt = kwargs['salt']
        self.instamojo_wrapper = Instamojo(
            kwargs['api_key'],
            auth_token=kwargs['auth_token'],
            endpoint=kwargs['endpoint']
            or "https://www.instamojo.com/api/1.1/")

    def refund_transaction(self, transaction, payment_method=None):
        # NOT IMPLEMENTED
        pass

    def void_transaction(self, transaction, payment_method=None):
        # NOT IMPLEMENTED
        pass

    def handle_transaction_response_inner(self, transaction: Transaction,
                                          payment_id):
        response = self.instamojo_wrapper.payment_detail(payment_id)

        print(response)
        if 'success' in response and not response['success']:
            logger.info("Failed to load payment info %r", response['message'])
            transaction.fail(fail_reason=response['message'])
            return

        payment_info = response['payment']
        if payment_info['status'] == 'Credit':
            logger.info("Payment success %r", payment_info)
            transaction.settle()
        else:
            logger.info("Payment failed %r", payment_info)
            transaction.fail()

    def handle_transaction_response(self, transaction: Transaction, request):
        try:
            if request.GET.get('payment_id', None):
                transaction.data['payment_id'] = request.GET['payment_id']
                self.handle_transaction_response_inner(
                    transaction, transaction.data['payment_id'])
            else:
                error = request.GET.get('err', None) or 'Unknown error'
                transaction.fail(fail_reason=error)
        except TransitionNotAllowed:
            pass

        transaction.save()
示例#15
0
class TestPaymentRequests(BaseTestClass):
    def setUp(self):
        self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
        self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)

    @responses.activate
    def test_refund_create(self):
        data = refunds_payload['refund_create']
        endpoint = self.api_endpoint + 'refunds/'
        responses.add(responses.POST,
                      endpoint,
                      body='{}',
                      content_type='application/json')
        resp = self.api.refund_create(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_refund_detail(self):
        data = refunds_payload['refund_detail']
        endpoint = self.api_endpoint + 'refunds/{id}/'.format(
            **data['request'])
        responses.add(responses.GET,
                      endpoint,
                      body='{}',
                      content_type='application/json')
        resp = self.api.refund_detail(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_refunds_list(self):
        data = refunds_payload['refunds_list']
        endpoint = self.api_endpoint + 'refunds/'
        responses.add(responses.GET,
                      endpoint,
                      body='{}',
                      content_type='application/json')
        resp = self.api.refunds_list(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)
示例#16
0
def payment_request(request):
    '''
    Creates a payment request and redirects to instamojo payments page and on completion returns to payment_response page.
    '''
    api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)

    participant = Participant.objects.get(user=request.user)
    response = api.payment_request_create(
        amount='180',
        purpose='Acument IT Hackathon',
        buyer_name=request.user.first_name,
        send_email=True,
        email=request.user.email,
        phone=participant.contact,
        redirect_url="https://www.acumenit.in/acuthon/payment_response",
        webhook="http://www.acumenit.in/acuthon/payment_webhook")

    print(response['payment_request']['id'])

    return redirect(response['payment_request']['longurl'])
示例#17
0
def payRegistration(payload):
    try:
        api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)
        # api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN, endpoint='https://test.instamojo.com/api/1.1/')
        response = api.payment_request_create(
            amount='100',
            purpose='Intern Fair 2k20 IIT Ropar Student Registration',
            send_email=True,
            email=payload["email"],
            buyer_name=payload["name"],
            send_sms=True,
            phone=payload["phone_number"],
            redirect_url=payload["redirect_url"],
        )
        data = {
            "id": response['payment_request']['id'],
            "link": response['payment_request']['longurl'],
            "error": False
        }
        return data
    except Exception:
        return {"error": True}
示例#18
0
def downloadrequestpage(request):
    if request.method=="GET":
        id=request.GET.get('id')
        user=request.session.get('user')
        product=Product.objects.get(id=id)
        request.session['product_name']=product.name
        userObject=User.objects.get(id=request.session['id'])
        amount=product.price-((product.price)*(product.discount)/100)
        api = Instamojo(api_key=PAYMENT_API_KEY, auth_token=PAYMENT_API_AUTH_TOKEN);
        response = api.payment_request_create(
            amount=math.floor(amount),
            purpose=f'Payment For {product.name}',
            send_email=True,
            email=request.session.get('email'),
            redirect_url="http://localhost:8000/Download/complete-payment"
            )
        payment_request_id=response['payment_request']['id']
        payment=Payment(product=product,user=userObject,payment_request_id=payment_request_id)
        payment.save()
        url=response['payment_request']['longurl']
        print(response)
        return redirect(url)
示例#19
0
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                a=OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            price=OrderItem.get_cost(a)
            # clear the cart
            request.session['order_id'] = order.id
            cart.clear()
            api = Instamojo(api_key="327dc26252b623af6faa0ef987188be5", auth_token="fb79872dab2032fd4c678f4d927c5625", endpoint='https://test.instamojo.com/api/1.1/');
            response = api.payment_request_create(
                purpose= 'Review Hub',
                amount= price,
                buyer_name= order.get_full_name(),
                email= order.email,
                phone= order.mobile,
                redirect_url=request.build_absolute_uri(reverse('orders:invoice', kwargs={'order_id':order.id})),
                send_email= 'True',
                send_sms= 'True',
                webhook= 'http://www.example.com/webhook/',
                allow_repeated_payments= 'False',
            )
            print (response)
            return HttpResponseRedirect(response['payment_request']['longurl'])
            # launch asynchronous task
            #order_created.delay(order.id)
            #return render(request, 'orders/order/created.html', {'order': order})
    else:
        form = OrderCreateForm()
    return render(request, 'orders/order/create.html', {'cart': cart,
                                                        'form': form})
示例#20
0
 def process_data(self, payment, request):
     if 'payment_request_id' not in request.GET:
         return HttpResponseForbidden('FAILED')
     payment_request_id = request.GET.get('payment_request_id')
     api = Instamojo(api_key=self.api_key, auth_token=self.auth_token, endpoint=self.endpoint)
     status_request = api.payment_request_status(payment_request_id)
     try:
         payment_req = status_request['payment_request']['payments'][0]
         status = payment_req['status']
         if status == 'Credit':
             payment.change_status(PaymentStatus.CONFIRMED)
             payment.captured_amount = payment.total
             payment.extra_data = json.dumps(status_request)
             first_name, last_name = payment_req['buyer_name'].rsplit(' ', 1)
             payment.billing_first_name = first_name
             payment.billing_last_name = last_name
             payment.save()
         elif status == 'Failed':
             payment.change_status(PaymentStatus.REJECTED)
             return redirect(payment.get_failure_url())
     except KeyError:
         payment.change_status(PaymentStatus.REJECTED)
         return redirect(payment.get_failure_url())
     return redirect(payment.get_success_url())
示例#21
0
def success(request):
    from django.contrib.auth.models import User
    api = Instamojo(api_key='27fb8178a52dc8e02866df53267d016d',
                    auth_token='4c5d72dcdaa1e81b2ec37525609dd6b5',
                    endpoint='https://test.instamojo.com/api/1.1/')
    # Create a new Payment Request
    payment_request_id = request.GET["payment_request_id"]
    txnid = request.GET["payment_id"]
    response = api.payment_request_status(payment_request_id)

    print response['payment_request']['shorturl']  # Get the    short URL
    print response['payment_request']['status']  # Get the current status
    print response['payment_request']['payments']  # List of payments
    print response['payment_request']['amount']

    status = response['payment_request']['status']
    amount = response['payment_request']['amount']
    print("\n\n ", request.user)
    if request.user.is_authenticated():
        print "true"
        donation = Donation(
            name=response['payment_request']['buyer_name'],
            transaction_id=txnid,
            donor_id=request.user,
            project_id_id=response['payment_request']['purpose'],
            amount=amount)
    else:
        print "false"
        donation = Donation(
            name=response['payment_request']['buyer_name'],
            transaction_id=txnid,
            donor_id=User.objects.get(username="******"),
            project_id_id=response['payment_request']['purpose'],
            amount=amount)
    donation.save()

    def raised_amount(project_id):
        donations = Donation.objects.filter(
            project_id=response['payment_request']['purpose'])
        print donations
        r_amt = 0
        for donation in donations:
            print donation
            r_amt = r_amt + donation.amount
            print r_amt
        return r_amt

    project = Project.objects.get(
        project_id=response['payment_request']['purpose'])
    project.raised_amount = raised_amount(
        response['payment_request']['purpose'])
    project.save()

    return render(
        request, 'sucess.html', {
            "status": status,
            "amount": amount,
            "txnid": txnid,
            'name': response['payment_request']['buyer_name'],
            'project_id': response['payment_request']['purpose'],
            'amount': amount
        })
示例#22
0
from django.shortcuts import render, redirect
from shop.models import Product, User, Payment
from instamojo_wrapper import Instamojo
from download_projects.settings import PAYMENT_API_KEY, PAYMENT_API_AUTH_TOKEN

API = Instamojo(api_key=PAYMENT_API_KEY,
                auth_token=PAYMENT_API_AUTH_TOKEN, endpoint='https://test.instamojo.com/api/1.1/')

import math


# Create your views here.
def createPayment(request, product_id):
    # Create a new Payment Request
    user = request.session.get('user')
    product = Product.objects.get(id=product_id)
    userObject = User.objects.get(id=user.get('id'))
    amount = (product.price - (product.price * (product.discount / 100)))
    response = API.payment_request_create(
        amount=math.floor(amount),
        purpose=f'Payment for {product.name}',
        send_email=True,
        buyer_name=userObject.name,
        email=user.get('email'),
        redirect_url="http://127.0.0.1:8000/complete-payment"
    )
    print(response)
    payment_request_id = response['payment_request']['id']
    # print the long URL of the payment request.
    payment = Payment(user=User(id = user.get('id') ) ,
                      product=product,
示例#23
0
class Testproducts(BaseTestClass):
    def setUp(self):
        self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
        self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)

    @responses.activate
    def test_basic_product_creation(self):
        data = products_payload['basic_product_creation']
        endpoint = self.api_endpoint + 'links/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.link_create(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_event_product_creation(self):
        data = products_payload['event_product_creation']
        endpoint = self.api_endpoint + 'links/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.link_create(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_digital_product_creation(self):
        data = products_payload['digital_product_creation']
        endpoint = self.api_endpoint + 'links/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        get_file_upload_url_endpoint = self.api_endpoint + 'links/get_file_upload_url/'
        file_upload_endpoint = self.api_endpoint + 'links/upload/'
        responses.add(
            responses.GET,
            get_file_upload_url_endpoint,
            json={'upload_url': file_upload_endpoint}
        )
        responses.add(
            responses.POST,
            self.api_endpoint + 'links/upload/',
            body='{"spam": "eggs"}'
        )
        with patch('instamojo_wrapper.api.open', mock_open(), create=True) as m:
            resp = self.api.link_create(**data['request'])
            self.assertEqual(resp, {})
            self.assertEqual(len(responses.calls), 3)
            self.assertEqual(
                responses.calls[0].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[1].request.url, file_upload_endpoint)
            self.assertEqual(
                responses.calls[2].request.url, endpoint)
            m.assert_called_once_with(data['request']['file_upload'], 'rb')

    @responses.activate
    def test_product_creation_with_cover_image(self):
        data = products_payload['product_creation_with_cover_image']
        endpoint = self.api_endpoint + 'links/'
        get_file_upload_url_endpoint = self.api_endpoint + 'links/get_file_upload_url/'
        file_upload_endpoint = self.api_endpoint + 'links/upload/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        responses.add(
            responses.GET,
            get_file_upload_url_endpoint,
            json={'upload_url': file_upload_endpoint}
        )
        responses.add(
            responses.POST,
            self.api_endpoint + 'links/upload/',
            body='{"spam": "eggs"}'
        )
        with patch('instamojo_wrapper.api.open', mock_open(), create=True) as m:
            resp = self.api.link_create(**data['request'])
            self.assertEqual(resp, {})
            self.assertEqual(len(responses.calls), 3)
            self.assertEqual(
                responses.calls[0].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[1].request.url, file_upload_endpoint)
            self.assertEqual(
                responses.calls[2].request.url, endpoint)
            m.assert_called_once_with(data['request']['cover_image'], 'rb')

    @responses.activate
    def test_product_creation_with_all_params(self):
        data = products_payload['product_creation_with_all_params']
        endpoint = self.api_endpoint + 'links/'
        get_file_upload_url_endpoint = self.api_endpoint + 'links/get_file_upload_url/'
        file_upload_endpoint = self.api_endpoint + 'links/upload/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        responses.add(
            responses.GET,
            get_file_upload_url_endpoint,
            json={'upload_url': file_upload_endpoint}
        )
        responses.add(
            responses.POST,
            file_upload_endpoint,
            body='{"spam": "eggs"}'
        )
        with patch('instamojo_wrapper.api.open', mock_open(), create=True) as m:
            resp = self.api.link_create(**data['request'])
            self.assertEqual(resp, {})
            self.assertEqual(len(responses.calls), 5)
            self.assertEqual(
                responses.calls[0].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[1].request.url, file_upload_endpoint)
            self.assertEqual(
                responses.calls[2].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[3].request.url, file_upload_endpoint)
            self.assertEqual(
                responses.calls[4].request.url, endpoint)
            m.assert_any_call(data['request']['cover_image'], 'rb')
            m.assert_any_call(data['request']['file_upload'], 'rb')

    @responses.activate
    def test_product_edit_with_all_params(self):
        data = products_payload['product_edit_with_all_params']
        endpoint = self.api_endpoint + 'links/{slug}/'.format(slug=data['request']['slug'])
        get_file_upload_url_endpoint = self.api_endpoint + 'links/get_file_upload_url/'
        file_upload_endpoint = self.api_endpoint + 'links/upload/'
        responses.add(
            responses.PATCH,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        responses.add(
            responses.GET,
            get_file_upload_url_endpoint,
            json={'upload_url': file_upload_endpoint}
        )

        responses.add(
            responses.POST,
            file_upload_endpoint,
            body='{"spam": "eggs"}'
        )
        with patch('instamojo_wrapper.api.open', mock_open(), create=True) as m:
            resp = self.api.link_edit(**data['request'])
            self.assertEqual(resp, {})
            self.assertEqual(len(responses.calls), 5)
            self.assertEqual(
                responses.calls[0].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[1].request.url, file_upload_endpoint)
            self.assertEqual(
                responses.calls[2].request.url, get_file_upload_url_endpoint)
            self.assertEqual(
                responses.calls[3].request.url, file_upload_endpoint)
            self.assertEqual(responses.calls[4].request.url, endpoint)
            m.assert_any_call(data['request']['cover_image'], 'rb')
            m.assert_any_call(data['request']['file_upload'], 'rb')

    @responses.activate
    def test_product_delete(self):
        data = products_payload['product_delete']
        endpoint = self.api_endpoint + 'links/{slug}/'.format(slug=data['request']['slug'])
        exception = Exception('Unable to decode response. Expected JSON, got this: \n\n\n ')
        responses.add(
            responses.DELETE,
            endpoint,
            body=exception
        )
        self.assertRaises(type(exception), self.api.link_delete, **data['request'])
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_product_details(self):
        data = products_payload['product_details']
        endpoint = self.api_endpoint + 'links/{slug}/'.format(slug=data['request']['slug'])
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.link_detail(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_product_details(self):
        data = products_payload['product_details']
        endpoint = self.api_endpoint + 'links/{slug}/'.format(slug=data['request']['slug'])
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.link_detail(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_products_payload_list(self):
        data = products_payload['products_list']
        endpoint = self.api_endpoint + 'links/'
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.links_list(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, endpoint)
示例#24
0
from writeonimage import WriteOnImage
from mailer import sendemail
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import json

import hmac
import hashlib
import base64
import cStringIO
from datetime import datetime

SALESTATUS = 2

api = Instamojo(api_key="a401e463d7e1bb3581f5a4a77acc9d02",
                auth_token="63832165458b889a1cce5e850b17c542")

users = {}

app = Flask(__name__,
            static_url_path='',
            static_folder='static',
            template_folder='static')
app.config.update(
    SECRET_KEY='SECRETSECRETKEY',
    GOOGLE_LOGIN_CLIENT_ID=
    '207581121170-6ja4pfdp9ec09l2b3g0ufb9c2pk42k9o.apps.googleusercontent.com',
    GOOGLE_LOGIN_CLIENT_SECRET='Fahbsf_7hbKxnGUgaN3Z_s4x',
    GOOGLE_LOGIN_REDIRECT_URI='http://localhost:5000/oauth2callback',
    # GOOGLE_LOGIN_REDIRECT_URI='http://192.168.59.22:5000/oauth2callback',
    GOOGLE_LOGIN_SCOPES='https://www.googleapis.com/auth/userinfo.email')
示例#25
0
from django.contrib.auth.decorators import login_required
from instamojo_wrapper import Instamojo
import re
from starconnect.keyconfig import *
from django.contrib.auth.models import User
import string
from random import sample, choice
from django.contrib import messages
chars = string.letters + string.digits
import requests
from datetime import datetime
import pytz

try:
	from starconnect.config import *
	api = Instamojo(api_key=INSTA_API_KEY, auth_token=AUTH_TOKEN)
except:
	api = Instamojo(api_key=INSTA_API_KEY, auth_token=AUTH_TOKEN, endpoint='https://test.instamojo.com/api/1.1/') #when in development

def home(request):
	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']
		user = authenticate(username=username, password=password)
		if user is not None:
			if user.is_active:
				if not user.cafe.email_verified:
					context = {'error_heading' : "Email not verified", 'message' :  'It seems you haven\'t verified your email yet. Please verify it as soon as possible to proceed.', 'url':request.build_absolute_uri(reverse('cafe:home'))}
					return render(request, 'cafe/message.html', context)
				login(request, user)
				return redirect('cafe:index')
示例#26
0
from instamojo_wrapper import Instamojo
from digitalShop.settings import PAYMENT_API_KEY, PAYMENT_AUTH_TOKEN

api = Instamojo(api_key=PAYMENT_API_KEY,
                auth_token=PAYMENT_AUTH_TOKEN,
                endpoint='https://test.instamojo.com/api/1.1/')

# Create a new Payment Request
response = api.payment_request_create(
    amount='20',
    purpose='Testing',
    send_email=True,
    email="*****@*****.**",
    redirect_url="https://www.programminghubs.com")
# print the long URL of the payment request.
url = response['payment_request']['longurl']
# print the unique ID(or payment request ID)
id = response['payment_request']['id']

print(url, id)
示例#27
0
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from instamojo_wrapper import Instamojo
from django.urls import reverse
from .forms import PaymentForm
# Create your views here.
# def index(request):
# 	return HttpResponse("Hello world")

payment_api = Instamojo(
    api_key="-----your api key--------",
    auth_token="---------your auth token-------------------",
    endpoint='https://test.instamojo.com/api/1.1/')


def index(request):
    if request.method == 'POST':
        print("\n\n" + str(request.POST))
        form = PaymentForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            response = payment_api.payment_request_create(
                amount=str(data['amount']),
                purpose=data['purpose'],
                send_email=False,
                send_sms=False,
                email=data['email'],
                buyer_name=data['name'],
                phone=data['contact_no'],
                redirect_url=request.build_absolute_uri(
                    reverse('www.xyz.com')))
from instamojo_wrapper import Instamojo
from accounts.models import StudentProfile
import pandas as pd
api = Instamojo(api_key="4a0095b9a6f22b83b9636b300d4295cd",
                auth_token="31c05e601dadb86742cf208c52d32dff")


response = api.payment_requests_list()
data = []
for payment_request in response['payment_requests']:
    if(payment_request['status']=="Completed"):
        id = payment_request['id']
        profiles = StudentProfile.objects.filter(order_id=id)
        if(profiles.count()):
            profile = profiles[0]
            if(not profile.reg_fees_paid):
                print(profile)
                data.append({
                    "name": profile.name,
                    "email": profile.email,
                })
            profile.reg_fees_paid = True
            profile.is_profile_complete = True
            profile.save()


pd.DataFrame(data).to_csv("success_but_changed_send_email.csv")
示例#29
0
 def setUp(self):
     self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
     self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)
示例#30
0
from django.shortcuts import render
from django.urls import reverse
from django.http import JsonResponse, HttpResponseRedirect
from models import Rocktaves, StandUp, StreetDance, PitchPerfect, RapWars
from django.views.decorators.csrf import csrf_exempt
from django.contrib.admin.views.decorators import staff_member_required
from instamojo_wrapper import Instamojo
import re

api = Instamojo(api_key=API_KEY, auth_token=AUTH_TOKEN)


@csrf_exempt
def index(request):

	if request.method == 'POST':

		event_id = request.POST['form_id']


		########## Rocktaves ##########
		if int(event_id) == 0:

			email = request.POST['email']

			try:
				Rocktaves.objects.get(email_address = email)
				user_exists = True
			except:
				user_exists = False
示例#31
0
    WorkshopEnrollmentModelSerializer, UserModelSerializer,
    UserPasswordSerializer, EmailSerializer, PasswordTokenSerializer)

from .token import account_activation_token
from django.core.mail import EmailMessage
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.http import HttpResponse
from django.views import View
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

from instamojo_wrapper import Instamojo
api = Instamojo(api_key='9474b726f61d6d2cf2d420437740074e',
                auth_token='8db275e2aaf013cfab88614cffd02a3a',
                endpoint='https://www.instamojo.com/api/1.1/')


class WorkshopListAPIView(APIView):
    """
    docstring here
        :param APIView: 
    """
    serializer_class = WorkshopModelSerializer
    permission_classes = (IsAdminOrReadOnly,
                          permissions.IsAuthenticatedOrReadOnly)

    def get(self, request):
        workshops = Workshop.objects.all()
        serializer = WorkshopModelSerializer(workshops, many=True)
示例#32
0
 def setUp(self):
     self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
     self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)
示例#33
0
from django.shortcuts import get_object_or_404
from instamojo_wrapper import Instamojo
from home import API_KEY, AUTH_TOKEN
from django.urls import reverse
from datetime import datetime
from django.contrib.auth import login, authenticate, logout
from .forms import SignUpForm
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
import re
import MySQLdb
api = Instamojo(api_key=API_KEY,
                auth_token=AUTH_TOKEN,
                endpoint='https://test.instamojo.com/api/1.1/')


def conn():
    return MySQLdb.connect("127.0.0.1", "root", "12345678", "rentafolio3")


def check_email(email):
    try:
        validate_email(email)
        return True
    except ValidationError:
        return False

class TestPaymentRequests(BaseTestClass):
    def setUp(self):
        self.api_endpoint = 'https://www.instamojo.com/api/1.1/'
        self.api = Instamojo('API-KEY', 'AUTH-TOKEN', self.api_endpoint)

    @responses.activate
    def test_payment_request_create(self):
        data = payment_requests_payload['payment_request_create']
        endpoint = self.api_endpoint + 'payment-requests/'
        responses.add(
            responses.POST,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.payment_request_create(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_payment_request_status(self):
        data = payment_requests_payload['payment_request_status']
        endpoint = self.api_endpoint + 'payment-requests/{id}/'.format(**data['request'])
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.payment_request_status(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_payment_requests_list(self):
        data = payment_requests_payload['payment_requests_list']
        endpoint = self.api_endpoint + 'payment-requests/'
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.payment_requests_list(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)

    @responses.activate
    def test_payment_requests_list_optional_params(self):
        data = payment_requests_payload['payment_requests_list_optional_params']
        endpoint = self.api_endpoint + 'payment-requests/'
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.payment_requests_list(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        parsed_url = urlparse(responses.calls[0].request.url)
        self.assertTrue(endpoint.endswith(parsed_url.path))
        self.assertDictEqual(dict(parse_qsl(parsed_url.query.strip('/'))), data['request'])

    @responses.activate
    def test_payment_request_payment_status(self):
        data = payment_requests_payload['payment_request_payment_status']
        endpoint = self.api_endpoint + 'payment-requests/{id}/{payment_id}/'.format(**data['request'])
        responses.add(
            responses.GET,
            endpoint,
            body='{}',
            content_type='application/json'
        )
        resp = self.api.payment_request_payment_status(**data['request'])
        self.assertEqual(resp, {})
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(
            responses.calls[0].request.url, endpoint)