Пример #1
0
def deposit_verify_thread(instance, test=False):
    paystack_transaction = Transaction(authorization_key=settings.PAYSTACK_PUBLIC_KEY)
    status = False
    count = 0
    while not status and count < 5:
        if not test:
            time.sleep(60)
        response = paystack_transaction.verify(instance.reference)
        print(response)
        if response[3]['status'] == 'success':
            instance.verified = True
            with transaction.atomic():
                balance = instance.user.user_balance.get()
                balance.balance = decimal.Decimal(response[3]['amount'] / 100) + balance.balance
                balance.save(force_update=True)
            if not instance.user.paystack_authorization_code:
                if response[3]['authorization']['reusable']:
                    instance.user.paystack_authorization_code = \
                        response[3]['authorization']['authorization_code']
                    print('paystack auth code added')
            instance.save()
            instance.user.save()
            return None
        count += 1
    return None
Пример #2
0
def verify(request, reference):
    transaction = Transaction(settings.SK_KEY)
    response = transaction.verify(reference)
    if response[3]['status'] == 'success':
        return render(request, 'pages/success.html')
    else:
        return HttpResponse('failed')
Пример #3
0
    def pay(self, payload):
        """Generate paystack payment link."""
        paystack_key = self.env["ir.config_parameter"].sudo().get_param(
            "paystack.key")
        # sk_test_6613ae6de9e50d198ba22637e6df1fecf3611610
        transaction = Transaction(authorization_key=paystack_key)
        partner_id = request.env.user.partner_id
        orders = (request.env["sale.order"].with_user(1).search(
            [
                ("partner_id", "=", partner_id.id),
                ("state", "=", "draft"),
                ("id", "in", payload.ids),
            ],
            limit=len(payload.ids),
        ))
        if not orders:
            resp = request.make_response(
                json.dumps({
                    "error":
                    "No other found for the given id(s) %s" % (payload.ids)
                }))
            resp.status_code = 401
            return resp

        total = sum([o.amount_total for o in orders]) * 100

        initialize = transaction.initialize(
            partner_id.email or request.env.user.company_id.email, total)
        return initialize
Пример #4
0
def payment():

    amount = request.form.get('amount')
    email = request.form.get('user-email')
    first_name = request.form.get('first-name')
    last_name = request.form.get('last-name')
    invoice = request.form.get('invoice')

    customer = Customer(
        authorization_key="sk_test_25a564e7f472ec8650770fb6d7d06fc2e7b57285")
    client = customer.create(first_name='first_name',
                             last_name='last_name',
                             email='email')
    init = Transaction.initialize(reference='invoice',
                                  amount='amount',
                                  email='email')
    json.dumps(init)

    charge = Transaction.charge(
        reference='invoice',
        authorization_code='sk_test_25a564e7f472ec8650770fb6d7d06fc2e7b57285',
        email='email',
        amount='amount')

    return render_template('customer/checkout.html',
                           charge=charge,
                           amount=amount,
                           email=email,
                           orders=orders,
                           init=init,
                           client=client,
                           first_name=first_name,
                           last_name=last_name,
                           invoice=invoice)
Пример #5
0
    def get(self, *args, **kwargs):
        transaction = Transaction(
            authorization_key='sk_test_4efc8832170a975a1e1eb669a89b512909d0049a'
        )
        response = transaction.verify(kwargs['id'])
        data = JsonResponse(response, safe=False)

        if response[3]:
            try:
                order = Order.objects.get(user=self.request.user,
                                          ordered=False)
                payment = Payment()
                payment.paystack_id = kwargs['id']
                payment.user = self.request.user
                payment.amount = order.get_total()
                payment.save()

                order_items = order.items.all()
                order_items.update(ordered=True)
                for item in order_items:
                    item.save()

                order.ordered = True
                order.payment = payment
                order.ref_code = create_ref_code()
                order.save()

                messages.success(self.request, "order was successful")
                return redirect("/")
            except ObjectDoesNotExist:
                messages.success(self.request, "Your order was successful")
                return redirect("/")
        else:
            messages.danger(self.request, "Could not verify the transaction")
            return redirect("/")
Пример #6
0
 def wallet_paymentlink(self, amount):
     """Get checkout payment link."""
     paystack_key = self.env["ir.config_parameter"].sudo().get_param(
         "paystack.key")
     transaction = Transaction(authorization_key=paystack_key)
     partner_id = request.env.user.partner_id
     initialize = transaction.initialize(
         partner_id.email or request.user.login, amount * 100)
     return initialize[3]
Пример #7
0
    def comfirm_payment(self, payload):
        partner_id = request.env.user.partner_id.id
        orders = (request.env["sale.order"].with_user(1).search(
            [
                ("partner_id", "=", partner_id),
                ("state", "=", "draft"),
                ("id", "in", payload.ids),
            ],
            limit=len(payload.ids),
        ))
        if not orders:
            resp = request.make_response(
                json.dumps(
                    {"error":
                     "There is no open order in cart or draft state"}))
            resp.status_code = 400
            return resp
        paystack_key = self.env["ir.config_parameter"].sudo().get_param(
            "paystack.key")
        # sk_test_6613ae6de9e50d198ba22637e6df1fecf3611610
        transaction = Transaction(authorization_key=paystack_key)
        response = transaction.verify(payload.payment_ref)
        state = "error"
        if response[3] != None and response[3]["status"] == "success":
            state = "done"

            [[
                order.action_confirm(),
                order.with_user(1)._create_payment_transaction({
                    "acquirer_id":
                    self.env.ref("aisiki.payment_acquirer_aisiki").id,
                    "acquirer_reference":
                    response[3]["reference"],
                    "state":
                    state,
                    "state_message":
                    response[3],
                    "partner_country_id":
                    request.env.ref("base.ng").id,
                }),
            ] for order in orders]
        invoices = [order._create_invoices() for order in orders]
        for order in orders:
            transaction_ids = order.transaction_ids
            for transaction_id in transaction_ids:
                transaction_id._reconcile_after_transaction_done()

        error = request.make_response(json.dumps(response))
        error.status_code = 401
        return response[3] if response[3] else error
Пример #8
0
def verify(request, id):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)
    transaction = Transaction(authorization_key=settings.PAYSTACK_SECRET_KEY)
    response = transaction.verify(id)
    data = JsonResponse(response, safe=False)
    verify_json = json.dumps(response)
    if verify_json[1] == '4':
        return render(request, 'paystack/failed-page.html')
    else:
        order.paid = True
        order.transaction_reference_id = id
        order.save()
        return render(request, 'paystack/success-page.html', {'order': order})
class Paystack:
    
    transaction = Transaction(authorization_key="sk_test_40842031d9cd521f662260d98a0248ed8c569d73")

    def __init__(self, ref_code):
        self.ref_code = ref_code
        self.email = ""
        self.transaction_date = ""
        self.amount = 0
        self.status = None

    def convert_amount(self, amount):
        return amount/100
    
    def verify_payment(self):
        try:
            response = self.transaction.verify(self.ref_code)[3]
            print(response["customer"]["email"], 
            response["customer"]["customer_code"], 
            response["status"], 
            self.convert_amount(response["amount"]),
            response["reference"]
            )
            return 'verified'
        except:
            return 'not verified'
Пример #10
0
    def postbalance(self, payload):
        """Add wallet balance"""
        paystack_key = self.env["ir.config_parameter"].sudo().get_param(
            "paystack.key")
        transaction = Transaction(authorization_key=paystack_key)
        response = transaction.verify(payload.payment_ref)
        try:

            if response[3]["status"] == "success":
                wallet_id = request.env.ref(
                    "aisiki.aisiki_wallet_journal").with_user(
                        request.env.user.id)

                payment = request.env["account.payment"].with_user(1)

                payment_type = (
                    request.env["account.payment.method"].with_user(1).search(
                        [("code", "=", "manual"),
                         ("payment_type", "=", "inbound")],
                        limit=1,
                    ))

                payload = {
                    "payment_type": "inbound",
                    "partner_type": "customer",
                    "journal_id": wallet_id.id,
                    "partner_id": request.env.user.partner_id.id,
                    "amount": response[3]["amount"],
                    "payment_method_id": payment_type.id,
                }
                payment.create(payload).action_post()
                total_due = abs(request.env.user.partner_id.total_due)
                resp = request.make_response(json.dumps({"balance":
                                                         total_due}))
                resp.status_code = 404
                return resp
        except Exception as e:
            resp = request.make_response(json.dumps({"error": str(response)}))
            resp.status_code = 402
            return resp
Пример #11
0
def main():
    """
    All Response objects are a tuple containing status_code, status, message and data
    """
    # print(dir(request))
    email = current_user.email

    paystack_secret = os.environ.get("paystack_live")
    bot_price = 25000 * 100
    #Instantiate the transaction object to handle transactions.
    #Pass in your authorization key - if not set as environment variable PAYSTACK_AUTHORIZATION_KEY
    # email = "*****@*****.**" "sk_test_faadf90960bad25e6a2b5c9be940792f928b73ac"
    transaction = Transaction(authorization_key=paystack_secret)
    transaction_table = Transaction_Table.query.filter_by(email=email).first()
    if transaction_table:
        response = transaction.charge(
            email, f"{transaction_table.auth_code}",
            int(transaction_table.amount))  #+rge a customer N100.
        print(response)
        reference = response[3].get('reference')
        transaction = Transaction_Table(ref_no=reference)
        db.session.add(transaction)
        db.session.commit()
        return redirect('/dashboard')
    else:
        init_transaction = transaction.initialize(email, bot_price)
        reference = init_transaction[3].get('reference')
        transaction = Transaction_Table(ref_no=reference)
        db.session.add(transaction)
        db.session.commit()
        return redirect(init_transaction[3].get('authorization_url'))
Пример #12
0
    def create(self, request, *args, **kwargs):
        user = request.user
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            transaction = Transaction(
                authorization_key=settings.PAYSTACK_PUBLIC_KEY)
            amount = float(serializer.validated_data.get('amount')) * 100
            if user.paystack_authorization_code:
                response = transaction.charge(user.email,
                                              user.paystack_authorization_code,
                                              amount)
                print("with auth code\n", response)
            else:
                response = transaction.initialize(user.email, int(amount))
                url = response[3]['authorization_url']
            self.perform_create(serializer, response)
            data = serializer.data
            data['paystack_response'] = response[3]
            return Response(data=data, status=status.HTTP_201_CREATED)

        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Пример #13
0
class TestTransaction(TestCase):
   
    def setUp(self):
        super(TestTransaction, self).setUp()
        self.test_auth_key = os.getenv('PAYSTACK_AUTHORIZATION_KEY', None)
        self.transaction = Transaction()
        
 
    def test_charge(self):
        (status_code, _ , _, _) = self.transaction.charge("AUTH_invalidcode", "*****@*****.**", 1000)
        self.assertEqual(status_code, 400)


    def test_verify(self):
       pass
Пример #14
0
 def setUp(self):
     super(TestTransaction, self).setUp()
     self.test_auth_key = os.getenv('PAYSTACK_AUTHORIZATION_KEY', None)
     self.transaction = Transaction()
Пример #15
0
from django.test import TestCase

# Create your tests here.

from pypaystack import Transaction, Customer, Plan
"""
All Response objects are a tuple containing status_code, status, message and data
"""

#Instantiate the transaction object to handle transactions.
#Pass in your authorization key - if not set as environment variable PAYSTACK_AUTHORIZATION_KEY

transaction = Transaction(
    authorization_key="sk_test_20e69816d2d6c536e1459487d6b7165261c82a22")
response = transaction.charge("*****@*****.**", "CustomerAUTHcode",
                              10000)  #Charge a customer N100.
response = transaction.verify(
    refcode)  #Verify a transaction given a reference code "refcode".

#Instantiate the customer class to manage customers

customer = Customer(
    authorization_key="sk_test_20e69816d2d6c536e1459487d6b7165261c82a22")
response = customer.create("*****@*****.**",
                           "John",
                           "Doe",
                           phone="080123456789")  #Add new customer
response = customer.getone(1234)  #Get customer with id of 1234
response = customer.getall()  #Get all customers

#Instantiate the plan class to manage plans
Пример #16
0
def verify(request, pid):
    transaction = Transaction(authorization_key=settings.PAYSTACK_SCRET_KEY)
    response = transaction.verify(pid)
    book = get_object_or_404(Book, id=pid)
    return redirect('book_download', pk=book.pk)