def capture_order(self, order_id, debug=True):
		
		request = OrdersCaptureRequest(order_id)
		request.prefer('return=representation')
		#3. Call PayPal to capture an order
		response = self.client.execute(request)
	
		#4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.

		if debug:
			print('Status Code: ', response.status_code)
			print('Status: ', response.result.status)
			print('Order ID: ', response.result.id)
			print('Links:')

		return_link = ""
		for link in response.result.links:
			print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method))
		
		print('Capture Ids: ')
		for purchase_unit in response.result.purchase_units:
			for capture in purchase_unit.payments.captures:
				print('\t', capture.id)
		print("Buyer:")
		print("\tEmail Address: {}\n\tName: {}".format(response.result.payer.email_address, 
			response.result.payer.name.given_name + " " + response.result.payer.name.surname))

		return response
Example #2
0
 def testOrdersCaptureTest(self):
     self.skipTest(
         "Tests that use this class must be ignored when run in an automated environment because executing an order will require approval via the executed payment's approve url"
     )
     request = OrdersCaptureRequest("ORDER-ID")
     request.request_body(self.build_request_body())
     response = self.client.execute(request)
     self.assertEqual(201, response.status_code)
     self.assertIsNotNone(response.result)
    def capture_order(self, order_id, debug=True,present_donor=None):
        """Method to capture order using order_id"""
        print('order_id==='+order_id)
        request = OrdersCaptureRequest(order_id)
        response = self.client.execute(request)
        if debug:
            print ('Status Code: ', response.status_code)
            print ('Status: ', response.result.status)
            print ('Order ID: ', response.result.id)
            print ('Links: ')
            for link in response.result.links:
                print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method))
            print ('Capture Ids: ')
            for purchase_unit in response.result.purchase_units:
                for capture in purchase_unit.payments.captures:
                    print('\t', capture.id)
                    captureId=capture.id
            try:

              print ("Buyer:")
              print ("\tEmail Address: {}\n\tName: {}\n\tPhone Number:".format(response.result.payer.email_address,
                                                                            response.result.payer.name.given_name + " " + response.result.payer.name.surname))
                                                                          #  response.result.payer.phone.phone_number.national_number))
            except:
              print("error")
            json_data = self.object_to_json(response.result)
            print ("capture_json_data: ", json.dumps(json_data,indent=4))
            curr_tran=transaction.objects.get(id=present_donor)
            curr_tran.capture_id=captureId
            curr_tran.status=response.result.status
            curr_tran.save()
            
        return json_data
Example #4
0
def capture(payment_information: PaymentData,
            config: GatewayConfig) -> GatewayResponse:
    client = get_paypal_client(**config.connection_params)
    request = OrdersCaptureRequest(payment_information.token)
    try:
        print(payment_information)
        response = client.execute(request)
    except IOError as ioe:
        # Limit message length not to incur in db write error
        error_message = ioe.message[0:255]
        return GatewayResponse(
            is_success=False,
            action_required=False,
            amount=payment_information.amount,
            transaction_id=payment_information.token,
            kind=TransactionKind.CAPTURE,
            currency=payment_information.currency,
            error=error_message,
            raw_response={"IOError": error_message},
        )
    else:
        transaction = response.result.purchase_units[0].payments.captures[0]
        return GatewayResponse(
            is_success=True,
            action_required=False,
            kind=TransactionKind.CAPTURE,
            amount=decimal.Decimal(transaction.amount.value),
            currency=transaction.amount.currency_code,
            transaction_id=transaction.id,
            error=None,
        )
Example #5
0
    def capture_order(self, order_id, debug=False):
        """Method to capture order using order_id"""
        request = OrdersCaptureRequest(order_id)
        #3. Call PayPal to capture an order
        response = self.client.execute(request)
        #4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.
        if debug:
            print('Status Code: ', response.status_code)
            print('Status: ', response.result.status)
            print('Order ID: ', response.result.id)
            print('Links: ')
            for link in response.result.links:
                print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href,
                                                       link.method))
            print('Capture Ids: ')
            for purchase_unit in response.result.purchase_units:
                for capture in purchase_unit.payments.captures:
                    print('\t', capture.id)
            print("Buyer:")
            #print "\tEmail Address: {}\n\tName: {}\n\tPhone Number: {}".format(response.result.payer.email_address,
            #  response.result.payer.name.given_name + " " + response.result.payer.name.surname,
            #  response.result.payer.phone.phone_number.national_number)
        return response


#"""This driver function invokes the capture order function.
#Replace Order ID value with the approved order ID. """
#if __name__ == "__main__":
#  order_id = 'REPLACE-WITH-APPORVED-ORDER-ID'
#  CaptureOrder().capture_order(order_id, debug=True)
Example #6
0
 def capture_order(self, order_id, debug=False):
     """Method to capture order using order_id"""
     request = OrdersCaptureRequest(order_id)
     response = self.client.execute(request)
     if debug:
         print 'Status Code: ', response.status_code
         print 'Status: ', response.result.status
         print 'Order ID: ', response.result.id
         print 'Links: '
         for link in response.result.links:
             print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href,
                                                    link.method))
         print 'Capture Ids: '
         for purchase_unit in response.result.purchase_units:
             for capture in purchase_unit.payments.captures:
                 print '\t', capture.id
         print "Buyer:"
         print "\tEmail Address: {}\n\tName: {}\n\tPhone Number: {}".format(
             response.result.payer.email_address,
             response.result.payer.name.given_name + " " +
             response.result.payer.name.surname,
             response.result.payer.phone.phone_number.national_number)
         json_data = self.object_to_json(response.result)
         print "json_data: ", json.dumps(json_data, indent=4)
     return response
 def capture(self, paypal_order_id) -> Union[HttpResponse, HttpError]:
     request = OrdersCaptureRequest(paypal_order_id)
     # 3. Call PayPal to capture an order
     response = self.client.execute(request)
     if PAYPAL_DEBUG:
         logger.debug(
             json.dumps(self.object_to_json(response.result), indent=4))
     return response
Example #8
0
  def capture_order(self, token, debug=False):
    request = OrdersCaptureRequest(token)

    try :
        response = self.client.execute(request)
        order_id = response.result.id

        return order_id

    except IOError as ioe:
        return 0
Example #9
0
def capture_paypal_order(token) -> str:
    request = OrdersCaptureRequest(token)
    
    try:
        response = client.execute(request)
        order = response.result.id
        return order
    except Exception as e:
        with open('logging/log.txt', 'a') as l:
            l.write(str(e) + '\n')
            l.close()
            return False
Example #10
0
 def return_order(self, data: dict, *args,
                  **kwargs) -> BaseTransactionResult:
     print("=========收到同步通知数据=========")
     print(data)
     data = self.__deal_dict(data)
     print(data)
     print("=========收到同步通知数据=========")
     _sid, _pid, _status = self.__order_get_request(data['token'])
     res_status = BaseTransactionResult.UNKNOWN_PAYMENT_STATUS
     if _status == 'APPROVED':
         orders_capture_request = OrdersCaptureRequest(data['token'])
         capture_res = self.paypal.execute(orders_capture_request)
         print(f"确认{_pid}订单并收款")
         self.__print_paypal_response(capture_res)
         res_status = BaseTransactionResult.SUCCESSFULLY_VERIFIED
     result = BaseTransactionResult(_sid, _pid, res_status)
     return result
def capture_order(order_id):
    request = OrdersCaptureRequest(order_id=order_id)
    try:
        client = configuration()
        response = client.execute(request)

        order = response.result.id
        return order
    except IOError as ioe:
        if isinstance(ioe, HttpError):
            # Something went wrong server-side
            print(ioe.status_code)
            print(ioe.headers)
            print(ioe)
        else:
            # Something went wrong client side
            print(ioe)
Example #12
0
    def capture_order(self, order_id, debug=True):
        request = OrdersCaptureRequest(order_id)
        response = self.client.execute(request)

        if debug:
            print("Status Code: ", response.status_code)
            print("Status: ", response.result.status)
            print("Order ID: ", response.result.id)
            print("Links: ")

            for link in response.result.links:
                print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method))

            print("Capture Ids:")
            for purchase_unit in response.result.purchase_units:
                for capture in purchase_unit.payments.captures:
                    print("\t", capture.id)
        
        return self.parse_response(response)
Example #13
0
def capture_order(order_id):
    # Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
    # Replace APPROVED-ORDER-ID with the actual approved order id.
    request = OrdersCaptureRequest(order_id)

    try:
        # Call API with your client and get a response for your call
        response = client.execute(request)

        # If call returns body in response, you can get the deserialized version from the result attribute of the response
        return response
    except IOError as ioe:
        if isinstance(ioe, HttpError):
            # Something went wrong server-side
            print(ioe.status_code)
            print(ioe.headers)
            print(ioe)
        else:
            # Something went wrong client side
            print(ioe)
Example #14
0
def CapturePayPalOrder(paypal_order_id):

    request = OrdersCaptureRequest(paypal_order_id)

    try:
        # Call API with your client and get a response for your call
        response = client.execute(request)

        # If call returns body in response, you can get the deserialized version from the result attribute of the response
        order = response.result.id
        return order
    except IOError as ioe:
        if isinstance(ioe, HttpError):
            # Something went wrong server-side
            print(ioe.status_code)
            print(ioe.headers)
            print(ioe)
        else:
            # Something went wrong client side
            print(ioe)
Example #15
0
async def capture_transaction(
    transaction_body: CaptureTransactionModel,
    identity: Optional[str] = Depends(get_jwt_identity_optional)):
    try:
        orderResponse = paypal_client.client.execute(
            OrdersGetRequest(transaction_body.orderID))
        order = Order.objects.get(
            id=orderResponse.result.purchase_units[0].custom_id)
        if not price_service.remove_stock(order):
            raise OutOfStockError
        response = paypal_client.client.execute(
            OrdersCaptureRequest(transaction_body.orderID))
        order.paypalCaptureID = response.result.purchase_units[
            0].payments.captures[0].id
        order.orderStatus = 'placed'
        order.save()
        return orderResponse.result.purchase_units[0].custom_id
    except OutOfStockError:
        raise OutOfStockError().http_exception
    except Exception as e:
        raise e
Example #16
0
 def notify_order(self, request, *args, **kwargs) -> BaseTransactionResult:
     print("=========收到异步通知数据=========")
     data = request.data
     print(data)
     print("=========收到异步通知数据=========")
     token = data['resource']['id']
     _sid, _pid, _status = self.__order_get_request(token)
     if _status == 'APPROVED':
         orders_capture_request = OrdersCaptureRequest(data['token'])
         capture_res = self.paypal.execute(orders_capture_request)
         print(f"确认{token}订单并收款")
         self.__print_paypal_response(capture_res)
         res_status = BaseTransactionResult.SUCCESSFULLY_VERIFIED
         result = BaseTransactionResult(_sid, _pid, res_status)
     elif _status == 'COMPLETED':
         res_status = BaseTransactionResult.SUCCESSFULLY_VERIFIED
         result = BaseTransactionResult(_sid, _pid, res_status)
     else:
         res_status = BaseTransactionResult.SIGN_VERIFICATION_FAILED
         result = BaseTransactionResult(_sid, _pid, res_status)
     return result
Example #17
0
def capture(request, order_id, assignment_id):
    assignment = get_object_or_404(Assignment, id=assignment_id)
    if request.method == "POST":
        capture_order = OrdersCaptureRequest(order_id)
        Order.objects.create(token=order_id,
                             total=assignment.price,
                             emailAddress=assignment.creator.email,
                             assignment=assignment,
                             paid=True,
                             client=assignment.creator,
                             writer=assignment.writer,
                             support=assignment.support)
        environment = LiveEnvironment(client_id=settings.PAYPAL_CLIENT_ID,
                                      client_secret=settings.PAYPAL_SECRET_ID)
        client = PayPalHttpClient(environment)

        response = client.execute(capture_order)
        data = response.result.__dict__['_dict']

        return JsonResponse(data)
    else:
        return JsonResponse({'details': "invalid request"})
Example #18
0
 def capture_order(self, order_id, debug=False):
     """Method to capture order using order_id"""
     request = OrdersCaptureRequest(order_id)
     #3. Call PayPal to capture an order
     response = self.client.execute(request)
     #4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.
     # if debug:
     #   print 'Status Code: ', response.status_code
     #   print 'Status: ', response.result.status
     #   print 'Order ID: ', response.result.id
     #   print 'Links: '
     #   for link in response.result.links:
     #     print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method))
     #   print 'Capture Ids: '
     #   for purchase_unit in response.result.purchase_units:
     #     for capture in purchase_unit.payments.captures:
     #       print '\t', capture.id
     #   print "Buyer:"
     #   print "\tEmail Address: {}\n\tName: {}\n\tPhone Number: {}".format(response.result.payer.email_address,
     #     response.result.payer.name.given_name + " " + response.result.payer.name.surname,
     #     response.result.payer.phone.phone_number.national_number)
     return response
Example #19
0
    def capture_order(self, order_id, debug=False):
        request = OrdersCaptureRequest(order_id)
        response = self.client.execute(request)
        if debug:
            print('Status Code: ', response.status_code)
            print('Status: ', response.result.status)
            print('Order ID: ', response.result.id)
            print('Links: ')
        for link in response.result.links:
            print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href,
                                                   link.method))

        print('Capture Ids: ')
        for purchase_unit in response.result.purchase_units:
            for capture in purchase_unit.payments.captures:
                print('\t', capture.id)
        print("Buyer:")
        print("\tEmail Address: {}\n\tName: {}".format(
            response.result.payer.email_address,
            response.result.payer.name.given_name + " " +
            response.result.payer.name.surname))
        return response
Example #20
0
def capture_paypal_order(donation, order_id):
    """Method to capture order using order_id"""
    paypalSettings = getPayPalSettings()
    client = PayPalHttpClient(paypalSettings.environment)

    req = OrdersCaptureRequest(order_id)
    _debug('PayPal: Capture Order')
    try:
        response = client.execute(req)
    except IOError as ioe:
        fail_reason = str(ioe)
        if isinstance(ioe, HttpError):
            # Something went wrong server-side
            httpError = json.loads(ioe.message)
            if 'details' in httpError and len(httpError['details']) > 0:
                fail_reason = process_capture_failure(
                    donation, httpError['details'][0]['issue'],
                    httpError['details'][0]['description'])
        # update donation status to failed
        donation.payment_status = STATUS_FAILED
        donation.save()
        raise IOError(fail_reason)
    return response.result
Example #21
0
    def capture(self, wh_data: Dict[str, Any]) -> None:
        """Выполняет операции, связанные с захватом средств после платежа"""

        # после выполнения capture приходит второй аналогичный по типу вебхук, содержащий сведения об оплате
        # todo вообще говоря, следует здесь сверять данные по позиции и сумме, а также комиссии
        if 'payments' in wh_data['resource']['purchase_units'][0]:
            return

        checkout_id = wh_data['resource']['id']
        # if we call for a capture, then the customer has approved a payment for it
        Checkout.objects.update_checkout(checkout_id,
                                         PaypalOrderStatus.APPROVED.value)
        # Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
        request = OrdersCaptureRequest(checkout_id)

        # todo выделить в отдельный метод
        try:
            # Call API with your client and get a response for your call
            response = self.client.execute(request)

            # If call returns body in response, you can get the deserialized version
            # from the result attribute of the response
            order = response.result.id
            result = response.status_code
            if response.status_code == 201:
                capture_id = response.result.purchase_units[
                    0].payments.captures[0].id
                Checkout.objects.update_capture(checkout_id, capture_id)
            logger.debug(f'{order}, {result}')
        except IOError as ioe:
            if isinstance(ioe, HttpError):
                # Something went wrong server-side
                logger.error(
                    f'code: {ioe.status_code}\nHeaders:\n{ioe.headers}\n{ioe}')
            else:
                # Something went wrong client side
                logger.error(f'client error: {ioe}')
Example #22
0
def create_checkout_session(request):
    data = json.loads(request.body)

    # Coupon 

    coupon_code = data['coupon_code']
    coupon_value = 0

    if coupon_code != '':
        coupon = Coupon.objects.get(code=coupon_code)

        if coupon.can_use():
            coupon_value = coupon.value
            coupon.use()

    #

    cart = Cart(request)
    items = []
    
    for item in cart:
        product = item['product']

        price = int(product.price * 100)

        if coupon_value > 0:
            price = int(price * (int(coupon_value) / 100))

        obj = {
            'price_data': {
                'currency': 'usd',
                'product_data': {
                    'name': product.title
                },
                'unit_amount': price
            },
            'quantity': item['quantity']
        }

        items.append(obj)

    gateway = data['gateway']
    session = ''
    order_id = ''
    payment_intent = ''
    
    if gateway == 'stripe':
        stripe.api_key = settings.STRIPE_API_KEY_HIDDEN
        session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            line_items=items,
            mode='payment',
            success_url='http://127.0.0.1:8000/cart/success/',
            cancel_url='http://127.0.0.1:8000/cart/'
        )
        payment_intent = session.payment_intent

    #
    # Create order

    orderid = checkout(request, data['first_name'], data['last_name'], data['email'], data['address'], data['zipcode'], data['place'], data['phone'])

    total_price = 0.00

    for item in cart:
        product = item['product']
        total_price = total_price + (float(product.price) * int(item['quantity']))

    if coupon_value > 0:
        total_price = total_price * (coupon_value / 100)
    
    if gateway == 'razorpay':
        order_amount = total_price * 100
        order_currency = 'INR'
        client = razorpay.Client(auth=(settings.RAZORPAY_API_KEY_PUBLISHABLE, settings.RAZORPAY_API_KEY_HIDDEN))
        data = {
            'amount': order_amount,
            'currency': order_currency
        }

        payment_intent = client.order.create(data=data)
    
    # PayPal

    if gateway == 'paypal':
        order_id = data['order_id']
        environment = SandboxEnvironment(client_id=settings.PAYPAL_API_KEY_PUBLISHABLE, client_secret=settings.PAYPAL_API_KEY_HIDDEN)
        client = PayPalHttpClient(environment)

        request = OrdersCaptureRequest(order_id)
        response = client.execute(request)

        order = Order.objects.get(pk=orderid)
        order.paid_amount = total_price
        order.used_coupon = coupon_code

        if response.result.status == 'COMPLETED':
            order.paid = True
            order.payment_intent = order_id
            order.save()

            decrement_product_quantity(order)
            send_order_confirmation(order)
        else:
            order.paid = False
            order.save()
    else:
        order = Order.objects.get(pk=orderid)
        if gateway == 'razorpay':
            order.payment_intent = payment_intent['id']
        else:
            order.payment_intent = payment_intent
        order.paid_amount = total_price
        order.used_coupon = coupon_code
        order.save()

    #

    return JsonResponse({'session': session, 'order': payment_intent})
Example #23
0
 def capture_order(self, order_id):
     request = OrdersCaptureRequest(order_id)
     response = self.client.execute(request)
     return response