def existing_payment_source(existing_customer: Customer, source_token: str) -> Customer: """ If Customer does not have an existing Payment Source and has not been Deleted: - Set the Customer's payment source to the new token - return the updated Customer Else - return the provided customer :param existing_customer: :param source_token: :return: """ if not existing_customer.get("sources"): if not existing_customer.get("deleted"): existing_customer = vendor.modify_customer( customer_id=existing_customer["id"], source_token=source_token, idempotency_key=utils.get_indempotency_key(), ) logger.info("add source", existing_customer=existing_customer) else: logger.info( "stripe customer is marked as deleted. cannot add source.") logger.debug("existing payment source", existing_customer=existing_customer) return existing_customer
def existing_payment_source(existing_customer: Customer, source_token: str) -> Customer: if not existing_customer.get("sources"): if not existing_customer.get("deleted"): existing_customer = Customer.modify( existing_customer["id"], source=source_token ) logger.info("add source", existing_customer=existing_customer) else: logger.info("existing source deleted") return existing_customer
def existing_payment_source(existing_customer: Customer, source_token: str) -> Customer: if not existing_customer.get("sources"): if not existing_customer.get("deleted"): existing_customer = vendor.modify_customer( customer_id=existing_customer["id"], source_token=source_token, idempotency_key=utils.get_indempotency_key(), ) logger.info("add source", existing_customer=existing_customer) else: logger.info("existing source deleted") return existing_customer
def modify_customer(customer_id: str, source_token: str, idempotency_key: str) -> Customer: """ Update customer source :param customer_id: :param source_token: :param idempotency_key: :return: updated Customer """ try: customer = Customer.modify(customer_id, source=source_token, idempotency_key=idempotency_key) return customer except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, IdempotencyError, CardError, StripeErrorWithParamCode, ) as e: logger.error("modify customer token", error=e) raise e
def create_stripe_customer(source_token: str, email: str, userid: str, name: str, idempotency_key: str) -> Customer: """ Create a new Stripe Customer. :param source_token: :param email: :param userid: :param name: :param idempotency_key: :return: Customer """ try: customer = Customer.create( source=source_token, email=email, description=userid, name=name, metadata={"userid": userid}, idempotency_key=idempotency_key, ) return customer except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, IdempotencyError, CardError, StripeErrorWithParamCode, ) as e: logger.error("create customer error", error=e) raise e
def token_for_customer(self, token, user): """Create a user in Stipe's system using a one time use token as returned from `stripe.js`. This function does not alter the user object in any way. :params token: The one time use token returned by stripe.js when submitting payment details. :type token: string :param user: The user with which the new stripe customer will be associated, used only for error logging. :type user: :class:`pooldlib.postgresql.models.User` :returns: string, the Customer ID returned by Stripe. :raises: stripe.AuthenticationError stripe.InvalidRequestError stripe.APIConnectionError stripe.APIError """ kwargs = dict(card=token, description='Poold user: %s' % user.id, email=user.email) try: stripe_user = _Customer.create(api_key=self.api_key, **kwargs) msg = 'New Stripe Customer Created' logger.transaction(msg, **kwargs) except stripe.StripeError, e: self._handle_error(e, user, kwargs)
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 billing_profile_created_receiver(sender, instance, *args, **kwargs): if not instance.customer_id and instance.email: # print("ACTUAL API REQUEST Send to Stripe") customer = Customer.create( email=instance.email ) # print(customer) instance.customer_id = customer.id
def fetch_customer(subhub_account: SubHubAccount, user_id: str) -> Customer: customer = None db_account = subhub_account.get_user(user_id) if db_account: customer = Customer.retrieve(db_account.cust_id) if "deleted" in customer and customer["deleted"]: subhub_account.remove_from_db(user_id) customer = None return customer
def update_payment_method(uid, data) -> FlaskResponse: """ Given a user id and a payment token, update user's payment method :param uid: :param data: :return: Success or failure message. """ customer = fetch_customer(g.subhub_account, uid) logger.info("customer", customer=customer) if not customer: return dict(message="Customer does not exist."), 404 metadata = customer.get("metadata") logger.info("metadata", metadata=metadata, customer=type(customer)) if metadata: if metadata["userid"] == uid: Customer.modify(customer.id, source=data["pmt_token"]) return {"message": "Payment method updated successfully."}, 201 return dict(message="Customer mismatch."), 400
def get_customer_list(email: str) -> Optional[List[Customer]]: try: customer_list = Customer.list(email=email) return customer_list except ( APIConnectionError, APIError, RateLimitError, StripeErrorWithParamCode, ) as e: logger.error("get customer list error", error=e) raise e
def has_existing_plan(customer: Customer, plan_id: str) -> bool: """ Check if user has the existing plan in an active or trialing state. :param customer: :param plan_id: :return: True if user has existing plan, otherwise False """ if customer.get("subscriptions"): for item in customer["subscriptions"]["data"]: if item["plan"]["id"] == plan_id and item["status"] in [ "active", "trialing", ]: return True return False
def form_valid(self, form): trans = form.cleaned_data["transactionDetails"] try: stripe_customer = StripeCustomer.retrieve(trans["customer_id"]) cus = Customer.objects.create( user=self.request.user, stripe_id=stripe_customer["id"] ) sync_customer(cus, stripe_customer) return redirect(reverse("pinax_stripe_subscription_list")) except StripeError as e: messages.error(self.request, "Unable to communicate with stripe. Please try again later") logger.error("Stripe Error during checkout for customer {}".format( self.request.user ), exc_info=True) return redirect(reverse("pinax_stripe_subscription_list"))
def create_customer( subhub_account: SubHubAccount, user_id: str, email: str, source_token: str, origin_system: str, display_name: str, ) -> Customer: _validate_origin_system(origin_system) # First search Stripe to ensure we don't have an unlinked Stripe record # already in Stripe customer = None customers = Customer.list(email=email) for possible_customer in customers.data: if possible_customer.email == email: # If the userid doesn't match, the system is damaged. if possible_customer.metadata.get("userid") != user_id: raise ServerError("customer email exists but userid mismatch") customer = possible_customer # If we have a mis-match on the source_token, overwrite with the # new one. if customer.default_source != source_token: Customer.modify(customer.id, source=source_token) break # No existing Stripe customer, create one. if not customer: try: customer = Customer.create( source=source_token, email=email, description=user_id, name=display_name, metadata={"userid": user_id}, ) except InvalidRequestError as e: logger.error("create customer error", error=e) raise InvalidRequestError( message="Unable to create customer.", param=str(e) ) # Link the Stripe customer to the origin system id db_account = subhub_account.new_user( uid=user_id, origin_system=origin_system, cust_id=customer.id ) if not subhub_account.save_user(db_account): # Clean-up the Stripe customer record since we can't link it Customer.delete(customer.id) e = IntermittentError("error saving db record") logger.error("unable to save user or link it", error=e) raise e return customer
def delete_customer(uid) -> FlaskResponse: """ Delete an existing customer, cancel active subscriptions and delete from payment provider :param uid: :return: Success of failure message for the deletion """ subscription_user = g.subhub_account.get_user(uid) if not subscription_user: return dict(message="Customer does not exist."), 404 deleted_payment_customer = Customer.delete(subscription_user.cust_id) if deleted_payment_customer: deleted_customer = delete_user_from_db(uid) user = g.subhub_account.get_user(uid) if deleted_customer and user is None: return dict(message="Customer deleted successfully"), 200 return dict(message="Customer not available"), 400
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 delete_stripe_customer(customer_id: str) -> Dict[str, Any]: """ Delete a Stripe customer :param customer_id: :return: object """ try: deleted_customer = Customer.delete(sid=customer_id) return deleted_customer except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, StripeErrorWithParamCode, ) as e: logger.error("delete customer error", error=e) raise e
def retrieve_stripe_customer(customer_id: str) -> Optional[Customer]: """ Retrieve Stripe Customer :param customer_id: :return: Customer """ try: customer = Customer.retrieve(id=customer_id) return customer except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, StripeErrorWithParamCode, ) as e: logger.error("retrieve stripe customer error", error=e) raise e
def fetch_customer(subhub_account: SubHubAccount, user_id: str) -> Customer: customer = None db_account = subhub_account.get_user(user_id) if db_account: customer = Customer.retrieve(db_account.cust_id) return customer
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