def post(self, request): """ Make a purchase of the cart. Args: request: rest_framework.request.Request Returns: rest_framework.response.Response """ token, cart = self.validate_data() with transaction.atomic(): order = create_order(cart, request.user) amount_in_cents = get_cents(order.total_paid) if amount_in_cents != 0: Charge.create( amount=amount_in_cents, currency="usd", source=token, description="Course purchase for MIT Teacher's Portal", metadata={ "order_id": order.id } ) errors = self.notify_external_services(order, request.user) if len(errors): return Response({ 'error': "Unable to post to CCXCon", 'error_list': errors, }, status=500) return Response(status=200)
def create_update_data(customer) -> dict: """ Provide readable data for customer update to display :param customer: :return: return_data dict """ payment_sources = customer["sources"]["data"] return_data = dict() return_data["subscriptions"] = [] if len(payment_sources) > 0: first_payment_source = payment_sources[0] return_data["payment_type"] = first_payment_source.get("funding") return_data["last4"] = first_payment_source.get("last4") return_data["exp_month"] = first_payment_source.get("exp_month") return_data["exp_year"] = first_payment_source.get("exp_year") else: return_data["payment_type"] = "" return_data["last4"] = "" return_data["exp_month"] = "" return_data["exp_year"] = "" for subscription in customer["subscriptions"]["data"]: if subscription["status"] == "incomplete": invoice = Invoice.retrieve(subscription["latest_invoice"]) if invoice["charge"]: intents = Charge.retrieve(invoice["charge"]) return_data["subscriptions"].append({ "current_period_end": subscription["current_period_end"], "current_period_start": subscription["current_period_start"], "ended_at": subscription["ended_at"], "plan_name": subscription["plan"]["nickname"], "plan_id": subscription["plan"]["id"], "status": subscription["status"], "cancel_at_period_end": subscription["cancel_at_period_end"], "subscription_id": subscription["id"], "failure_code": intents["failure_code"], "failure_message": intents["failure_message"], }) else: return_data["cancel_at_period_end"] = subscription[ "cancel_at_period_end"] return_data["subscriptions"].append( create_subscription_object_without_failure(subscription)) else: return_data["cancel_at_period_end"] = subscription[ "cancel_at_period_end"] return_data["subscriptions"].append( create_subscription_object_without_failure(subscription)) return return_data
def create_update_data(customer) -> Dict[str, Any]: """ Provide readable data for customer update to display :param customer: :return: return_data dict """ payment_sources = customer["sources"]["data"] return_data: Dict[str, Any] = dict() return_data["subscriptions"] = [] return_data["payment_type"] = "" return_data["last4"] = "" return_data["exp_month"] = "" return_data["exp_year"] = "" if len(payment_sources) > 0: first_payment_source = payment_sources[0] return_data["payment_type"] = first_payment_source.get("funding") return_data["last4"] = first_payment_source.get("last4") return_data["exp_month"] = first_payment_source.get("exp_month") return_data["exp_year"] = first_payment_source.get("exp_year") products = {} # type: Dict for subscription in customer["subscriptions"]["data"]: try: product = products[subscription["plan"]["product"]] except KeyError: product = Product.retrieve(subscription["plan"]["product"]) products[subscription["plan"]["product"]] = product plan_name = format_plan_nickname( product_name=product["name"], plan_interval=subscription["plan"]["interval"] ) if subscription["status"] == "incomplete": invoice = Invoice.retrieve(subscription["latest_invoice"]) if invoice["charge"]: intents = Charge.retrieve(invoice["charge"]) return_data["subscriptions"].append( { "current_period_end": subscription["current_period_end"], "current_period_start": subscription["current_period_start"], "ended_at": subscription["ended_at"], "plan_name": plan_name, "plan_id": subscription["plan"]["id"], "status": subscription["status"], "cancel_at_period_end": subscription["cancel_at_period_end"], "subscription_id": subscription["id"], "failure_code": intents["failure_code"], "failure_message": intents["failure_message"], } ) continue return_data["cancel_at_period_end"] = subscription["cancel_at_period_end"] return_data["subscriptions"].append( create_subscription_object_without_failure(subscription, plan_name) ) return return_data
def retrieve_stripe_charge(charge_id: str) -> Charge: """ Retrive Stripe Charge :param charge_id: :return: Charge """ if charge_id is None: logger.error( "hub::shared::vendor::retrieve_stripe_charge received a None charge_id, ignoring." ) return None else: try: charge = Charge.retrieve(charge_id) logger.debug("retrieve stripe charge", charge=charge) return charge except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, IdempotencyError, StripeErrorWithParamCode, ) as e: logger.error("retrieve stripe error", error=str(e)) raise e
def stripe(): print '--- got stripe request ---' stripe.api_key = stripe_keys['secret_key'] form = stripeform() output = render_template('stripe.html', key=stripe_keys['publishable_key'], form=form) if form.amount.data: drill("xTcR Donation","Thanks for donating to xTcR!",request.form["stripeEmail"]) #stripe.api_key = "sk_test_KBnACrVyXtFPcHyGTd5cot9D" customer = Customer.create( email= request.form["stripeEmail"], card=request.form['stripeToken'] ) charge = Charge.create( customer=customer.id, amount=form.amount.data * 100, currency='usd', description='xTcR Donation' ) amnt = form.amount.data * 100 custom = '0' if request.form.has_key('custom'): custom = str(request.form['custom']) cb_data = { #'app': 'donate', #'do': 'payment', #'gateway': '1', 'mc_gross': float(charge['amount']) / 100, 'mc_currency': charge['currency'], 'custom': custom, 'payment_status': 'Completed' if charge['status'] == 'succeeded' else charge['status'], 'business': charge['receipt_email'], 'option_selection1': '', 'option_selection2': '', 'txn_id': charge['id'], 'memo': 'stripe', 'fees': (float(charge['amount']) / 100) * 0.029 + 0.30, 'item_name': str(request.form['item_name']), 'item_number': str(request.form['item_number']) } r = requests.post("http://192.3.130.131/index.php?app=donate&do=payment&gateway=1", data=cb_data) try: r = requests.get("http://kc1.freebieservers.com/1/donate.php?name=%s&amount=%s"%(g.user.nickname,amnt)) print r print r.url except: print "Server Down" print ' ----- ' cmd("echo '%s' >> stripe.log"%r.text) output = redirect("http://xtcr.net/success.html") return output
def charge(self, charge_amount, app_fee, currency, user, charge_description): cust_token = _Token.create(customer=user.stripe_customer_id, api_key=self.api_key) kwargs = dict(amount=charge_amount, application_fee=app_fee, card=cust_token.id, currency=currency.code, description=charge_description) try: charge = _Charge.create(api_key=self.api_key, **kwargs) except stripe.StripeError, e: self._handle_error(e, user, kwargs)
def create_return_data(subscriptions) -> JsonDict: """ Create json object subscriptions object :param subscriptions: :return: JSON data to be consumed by client. """ return_data: Dict[str, Any] = {} return_data["subscriptions"] = [] products = {} # type: Dict for subscription in subscriptions["data"]: try: product = products[subscription["plan"]["product"]] except KeyError: product = Product.retrieve(subscription["plan"]["product"]) products[subscription["plan"]["product"]] = product plan_name = format_plan_nickname( product_name=product["name"], plan_interval=subscription["plan"]["interval"] ) if subscription["status"] == "incomplete": invoice = Invoice.retrieve(subscription["latest_invoice"]) if invoice["charge"]: intents = Charge.retrieve(invoice["charge"]) logger.debug("intents", intents=intents) return_data["subscriptions"].append( { "current_period_end": subscription["current_period_end"], "current_period_start": subscription["current_period_start"], "ended_at": subscription["ended_at"], "plan_name": plan_name, "plan_id": subscription["plan"]["id"], "status": subscription["status"], "subscription_id": subscription["id"], "cancel_at_period_end": subscription["cancel_at_period_end"], "failure_code": intents["failure_code"], "failure_message": intents["failure_message"], } ) continue return_data["subscriptions"].append( create_subscription_object_without_failure(subscription, plan_name) ) return return_data
def charge(): if not check_body(["plan", "transaction"]): return errors.missing_charge_parameters() plan = int(request.json["plan"]) token = request.json["transaction"]["id"] amount = [499, 2748, 4992][plan] customer = Customer.create(email=current_user.email, source=token) charge = Charge.create(customer=customer.id, amount=amount, currency="usd", description="Flask Charge") return "", 204
def retrieve_stripe_charge(charge_id: str) -> Charge: """ Retrive Stripe Charge :param charge_id: :return: Charge """ try: charge = Charge.retrieve(charge_id) return charge except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, IdempotencyError, StripeErrorWithParamCode, ) as e: logger.error("retrieve stripe error", error=str(e)) raise e
def create_return_data(subscriptions) -> JsonDict: """ Create json object subscriptions object :param subscriptions: :return: JSON data to be consumed by client. """ return_data = dict() return_data["subscriptions"] = [] for subscription in subscriptions["data"]: if subscription["status"] == "incomplete": invoice = Invoice.retrieve(subscription["latest_invoice"]) if invoice["charge"]: intents = Charge.retrieve(invoice["charge"]) logger.debug("intents", intents=intents) return_data["subscriptions"].append({ "current_period_end": subscription["current_period_end"], "current_period_start": subscription["current_period_start"], "ended_at": subscription["ended_at"], "plan_name": subscription["plan"]["nickname"], "plan_id": subscription["plan"]["id"], "status": subscription["status"], "subscription_id": subscription["id"], "cancel_at_period_end": subscription["cancel_at_period_end"], "failure_code": intents["failure_code"], "failure_message": intents["failure_message"], }) else: return_data["subscriptions"].append( create_subscription_object_without_failure(subscription)) else: return_data["subscriptions"].append( create_subscription_object_without_failure(subscription)) return return_data
def make_payment(self): holder = None try: holder = issuing.Cardholder.create( type="individual", name=self.card_holder, api_key=STRIPE_SK_KEY, billing={ "address": { "line1": "Jhangirpura", "city": "Surat", "state": "Gujarat", "country": "IN", "postal_code": "395005", } } ) except Exception as e: print(e) token = Token.create( card={ "number": self.card_number, "exp_month": self.exp_month, "exp_year": self.exp_year, "cvc": self.cvc }, api_key=STRIPE_SK_KEY ) charge = Charge.create( amount=self.amount, currency="inr", source=token.id, description=f"[{datetime.now().isoformat()}] holder_obj = {holder} holder_name={self.card_holder}", api_key=STRIPE_SK_KEY ) return charge
def stripe2(): g.user = None form = xForm() form2 = signForm() team = None emailz = None output = render_template("fail.html") if 'user_id' in session: g.user = User.query.get(session['user_id']) if g.user != None: team = g.user.ptype emailz = g.user.email stripe_token = request.form['stripeToken'] email = request.form['stripeEmail'] if team == 1: amnt = 5 print amnt else: amnt = 20 print amnt try: charge = Charge.create( amount=int(amnt * 100), currency='usd', card=stripe_token, description=email) g.user.paid = 1 db_session.commit() output = render_template('success.html') if team == 2: html = "<p>You will be receiving a friend request in steam from a user named xTcR | Tournament [IN]. You will need to accept this friend request to be verified on the date of the tournament.</p><p>The tournament will be on August 15th, 2015 at 1:00pm EST. You and your team will need to be in xTcR's teamspeak (ts3.xtcr.net > INS Tournament Waiting Room) 1 hour before the starting time in order to be verified.</p><p>*If you do not recieve a friend request from xTcR | Tournament [IN] please add the user here: http://steamcommunity.com/id/xtcr-tournament/ . You will not be able to be verified for the tournament if you skip this step.</p>" else: html = "<p>You will be receiving a friend request in steam from a user named xTcR | Tournament [IN]. You will need to accept this friend request to be verified on the date of the tournament.</p><p>The tournament will be on August 15th, 2015 at 1:00pm EST. You will need to be in teamspeak (ts3.xtcr.net > INS Tournament Waiting Room) 1 and a half hours before the starting time to allow time for teaming up.</p><p>*If you do not recieve a friend request from xTcR | Tournament [IN] please add the user here: http://steamcommunity.com/id/xtcr-tournament/ . You will not be able to be verified for the tournament if you skip this step.</p>" drill(g.user.email,html) except stripe.CardError, e: return render_template("fail.html")
def post(self, request, *args, **kwargs): try: token = request.data.get('stripe_token', None) transaction_id = request.data.get('transaction_id', None) txn_type = request.data.get('type', None) if not token or not transaction_id: raise TransactionException if not txn_type or txn_type not in t.INSTANT_PAYMENTS: raise TransactionException payment_class = getattr(mod, t.TXN_TYPE_2_MODEL[txn_type]) user_id = request.user.id transaction = payment_class.objects.get(id=transaction_id, sender__id=user_id, state=t.INIT) # redeem free transaction referral = request.user.referral if referral.free_transaction: transaction.service_charge = 0 transaction.free_from_referral = True amount_usd = int(transaction.total_charge_usd * 100) stripe.api_key = settings.STRIPE_SECRET_KEY description = 'GHS {} of {} to {} (Ref. No.: {})'.format( transaction.amount_ghs, (t.BILL_2_DESC[transaction.bill_type] if txn_type == t.BILL else 'Airtime'), str(transaction.recipient), transaction.reference_number) statement_descriptor = 'Beam Bill Ref. {}'.format( transaction.reference_number) charge = Charge.create(amount=amount_usd, currency='USD', source=token, description=description, receipt_email=request.user.email, statement_descriptor=statement_descriptor, capture=settings.STRIPE_SETTING_CAPTURE) transaction.payment_reference = charge.id transaction.payment_processor = t.STRIPE transaction.state = t.PAID transaction.save() transaction.add_status_change(t.PAID) transaction.post_paid() if referral.free_transaction: referral.redeem_transaction() return Response(status=status.HTTP_201_CREATED) except (InvalidRequestError, TypeError, ReferralException) as e: return Response({'detail': e[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except CardError as e: transaction.payment_processor = t.STRIPE transaction.state = t.INVALID transaction.save() transaction.add_status_change(t.INVALID) return Response({ 'detail': p.STRIPE_ERROR, 'message': e[0] }, status=status.HTTP_400_BAD_REQUEST) except (ObjectDoesNotExist, TransactionException): return Response({'detail': p.INVALID_PARAMETERS}, status=status.HTTP_400_BAD_REQUEST)
def stripe(): print '--- got stripe request ---' stripe.api_key = stripe_keys['secret_key'] form = stripeform() output = render_template('stripe.html', key=stripe_keys['publishable_key'], form=form) if form.amount.data: drill("xTcR Donation", "Thanks for donating to xTcR!", request.form["stripeEmail"]) #stripe.api_key = "sk_test_KBnACrVyXtFPcHyGTd5cot9D" customer = Customer.create(email=request.form["stripeEmail"], card=request.form['stripeToken']) charge = Charge.create(customer=customer.id, amount=form.amount.data * 100, currency='usd', description='xTcR Donation') amnt = form.amount.data * 100 custom = '0' if request.form.has_key('custom'): custom = str(request.form['custom']) cb_data = { #'app': 'donate', #'do': 'payment', #'gateway': '1', 'mc_gross': float(charge['amount']) / 100, 'mc_currency': charge['currency'], 'custom': custom, 'payment_status': 'Completed' if charge['status'] == 'succeeded' else charge['status'], 'business': charge['receipt_email'], 'option_selection1': '', 'option_selection2': '', 'txn_id': charge['id'], 'memo': 'stripe', 'fees': (float(charge['amount']) / 100) * 0.029 + 0.30, 'item_name': str(request.form['item_name']), 'item_number': str(request.form['item_number']) } r = requests.post( "http://192.3.130.131/index.php?app=donate&do=payment&gateway=1", data=cb_data) try: r = requests.get( "http://kc1.freebieservers.com/1/donate.php?name=%s&amount=%s" % (g.user.nickname, amnt)) print r print r.url except: print "Server Down" print ' ----- ' cmd("echo '%s' >> stripe.log" % r.text) output = redirect("http://xtcr.net/success.html") return output
def post(self, request): if not request.POST.get('event_id'): return HttpResponseBadRequest() event = get_object_or_404(Event, id=request.POST.get('event_id')) has_signed_up = EventSignup.objects.for_event(event, request.user).exists() if has_signed_up: messages.error(request, 'You\'re already signed up to that event.', extra_tags='is-danger') return redirect('event_home', slug=event.slug) profile = WarwickGGUser.objects.get(user=request.user) # If the event is hosted by UWCS if 'UWCS' in event.hosted_by: uwcs_member = check_membership(settings.UWCS_API_KEY, profile, request, 'UWCS') else: uwcs_member = False # If the event is hosted by Esports if 'WE' in event.hosted_by: esports_member = check_membership(settings.ESPORTS_API_KEY, profile, request, 'Esports') else: esports_member = False signup_cost = event.cost_member if esports_member or uwcs_member else event.cost_non_member # If the user should be charged but there's no stripe token then error if signup_cost > 0 and not request.POST.get('stripe_token'): return HttpResponseBadRequest() # If there was an issue processing the signup form then error - there shouldn't be any reason since # all of the fields are optional but ??? signup = EventSignup(user=request.user, event=event) signup_form = SignupForm(request.POST, instance=signup) if not signup_form.is_valid(): messages.error( request, 'There was an error processing your signup, double check everything is in order and try again.', extra_tags='is-danger') return redirect('event_signup', slug=event.slug) if signup_cost > 0: token = request.POST.get('stripe_token') try: charge = Charge.create(amount=int(signup_cost * 100), currency='gbp', source=token, receipt_email=request.user.email) except StripeError: # If there was an error with the request messages.error( request, 'There was an error processing the payment. Please check your balance and try again later.', extra_tags='is-danger') return redirect('event_signup', slug=event.slug) if charge.paid: signup = signup_form.save(commit=False) signup.transaction_token = charge.stripe_id signup.save() messages.success( request, 'Signup successful!{seating}'.format( seating= ' You can now reserve a seat on the seating plan.' if event.has_seating else ''), extra_tags='is-success') return redirect('event_home', slug=event.slug) else: messages.error( request, 'There was an error processing your payment. Make sure you have sufficient balance and try again.', extra_tags='is-danger') return redirect('event_signup', slug=event.slug) else: signup_form.save() messages.success( request, 'Signup successful!{seating}'.format( seating=' You can now reserve a seat on the seating plan.' if event.has_seating else ''), extra_tags='is-success') return redirect(event.get_absolute_url() + '#signup')
def post(self, request, *args, **kwargs): try: token = request.data.get('stripe_token', None) transaction_id = request.data.get('transaction_id', None) txn_type = request.data.get('type', None) if not token or not transaction_id: raise TransactionException if not txn_type or txn_type not in t.INSTANT_PAYMENTS: raise TransactionException payment_class = getattr(mod, t.TXN_TYPE_2_MODEL[txn_type]) user_id = request.user.id transaction = payment_class.objects.get( id=transaction_id, sender__id=user_id, state=t.INIT ) # redeem free transaction referral = request.user.referral if referral.free_transaction: transaction.service_charge = 0 transaction.free_from_referral = True amount_usd = int(transaction.total_charge_usd * 100) stripe.api_key = settings.STRIPE_SECRET_KEY description = 'GHS {} of {} to {} (Ref. No.: {})'.format( transaction.amount_ghs, (t.BILL_2_DESC[transaction.bill_type] if txn_type == t.BILL else 'Airtime'), str(transaction.recipient), transaction.reference_number ) statement_descriptor = 'Beam Bill Ref. {}'.format( transaction.reference_number) charge = Charge.create( amount=amount_usd, currency='USD', source=token, description=description, receipt_email=request.user.email, statement_descriptor=statement_descriptor, capture=settings.STRIPE_SETTING_CAPTURE ) transaction.payment_reference = charge.id transaction.payment_processor = t.STRIPE transaction.state = t.PAID transaction.save() transaction.add_status_change(t.PAID) transaction.post_paid() if referral.free_transaction: referral.redeem_transaction() return Response(status=status.HTTP_201_CREATED) except (InvalidRequestError, TypeError, ReferralException) as e: return Response( {'detail': e[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) except CardError as e: transaction.payment_processor = t.STRIPE transaction.state = t.INVALID transaction.save() transaction.add_status_change(t.INVALID) return Response( {'detail': p.STRIPE_ERROR, 'message': e[0]}, status=status.HTTP_400_BAD_REQUEST ) except (ObjectDoesNotExist, TransactionException): return Response( {'detail': p.INVALID_PARAMETERS}, status=status.HTTP_400_BAD_REQUEST )