Пример #1
0
    def post(self):
        form = PaymentForm()

        if form.validate_on_submit():
            print(url_for('static', filename='hicoin.png', _external=True))
            headers = {
                "X-LINE-ChannelId": app.config['CHANNEL_ID'],
                "X-LINE-ChannelSecret": app.config['CHANNEL_SECRET'],
                "Content-Type": "application/json; charset=UTF-8"
            }
            data = {
                "amount": form.payment.data,
                "productName": "Hi幣",
                "productImageUrl":
                "https://h-coin.3zh-studio.com/img/H-Coin%20Logo.png",
                "confirmUrl": url_for('user.payment_confirm', _external=True),
                "orderId": uuid.uuid4().hex,
                "currency": "TWD"
            }
            response = requests.post(app.config['CHANNEL_URL'],
                                     headers=headers,
                                     data=json.dumps(data).encode('utf-8'))

            if int(json.loads(response.text)['returnCode']) == 0:
                payment = Payment(payer_id=current_user.id,
                                  transaction_id=json.loads(
                                      response.text)['info']['transactionId'],
                                  amount=form.payment.data,
                                  currency="TWD",
                                  confirm=False).save()
                return redirect(
                    json.loads(response.text)['info']['paymentUrl']['web'])

        return redirect(url_for('user.payment'))
Пример #2
0
	def get(self):
		payments = Payment.objects(payer_id=current_user.id, confirm=True)
		buy_orders = Order.objects(buyer_id=current_user.id, status__ne=ORDER_STATUS["CANCEL"])
		sell_orders = Order.objects(product_id__in=Product.objects(seller_id=current_user.id), status=ORDER_STATUS["COMPLETE"])

		records = list()
		for payment in payments:
			record = Record("儲值", payment.amount, payment.create_time)
			records.append(record)
		for order in buy_orders:
			if order.product_id.bidding == False:
				if order.coupon_id == None:
					record = Record("購買" + order.product_id.name, -1 * int(order.product_id.price * order.product_id.discount), order.create_time)
				else:
					record = Record("購買" + order.product_id.name, -1 * max(0, int(order.product_id.price * order.product_id.discount - order.coupon_id.discount)), order.create_time)
			else:
				record = Record("購買" + order.product_id.name, -1 * order.product_id.bid.now_price, order.create_time)
			records.append(record)
		for order in sell_orders:
			if order.product_id.bidding == False:
				record = Record("販賣" + order.product_id.name, int(order.product_id.price * RATE), order.finish_time)
			else:
				record = Record("販賣" + order.product_id.name, int(order.product_id.bid.now_price * RATE), order.finish_time)
			records.append(record)
		records = sorted(records, key=lambda k: k.time, reverse=True)
		return render_template('user/hicoin/record.html', records=records)
Пример #3
0
def process_payment():
    """
    Process payment creation.
    """
    if request.method == 'GET':
        return "Get request"

    data = request.get_json()
    try:
        payment = Payment(**data)
        payment.save_record()
        print(data)

        return attempt_payment(payment)
    except Exception as e:
        print(e)
        return 'Error', 500
    return 'Not OK', 400
Пример #4
0
def create_payment(payment_payload):
    new_payment = Payment(invoice_id=payment_payload['invoice'],
                          amount=payment_payload['amount'],
                          payment_mode=payment_payload['payment_mode'])

    try:
        db.session.add(new_payment)
        db.session.commit()

    except Exception as exception:
        print("error : ", exception)
Пример #5
0
    def create(self, payloads):
        self.model_order = Order()
        order_details = payloads['order_details']
        self.model_order.user_id = payloads['user_id']
        self.model_order.status = 'pending'
        referal = db.session.query(Referal).filter_by(
            referal_code=payloads['referal_code'])
        if (referal.first() is not None):
            self.model_order.referal_id = referal.first().as_dict()['id']
        db.session.add(self.model_order)
        try:
            db.session.commit()
            data = self.model_order.as_dict()
            # insert the order details
            order_id = data['id']
            order_items = []
            for item in order_details:
                order_item = OrderDetails()
                order_item.ticket_id = item['ticket_id']
                order_item.count = item['count']
                order_item.order_id = order_id
                # get ticket data
                ticket = self.get_ticket(item['ticket_id'])
                if payloads['payment_type'] == 'paypal':
                    order_item.price = ticket.usd_price
                else:
                    order_item.price = ticket.price
                db.session.add(order_item)
                db.session.commit()
                order_items.append(order_item.as_dict())
            if payloads['payment_type'] == 'offline':
                gross_amount = (item['count'] * ticket.price)
                payment = Payment()
                payment.order_id = order_id
                payment.payment_type = 'offline'
                payment.gross_amount = gross_amount
                payment.transaction_time = datetime.datetime.now()
                payment.transaction_status = 'pending'
                db.session.add(payment)
                db.session.commit()

                # if payloads['payment_type'] == 'paypal':
                # self.paypalorder(payloads)
            # save all items
            return {'error': False, 'data': data, 'included': order_items}
        except SQLAlchemyError as e:
            data = e.orig.args
            return {'error': True, 'data': data}
Пример #6
0
    def post(self, id):
        parser = RequestParser(trim=True)
        parser.add_argument('amount', type=float)
        parser.add_argument('pay_type', type=int)
        parser.add_argument('bank_type', type=str)
        m_args = parser.parse_args(strict=True)
        if not hasattr(g, 'current_member'):
            return {'errorCode': "9999", 'errorMsg': "用戶未登录", 'success': False}
        uid = g.current_member.id
        member = Member.query.filter(Member.id == uid).first()
        status = member.status
        if status == 2:
            m_html = '''
						<body class="notfound">
						<div class="wrapper">
							<div class="big">页面不见了!</div>
							<div>该用户钱包已经被冻结</div>
						<div>
						</body>
			            '''
        if status == 0:
            m_html = '''
						<body class="notfound">
						<div class="wrapper">
							<div class="big">页面不见了!</div>
							<div>该用户已被禁用</div>
						<div>
						</body>
			            '''
            m_response = make_response(m_html)
            m_response.headers["Content-type"] = "text/html;charset=UTF-8"
            return m_response

        paylogger.info("%s用户使用线上支付%s" %
                       (g.current_member.id, m_args['amount']))
        realIp = request.remote_addr
        ip = utils.host_to_value(realIp)
        m_res = Payment().pay(id, m_args, g.current_member.id,
                              g.current_member.username, ip, realIp)
        paylogger.info("请求html------------------------")
        paylogger.info(m_res)
        paylogger.info("请求html------------------------")
        m_response = make_response(m_res)
        m_response.headers["Content-type"] = "text/html;charset=UTF-8"
        return m_response
Пример #7
0
 def post(self, id):
     parser = RequestParser(trim=True)
     parser.add_argument('amount', type=float)
     parser.add_argument('remitter', type=str)
     parser.add_argument('msg', type=str)
     parser.add_argument('income_type', type=int)
     parser.add_argument('pay_type', type=int)
     parser.add_argument('bankId', type=int)
     parser.add_argument('accountName', type=int)
     m_args = parser.parse_args(strict=True)
     if not hasattr(g, 'current_member'):
         return {'errorCode': "9999", 'errorMsg': "用戶未登录", 'success': False}
     paylogger.info("%s用户公司入款 args:%s" %
                    (g.current_member.username, m_args))
     uid = g.current_member.id
     member = Member.query.filter(Member.id == uid).first()
     status = member.status
     if status == 2:
         return {
             'errorCode': "9999",
             'errorMsg': "该用户已被冻结",
             'success': False
         }
     if status == 0:
         return {
             'errorCode': "9999",
             'errorMsg': "该用户已被禁用",
             'success': False
         }
     if m_args['amount'] == None or m_args['pay_type'] == None:
         return {"success": False, 'errorCode': "1010", 'errorMsg': "充值失败"}
     m_amount = m_args['amount']
     if m_amount <= 0:
         return {
             "success": False,
             'errorCode': "1010",
             'errorMsg': "充值失败,充值金额不正确"
         }
     ip = utils.host_to_value(request.remote_addr)
     m_res = Payment().recharge(id, m_args, g.current_member.id,
                                g.current_member.username, ip)
     if m_res:
         return {"success": True}
     else:
         return {"success": False, 'errorCode': "1010", 'errorMsg': "充值失败"}
Пример #8
0
    def get(self):
        payment = Payment.objects(
            payer_id=current_user.id,
            transaction_id=request.args.get('transactionId')).first()
        headers = {
            "X-LINE-ChannelId": app.config['CHANNEL_ID'],
            "X-LINE-ChannelSecret": app.config['CHANNEL_SECRET'],
            "Content-Type": "application/json; charset=UTF-8"
        }
        data = {"amount": payment.amount, "currency": payment.currency}
        response = requests.post(app.config['CHANNEL_CONFIRM_URL'].format(
            payment.transaction_id),
                                 headers=headers,
                                 data=json.dumps(data).encode('utf-8'))

        if int(json.loads(response.text)['returnCode']) == 0:
            payment.confirm = True
            payment.save()

            current_user.hicoin += payment.amount
            current_user.save()

        return redirect(url_for('user.payment'))
Пример #9
0
    def run():
        """
        Create 4 Payments seeds
        """

        transaction_statuses = ['capture', 'authorize', 'deny']
        statuses = ['accept', 'challenge', 'deny']
        payment_types = ['bank_transfer', 'credit_card']
        banks = ['bri', 'bni', 'permata', 'maybank', 'mandiri', 'bca', 'cimb']
        range_start = 10**(7 - 1)
        range_end = (10**7) - 1
        orders = BaseModel.as_list(db.session.query(Order).all())
        for i in range(0, 4):
            order_id = choice(orders)['id']
            saved_token_id = randint(range_start, range_end)
            transaction_id = randint(range_start, range_end)
            gross_amount = randint(range_start, range_end)
            transaction_time = datetime.datetime.now()

            transaction_status = transaction_statuses[randint(0, 2)]
            masked_card = randint(range_start, range_end)
            payment_type = payment_types[randint(0, 1)]
            bank = banks[randint(0, 6)]
            fraud_status = statuses[randint(0, 2)]

            new_payment = Payment()
            new_payment.order_id = order_id
            new_payment.saved_token_id = saved_token_id
            new_payment.transaction_id = transaction_id
            new_payment.gross_amount = gross_amount
            new_payment.transaction_time = transaction_time
            new_payment.transaction_status = transaction_status
            new_payment.masked_card = masked_card
            new_payment.payment_type = payment_type
            new_payment.bank = bank
            new_payment.fraud_status = fraud_status
            db.session.add(new_payment)
            db.session.commit()
Пример #10
0
 def confirm(self, payload, user_id, request):
     response = ResponseBuilder()
     emailservice = EmailService()
     transaction_exist = db.session.query(Payment).filter_by(
         transaction_id=payload['transaction_id']).first()
     if transaction_exist:
         return response.set_error(True).set_message(
             'this transaction have been used before').set_data(
                 None).build()
     paypal_details = self.get_paypal_detail(payload['transaction_id'])
     if paypal_details == False:
         return response.set_error(True).set_message(
             'Transaction id not found').set_data(None).build()
     paypal_details_amount = int(
         paypal_details['transactions'][0]['amount']['total'].split('.')[0])
     order_ = db.session.query(Order).filter_by(
         id=payload['order_id']).first()
     if order_ is None:
         return response.set_error(True).set_data(None).set_message(
             'Order not found').build()
     user = order_.user
     order_details = db.session.query(OrderDetails).filter_by(
         order_id=payload['order_id']).all()
     check_total = 0
     discount = 0
     for order in order_details:
         check_total += order.price * order.count
     if order_.referal_id is not None:
         discount = check_total * order_.referal.discount_amount
     if check_total - discount <= paypal_details_amount:
         payment_exist = db.session.query(Payment).filter_by(
             transaction_id=payload['transaction_id']).first()
         if payment_exist:
             return response.set_data(None).set_message(
                 'Payment had been completed!').set_error(True).build()
         payment = Payment()
         payment.order_id = payload['order_id']
         payment.transaction_id = payload['transaction_id']
         payment.gross_amount = paypal_details_amount
         payment.payment_type = 'paypal'
         payment.transaction_status = "captured"
         try:
             db.session.add(payment)
             db.session.commit()
         except SQLAlchemyError as e:
             data = e.orig.args
             return response.set_data(None).set_message(data).set_error(
                 True).build()
         items = db.session.query(OrderDetails).filter_by(
             order_id=payment.order_id).first()
         url_invoice = request.host + '/invoices/' + order_.id
         if items.ticket.type == TICKET_TYPES['exhibitor']:
             payload = {}
             payload['user_id'] = user.id
             payload['ticket_id'] = items.ticket_id
             UserTicketService().create(payload)
             self.create_booth(user)
             user_query = db.session.query(User).filter_by(id=user.id)
             user_query.update({'role_id': ROLE['booth']})
             redeem_payload = {}
             redeem_payload['ticket_id'] = items.ticket_id
             redeem_payload['codeable_id'] = user.id
             RedeemCodeService().purchase_user_redeems(redeem_payload)
             get_codes = db.session.query(RedeemCode).filter_by(
                 codeable_type='user', codeable_id=user.id).all()
             code = []
             for get_code in get_codes:
                 code.append("<li>%s</li>" % (get_code.code))
             li = ''.join(code)
             template = "<h3>You have complete the payment with order_id = %s</h3><h4>Here are the redeem codes for claiming full 3 days ticket at devsummit event as described in the package information : </h4>%s<h3>Use the above code to claim your ticket</h3><h3>Thank you for your purchase</h3>" % (
                 order_.id, li)
             template += "<h4>And here is your Invoice:</h4>"
             template += '<a href="' + url_invoice + '">Klik here to show the invoice</a>'
             email = emailservice.set_recipient(user.email).set_subject(
                 'Congratulations !! you received exhibitor code'
             ).set_sender('*****@*****.**').set_html(
                 template).build()
             mail.send(email)
         if items.ticket.type == TICKET_TYPES['hackaton']:
             payload = {}
             payload['user_id'] = user.id
             payload['ticket_id'] = items.ticket_id
             UserTicketService.create(payload)
             self.create_hackaton_team(user, items.ticket_id)
             user_query = db.session.query(User).filter_by(id=user.id)
             user_query.update({'role_id': ROLE['hackaton']})
             hacker_team = db.session.query(HackerTeam).order_by(
                 HackerTeam.created_at.desc()).first()
             redeem_payload = {}
             redeem_payload['codeable_type'] = TICKET_TYPES['hackaton']
             redeem_payload['codeable_id'] = hacker_team.id,
             redeem_payload['count'] = items.ticket.quota
             RedeemCodeService().create(redeem_payload)
             get_codes = db.session.query(RedeemCode).filter_by(
                 codeable_type='hackaton',
                 codeable_id=hacker_team.id).all()
             code = []
             for get_code in get_codes:
                 code.append("<li>%s</li>" % (get_code.code))
             li = ''.join(code)
             template = "<h3>You have complete the payment with order_id = %s</h3><h4>Here your redeem codes : </h4>%s<h3>Share the above code to your teammate, and put it into redeem code menu to let them join your team and claim their ticket</h3><h3>Thank you for your purchase</h3>" % (
                 order_.id, li)
             template += "<h4>And here is your Invoice:</h4>"
             template += '<a href="' + url_invoice + '">Klik here to show the invoice</a>'
             email = emailservice.set_recipient(user.email).set_subject(
                 'Congratulations !! you received hackaton code'
             ).set_sender('*****@*****.**').set_html(
                 template).build()
             mail.send(email)
         else:
             result = None
             for order in order_details:
                 for i in range(0, order.count):
                     payload = {}
                     payload['user_id'] = user.id
                     payload['ticket_id'] = order.ticket_id
                     result = UserTicketService().create(payload)
             if (result and (not result['error'])):
                 template = "<h3>Congratulation! you have the previlege to attend Indonesia Developer Summit</h3>"
                 template += "<h4>Here is your Invoice:</h4>"
                 template += '<a href="' + url_invoice + '">Klik here to show the invoice</a>'
                 template += "<h5>Thank you.</h5>"
                 email = emailservice.set_recipient(user.email).set_subject(
                     'Devsummit Ticket Invoice').set_sender(
                         '*****@*****.**').set_html(template).build()
                 mail.send(email)
         confirmed_order = db.session.query(Order).filter_by(
             id=payment.order_id)
         confirmed_order.update({'status': 'paid'})
         db.session.commit()
         send_notification = FCMService().send_single_notification(
             'Payment Status', 'Your payment has been confirmed', user.id,
             ROLE['admin'])
         return response.set_data(None).set_message(
             'Purchase Completed').build()
     else:
         return response.set_error(True).set_message(
             'Paypal amount did not match').build()
Пример #11
0
    def save_payload(self, data, payloads):
        new_payment = Payment()
        new_payment.transaction_id = data['transaction_id']
        new_payment.order_id = data['order_id']
        new_payment.gross_amount = data['gross_amount']
        new_payment.payment_type = data['payment_type']
        new_payment.transaction_time = data['transaction_time']
        new_payment.transaction_status = data['transaction_status']
        new_payment.bank = data['bank']
        new_payment.fraud_status = data[
            'fraud_status'] if 'fraud_status' in data else None
        new_payment.masked_card = payloads[
            'masked_card'] if 'masked_card' in payloads else None
        new_payment.saved_token_id = payloads[
            'saved_token_id'] if 'saved_token_id' in payloads else None
        new_payment.va_number = data[
            'va_number'] if 'va_number' in data else None

        db.session.add(new_payment)
        db.session.commit()
    def create(self, payloads, user):
        response = ResponseBuilder()
        if user['role_id'] == ROLE['hackaton']:
            return response.set_data(None).set_message(
                'Hackaton attendee cannot buy ticket').set_error(True).build()
        order_details = payloads['order_details']
        # check if it's hackaton
        if order_details[0]['ticket_id'] == 10:
            # check if proposal already submited
            # disable hackaton now
            return response.set_data(None).set_message(
                'Hackaton registration is over.').set_error(True).build()
            # if self.hackatonproposalservice.check_hackaton_proposal_exist(user['id']):
            # 	return response.set_error(True).set_message('Hackaton cannot be submitted twice, our admin is in the process of verifying it, you will receive notification once it is done').set_data(None).build()

        self.model_order = Order()
        self.model_order.user_id = payloads['user_id']
        self.model_order.status = 'pending'
        # Referal code checking
        referal = db.session.query(Referal).filter_by(
            referal_code=payloads['referal_code'])
        if referal.first() is not None:
            # verify quota and update quota
            if referal.first().quota > 0:
                referal.update({'quota': referal.first().quota - 1})
                self.model_order.referal_id = referal.first().as_dict()['id']
            else:
                # handle for referal code exceed limit / quota
                return response.set_error(True).set_data(None).set_message(
                    'quota for specified code have exceeded the limit').build(
                    )
        # place order
        db.session.add(self.model_order)
        try:
            db.session.commit()
            data = self.model_order.as_dict()
            # insert the order details
            order_id = data['id']
            order_items = []
            for item in order_details:
                order_item = OrderDetails()
                order_item.ticket_id = item['ticket_id']
                order_item.count = item['count']
                order_item.order_id = order_id
                # get ticket data
                ticket = self.get_ticket(item['ticket_id'])
                if payloads['payment_type'] == 'paypal':
                    order_item.price = ticket.usd_price
                else:
                    order_item.price = ticket.price
                db.session.add(order_item)
                db.session.commit()
                order_item_dict = order_item.as_dict()
                order_item_dict['ticket'] = order_item.ticket.as_dict()
                order_items.append(order_item_dict)
            if payloads['payment_type'] == 'offline':
                gross_amount = (item['count'] * ticket.price)
                if referal.first() is not None:
                    # discount on gross amount
                    gross_amount -= gross_amount * referal.first(
                    ).discount_amount
                payment = Payment()
                payment.order_id = order_id
                payment.payment_type = 'offline'
                payment.gross_amount = gross_amount
                payment.transaction_time = datetime.datetime.now()
                payment.transaction_status = 'pending'

                db.session.add(payment)
                db.session.commit()
                # check if ticket is free
                if order_details[0]['ticket_id'] == 10:
                    # hackaton proposal
                    hackatonproposal = {
                        'github_link': payloads['hacker_team_name'],
                        'order_id': order_id
                    }
                    hack_result = self.hackatonproposalservice.create(
                        hackatonproposal)

                elif gross_amount == 0 or (referal.first()
                                           and referal.first().discount_amount
                                           == 1):
                    # call verify service
                    ov_service = OrderVerificationService()
                    ov_service.admin_verify(self.model_order.id, request,
                                            payloads['hacker_team_name'])

            # save all items
            return {'error': False, 'data': data, 'included': order_items}
        except SQLAlchemyError as e:
            data = e.orig.args
            return {'error': True, 'data': data}
Пример #13
0
	def confirm(self, payload):
		response = ResponseBuilder()
		transaction_exist = db.session.query(Payment).filter_by(transaction_id=payload['transaction_id']).first()
		if transaction_exist:
			return response.set_error(True).set_message('this transaction have been used before').set_data(None).build()
		paypal_details = self.get_paypal_detail(payload['transaction_id'])
		if paypal_details == False:
			return response.set_error(True).set_message('Transaction id not found').set_data(None).build()
		paypal_details_amount = int(paypal_details['transactions'][0]['amount']['total'].split('.')[0])
		order_ = db.session.query(Order).filter_by(id=payload['order_id']).first()
		if order_ is None:
			return response.set_error(True).set_data(None).set_message('Order not found').build()
		user = order_.user
		order_details = db.session.query(OrderDetails).filter_by(order_id=payload['order_id']).all()
		check_total = 0
		for order in order_details:
			check_total += order.price * order.count	
		if check_total == paypal_details_amount:
			payment_exist = db.session.query(Payment).filter_by(transaction_id=payload['transaction_id']).first()
			if payment_exist:
				return response.set_data(None).set_message('Payment had been completed!').set_error(True).build()
			payment = Payment()
			payment.order_id = payload['order_id']
			payment.transaction_id = payload['transaction_id']
			payment.gross_amount = paypal_details_amount
			payment.payment_type = 'paypal'
			payment.transaction_status = "captured"			
			try:				
				db.session.add(payment)
				db.session.commit()
			except SQLAlchemyError as e:
				data = e.orig.args
				return response.set_data(None).set_message(data).set_error(True).build()
			items = db.session.query(OrderDetails).filter_by(order_id=payment.order_id).first()
			if items.ticket.type == TICKET_TYPES['exhibitor']:
				payload = {}
				payload['user_id'] = user.id
				payload['ticket_id'] = items.ticket_id
				UserTicketService().create(payload)
				self.create_booth(user)
				user_query = db.session.query(User).filter_by(id=user.id)
				user_query.update({
					'role_id': ROLE['booth']
				})
				redeem_payload = {}
				redeem_payload['ticket_id'] = items.ticket_id
				redeem_payload['codeable_id'] = user.id
				RedeemCodeService().purchase_user_redeems(redeem_payload)

				# user_role = db.session.query(User).filter_by(id=user.id)
				# user_role.update({
				# 	'updated_at': datetime.datetime.now(),
				# 	'role_id': 3
				# })
				# ticket_quota = order_details.ticket.quota
				# for i 
			else:				
				for order in order_details:
					for i in range(0, order.count):
						payload = {}
						payload['user_id'] = user.id
						payload['ticket_id'] = order.ticket_id
						UserTicketService().create(payload)
			confirmed_order = db.session.query(Order).filter_by(id=payment.order_id)
			confirmed_order.update({
				'status': 'paid'
			})
			db.session.commit()
			return response.set_data(None).set_message('Purchase Completed').build()
		else:
			return response.set_error(True).set_message('Paypal amount did not match').build()