from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt # Create your views here. import braintree gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="twdv64kb25vmx2h3", public_key="yqmd5tc7kc4k6nvd", private_key="64c1b0d90342975be33e28ceb5bb0b80")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token):
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="x6f6yh46jdqvg2rj", public_key="qs2qtdhm3mbmwby2", private_key="4535351ba8fb82ff84866277523c5f29")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token): if not validate_user_session(id, token):
USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') CART_SESSION_ID = 'cart' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #Braintree settings BRAINTREE_MERCHANT_ID = '3rj8d7xvr6ybmnsq' #Merchant ID BRAINTREE_PUBLIC_KEY = 'xcq9jxgjwxb3346n' #Public Key BRAINTREE_PRIVATE_KEY = 'fd01b34a78657750af6ce49c787f6f70' #Private Key BRAINTREE_CONF = braintree.Configuration(braintree.Environment.Sandbox, BRAINTREE_MERCHANT_ID, BRAINTREE_PRIVATE_KEY, BRAINTREE_PUBLIC_KEY) STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
import braintree from dotenv import load_dotenv, find_dotenv import os from os.path import join, dirname, exists APP_ENV = os.environ.get('APP_ENV', 'dev') DOTENV_PATH = join(dirname(__file__), f'.{APP_ENV}.env') if exists(DOTENV_PATH): load_dotenv(dotenv_path=DOTENV_PATH) else: load_dotenv(find_dotenv()) DATABASE_URI = os.environ['DATABASE_URI'] BRAINTREE_CONFIG = braintree.Configuration( braintree.Environment.Sandbox, merchant_id=os.environ.get('BRAINTREE_MERCHANT_ID'), public_key=os.environ.get('BRAINTREE_PUBLIC_KEY'), private_key=os.environ.get('BRAINTREE_PRIVATE_KEY'))
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Sandbox, merchant_id='msqfrmbmgdpt6zs7', public_key='fhcqbjx5z65958q2', private_key='1b55b4f4d7f3f45ed689333bc65cb736' ) ) def validate_user_session(id,token): UserModel = get_user_model try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request,id,token): if not validate_user_session(id,token): return JsonResponse({'error':'Invalid session,Please login again'})
import braintree import os gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=os.getenv('merchant_id'), public_key=os.getenv('public_key'), private_key=os.getenv('private_key')))
import os from dotenv import load_dotenv import braintree gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=os.environ.get("BT_MERCHANT_ID"), public_key=os.environ.get("BT_PUBLIC_KEY"), private_key=os.environ.get("BT_PRIVATE_KEY")))
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="fr7wrv6wcxpn9r5p", public_key="6fg87p6km798ysbh", private_key="b75dc8686df3bab8c07ad7c825f67f73")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token): if not validate_user_session(id, token):
@app.teardown_request def _db_close(exc): if not db.is_closed(): print(db) print(db.close()) return exc @login_manager.user_loader def load_user(user_id): return User.get_by_id(user_id) gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=os.environ.get("SB_MERCHANT"), public_key=os.environ.get("SB_PUBLIC"), private_key=os.environ.get("SB_KEY"))) oauth.register('google', client_id=config.GOOGLE_CLIENT_ID, client_secret=config.GOOGLE_CLIENT_SECRET, access_token_url='https://accounts.google.com/o/oauth2/token', access_token_params=None, refresh_token_url=None, authorize_url='https://accounts.google.com/o/oauth2/auth', api_base_url='https://www.googleapis.com/oauth2/v1/', client_kwargs={ 'scope': 'https://www.googleapis.com/auth/userinfo.email', 'token_endpoint_auth_method': 'client_secret_basic', 'token_placement': 'header', 'prompt': 'consent'
import random import string from datetime import date import datetime import braintree from shopping_cart.models import OrderItem def generate_order_id(): date_str = date.today().strftime('%Y%m%d')[2:] + str(datetime.datetime.now().second) rand_str = "".join([random.choice(string.digits) for count in range(3)]) return date_str + rand_str gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="55mrzc3ph5vfvgkd", public_key="286xsgxxrb6rdsk9", private_key="4d0976b370cce3ef8abef87a5806ccfb" ) ) def generate_client_token(): print(gateway) return gateway.client_token.generate() def transact(options): return gateway.transaction.sale(options) def find_transaction(id): return gateway.transaction.find(id)
class BrainTree(models.Model): merchant_id = settings.BRAINTREE_MERCHANT_ID public_key = settings.BRAINTREE_PUBLIC_KEY private_key = settings.BRAINTREE_PRIVATE_KEY braintree_environment = None if settings.BRAINTREE_ENVIRONMENT == 'sandbox': braintree_environment = braintree.Environment.Sandbox if settings.BRAINTREE_ENVIRONMENT == 'production': braintree_environment = braintree.Environment.Production gateway = braintree.BraintreeGateway( braintree.Configuration(braintree_environment, merchant_id=merchant_id, public_key=public_key, private_key=private_key)) def __unicode__(self): # Python 3: def __str__(self): return 'nothing here' def generate_client_token(self, customer=None): client_data = {} if customer: client_data = { "customer_id": customer.id, } return self.gateway.client_token.generate(client_data) def transact(self, options): return self.gateway.transaction.sale(options) def find_transaction(self, id): return self.gateway.transaction.find(id) def delete_card(self, token): try: delete_response = self.gateway.credit_card.delete(token) return delete_response except Exception as ex: f = open('/tmp/deletecard', 'w') f.write(repr(ex)) f.close() return None def get_subscription(self, subscription_id): try: subscription = self.gateway.subscription.find(subscription_id) return subscription except Exception as ex: f = open('/tmp/subscription_errors', 'w') f.write(repr(ex)) f.close() return None def cancel_subscription(self, subscription_id): try: result = self.gateway.subscription.cancel(subscription_id) return result except Exception as ex: f = open('/tmp/subscription_errors', 'w') f.write(repr(ex)) f.close() return None def create_transaction(self, payment, user): #user = DC801User.objects.get(id=user.id) now = timezone.now() result = None try: result = self.gateway.transaction.sale({ "amount": payment['amount'], "payment_method_nonce": payment['nonce'], "customer": { 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, }, "options": { "submit_for_settlement": True, } }) success = 0 if result.is_success: success = 1 transaction = Transaction( transaction_id=result.transaction.id, user=user, amount=payment['amount'], payment_date=now, timestamp=time.time(), success=success, status=result.transaction.status, ) transaction.save() return result except Exception as ex: f = open('/tmp/payment_errors', 'w') f.write(repr(ex)) f.close() def get_braintree_customer(self, customer_id): try: customer = self.gateway.customer.find(str(customer_id)) return customer except braintree.exceptions.NotFoundError: return None def get_plans(self): try: result = self.gateway.plan.all() return result except braintree.exceptions.NotFoundError: return None def get_transactions(self, customer_id): try: result = self.gateway.transaction.search( braintree.TransactionSearch.customer_id == str(customer_id)) return result except braintree.exceptions.NotFoundError: return None def get_payment_method(self, payment_method_token): try: result = self.gateway.payment_method.find(payment_method_token) return result except braintree.exceptions.NotFoundError: return None def get_subscriptions(self, customer_id): try: result = self.gateway.subscription.search( braintree.SubscriptionSearch.customer_id == str(customer_id)) return result except braintree.exceptions.NotFoundError: return None def set_subscription(self, customer, payment_method_nonce, plan_id, subscription=None): try: # if plan changes, we need to clear out the old plan and add a new plan if subscription and plan_id != subscription.plan_id: cancel_result = self.cancel_subscription(subscription.id) if cancel_result.is_success or cancel_result.message == 'Subscription has already been canceled.': subscription = None else: raise Exception("Unable to update subscription") # create new subscription if there isn't one, or the one on file has been canceled (if payment method is removed, subscription will be canceled) if subscription is None or subscription.status == 'Canceled': result = self.gateway.subscription.create({ # "payment_method_token": token_result.payment_method.token, "payment_method_nonce": payment_method_nonce, "plan_id": plan_id, }) else: result = self.gateway.subscription.update( subscription.id, { "payment_method_nonce": payment_method_nonce, }) return result except braintree.exceptions.NotFoundError: pass return None def create_customer(self, user, payment_method_nonce=None): customer_data = { "id": str(user.id), "first_name": user.first_name, "last_name": user.last_name, "email": user.email, } # associate a payment method with customer if payment_method_nonce: customer_data["payment_method_nonce"] = payment_method_nonce return self.gateway.customer.create(customer_data) def create_payment_method(self, user, payment_method_nonce): data = { "customer_id": str(user.id), "payment_method_nonce": payment_method_nonce, } return self.gateway.payment_method.create(data) def set_default_payment_method(self, token): data = {"options": {"make_default": True}} return self.gateway.payment_method.update(token, data)
from flask import request, render_template, Blueprint, url_for, flash, redirect from models.donation import Donation from models.image import Image from models.user import User from flask_login import current_user, login_required import braintree import os import requests payments_blueprint = Blueprint('payments', __name__, template_folder="templates") gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=os.getenv("BRAINTREE_ID"), public_key=os.getenv("BRAINTREE_PUBLIC_KEY"), private_key=os.getenv("BRAINTREE_PRIVATE_KEY"))) @payments_blueprint.route("/<username>/<imageid>") @login_required def payment_form(username, imageid): image = Image.get_by_id(imageid) client_token = gateway.client_token.generate() return render_template('payments/new.html', client_token=client_token, image=image) @payments_blueprint.route("/<username>/<imageid>/pay", methods=["POST"]) @login_required
# Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. This means flask provides you with tools, libraries and technologies that allow you to build a web application. from flask import Flask, render_template, request # In this line you are first making available the code you need to build web apps with flask. flask is the framework here, while Flask is a Python class datatype. In other words, Flask is the prototype used to create instances of web application or web applications if you want to put it simple. # To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. When you include this Flask will look for templates in the templates folder - in our case, the HTML files. # Request is going to tell us to access one of our HTML forms and get something to use later import braintree # This is importing the Braintree package gateway = braintree.BraintreeGateway( braintree.Configuration(environment=braintree.Environment.Sandbox, merchant_id='qr7h9y9634y43hy3', public_key='8wtdvybw5yht6crc', private_key='your_private_key')) # Here is where we configure the environment and API credentials - this tells Braintree what account to send the transaction to. Think of this like the Braintree username and password so the Braintree servers know where to go with this information (in our case a transaction). app = Flask(__name__) # Once we import Flask, we need to create an instance of the Flask class for our web app. That’s what this line does. __name__ is a special variable that gets as value the string "__main__" when you’re executing the script. @app.route("/") def index(): client_authorization = "sandbox_rx8dxxqr_qr7h9y9634y43hy3" return render_template('index.html', client_authorization=client_authorization) # Here we are defining a function that authorizes our client. That function is mapped to the home ‘/’ URL. That means when the user navigates to localhost:5000/, the home function will run and in our case, it will return the Drop-in UI. This entire function says, go find the index.html page, render the template on that page, and use this tokenization key.
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="mtgfpp97zk5ymh2q", public_key="hq8cf4xhkzsw6s7s", private_key="ab2c5ead9f4bef1a2f9d0549424eae20")) def validate_user_session(id, token): UserModel = get_user_model try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token): if not validate_user_session(id, token): return JsonResponse({'error': 'invalid session please login again!'})
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(environment=braintree.Environment.Sandbox, merchant_id='q3z7drcn9nrzyc97', public_key='zn2xdpxdfh369xgh', private_key='4ca14a8fe0d18d12c79eb01eba5f254e')) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token): if not validate_user_session(id, token):
# 这是用户会话中购物车的键 CART_SESSION_ID = 'cart' #CELERY_ALWAYS_EAGER = False # 把邮件发到控制台 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Braintree配置 BRAINTREE_MERCHANT_ID = '9jhqg4dwwtmw7tzh' BRAINTREE_PUBLIC_KEY = '97mthtm54wf9bwnx' BRAINTREE_PRIVATE_KEY = '99b749a8e1392006491189cbcad8ee7d' BRAINTREE_CONF = braintree.Configuration( # 因为当前是开发阶段,所以使用沙箱环境 # 上线的时候会把这个改成Environment.Production braintree.Environment.Sandbox, BRAINTREE_MERCHANT_ID, BRAINTREE_PUBLIC_KEY, BRAINTREE_PRIVATE_KEY) # 要找到pdf的css需要使用这个路径 STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, 'static/')) # 配置redis REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 1 REDIS_USERNAME = '******' REDIS_PASSWORD = '******'
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Sandbox, merchant_id='2954qdx8822x2zk7', public_key='qmby5vkj9hdvp5bc', private_key='d4851961c20ca93f9b207c4ee91cb3d1' ) ) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.all(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="rj6zsdkqv6ncxvgb", public_key="p9ttrbbwf86rq6bd", private_key="d0ec81a9e4df0910f8d3b5db1742015f")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="q5n7sc57z5mbwf7s", public_key="bqhqxvp3thz7g4vp", private_key="facb2500a248f9b8f1cd3e414d4c47c1" ) ) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt
import string from datetime import date import time from pprint import pprint import time #Firebase realtime database import firebase_admin from firebase_admin import credentials from firebase_admin import db #Braintree import braintree gateway = braintree.BraintreeGateway( braintree.Configuration(environment=braintree.Environment.Sandbox, merchant_id='c9zswznhcgy499sv', public_key='h32bbxg6wckmx83w', private_key='ca34384614ba3f669b861e9d5c2d1dc4')) cartList = [] errorCode = 0 itemDeficiency = '' os.environ[ 'GOOGLE_APPLICATION_CREDENTIALS'] = "C:/Users/Aniket/Desktop/Aniket/food-grain-app/farmfresh-9c7fd-firebase-adminsdk-dx65j-9533ee02a1.json" cred = credentials.Certificate( 'farmfresh-9c7fd-firebase-adminsdk-dx65j-9533ee02a1.json') firebase_admin.initialize_app( cred, {'databaseURL': 'https://farmfresh-9c7fd.firebaseio.com/'})
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="g88p68zxydmbzfxt", public_key="ysz9ptr2kgx5n86j", private_key="b2eabd0fbf591ef275360723c4c1d5f3")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token):
import braintree from config import BT_MERCHANT_ID, BT_PUBLIC_KEY, BT_PRIVATE_KEY gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=BT_MERCHANT_ID, public_key=BT_PUBLIC_KEY, private_key=BT_PRIVATE_KEY)) def generate_client_token(): return gateway.client_token.generate() # client_token = gateway.client_token.generate({ # "customer_id": a_customer_id # }) # @app.route("/client_token", methods=["GET"]) # def client_token(): # return gateway.client_token.generate() # @app.route("/checkout", methods=["POST"]) # def create_purchase(): # nonce_from_the_client = request.form["payment_method_nonce"] # # Use payment method nonce here... def complete_transaction(nonce, amount): result = gateway.transaction.sale({ "amount": amount,
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Sandbox, merchant_id='xy66nsd58tqz86fz', public_key='r6gtk5qsh3jn6c9p', private_key='3ef1eae2c92981a827e6e725dbc56b29' ) ) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session.token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token):
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree # Create your views here. gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="4hdxs42xr4rg85y3", public_key="ncbrqfxfjdmf8fj4", private_key="1916df83de3eb5b8f11e3d06ead0b39c")) def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False @csrf_exempt def generate_token(request, id, token): if not validate_user_session(id, token): return JsonResponse({'error': 'invalid session, login again!'})
from django.shortcuts import render # Create your views here. from django.http import HttpResponse,JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="vcd2gx4568s7ybx9", public_key="y2jpypws7b5pxpnm", private_key="44ab3bb8db8457afa4865555a7b4c739" ) ) def validate_user_session(id,token): UserModel = get_user_model() try: user = UserModel.object.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.views.decorators.csrf import csrf_exempt import braintree #gateway object for payment platform gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id="ynpknfh2j545n92y", public_key="t3gf7xx26b7j99xd", private_key="55f26f2f93beacaf0156a4d384dfad98")) #validation of user token for payment def validate_user_session(id, token): UserModel = get_user_model() try: user = UserModel.objects.get(pk=id) if user.session_token == token: return True return False except UserModel.DoesNotExist: return False #cross site forgery protection for token generation @csrf_exempt
from datetime import date import datetime import braintree from shopping_cart.models import OrderItem def generate_order_id(): date_str = date.today().strftime('%Y%m%d')[2:] + str( datetime.datetime.now().second) rand_str = "".join([random.choice(string.digits) for count in range(3)]) return date_str + rand_str gateway = braintree.BraintreeGateway( braintree.Configuration(environment=settings.BT_ENVIRONMENT, merchant_id=settings.BT_MERCHANT_ID, public_key=settings.BT_PUBLIC_KEY, private_key=settings.BT_PRIVATE_KEY)) def generate_client_token(): return gateway.client_token.generate() def transact(options): return gateway.transaction.sale(options) def find_transaction(id): return gateway.transaction.find(id)
import braintree from django.conf import settings from datetime import date, timedelta gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Production, merchant_id=settings.MERCHANT_ID, public_key=settings.PUBLIC_KEY, private_key=settings.PRIVATE_KEY)) def client_token(user=None): if not user: return gateway.client_token.generate() if user.braintree_id: customer_id = user.braintree_id else: print({ 'first_name': user.name, 'last_name': user.surname, 'company': '', 'email': user.email, #'phone': '', #'fax': '', #'website': '' }) result = gateway.customer.create({ 'first_name': user.name, 'last_name': user.surname, #'company': '', 'email': user.email,
import braintree import os gateway = braintree.BraintreeGateway( braintree.Configuration(braintree.Environment.Sandbox, merchant_id=os.getenv('MERCHANT_ID'), public_key=os.getenv('PUBLIC_KEY'), private_key=os.getenv('PRIVATE_KEY')))
def validate_credentials(): transaction_id = request.headers.get("x-transactionid", "") if not transaction_id: app.logger.info("no transaction id header present") transaction_id = str(uuid.uuid4()) app.logger.info( "{}: got new transaction to validate braintree credentials".format( transaction_id)) if not request.is_json or not request.data: app.logger.info("{}: no valid json submitted abort transaction".format( transaction_id)) return jsonify({ "status": "ERROR", "status_code": 400, "message": "please submit a valid json body", "transaction_id": transaction_id }), 400 data = request.get_json() if not "merchant_id" in data or not "environment" in data or not "public_key" in data or not "private_key" in data: app.logger.info( "{}: the post request has missing fields".format(transaction_id)) return jsonify({ "status": "ERROR", "status_code": 400, "message": "you have to submit merchant_id, environment, public_key and private key", "transaction_id": transaction_id }), 400 if data["environment"] not in ["production", "sandbox"]: app.logger.info( "{}: no valid environment submitted, going to abort transaction". format(transaction_id)) return jsonify( status="ERROR", status_code=400, message="environment must be either production or sandbox", transaction_id=transaction_id) try: if data["environment"] == 'production': environment = braintree.Environment.Production else: environment = braintree.Environment.Sandbox gateway = braintree.BraintreeGateway( braintree.Configuration(environment=environment, merchant_id=data["merchant_id"], public_key=data["public_key"], private_key=data["private_key"])) try: client_token = gateway.client_token.generate({}) app.logger.info( "{}: successfully validated credentials: {}".format( transaction_id, client_token)) return jsonify(status="INFO", status_code=200, message="successfully validated credentials", token=client_token, transaction_id=transaction_id), 200 except Exception as e: app.logger.info(e) app.logger.info("{}: error while trying to retrieve token".format( transaction_id)) return jsonify(status="ERROR", status_code=401, message="not possible to authenticate user", transaction_id=transaction_id), 400 except Exception as e: app.logger.info(e) app.logger.info( "{}: error while trying to generate token".format(transaction_id)) return jsonify(status="ERROR", status_code=500, message="not possible to authenticate user", transaction_id=transaction_id), 500