def post(self, request, *args, **kwargs): access_token = 'STAGE_25361b68e606cc342a7e4ec982fac2139f9f72dd42156237da9468c832f56dce' production = False client_id = 167754 client_secret = "da07303f7e" email = self.request.user.email first_name = self.request.user.name last_name = "WeParty" wepay = WePay(production, access_token) response = wepay.call('/user/register', { "client_id":client_id, "client_secret":client_secret, "email":email, "scope":"manage_accounts,view_balance,collect_payments,view_user", "first_name":first_name, "last_name":last_name, "original_ip":"74.125.224.84", "original_device":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.102 Safari/534.13" }) print type(response) print response user_access_token = response[u'access_token'] wepay2 = WePay(production, user_access_token) response2 = wepay.call('/account/create', { "name": first_name + " WeParty", "description": "WeParty account" }) print response2 user = User.objects.get(id=request.user.id) user.wepayUserId = response[u'user_id'] user.wepayAccountId = response2[u'account_id'] user.wepayAccessToken = response[u'access_token'] user.save() return HttpResponseRedirect('/dashboard/')
def GET(self, query): wepay = WePay(IN_PRODUCTION) code = web.input(code='')['code'] try: # try to get a token with our code wepay.get_token(web.ctx.homedomain + '/callback', CLIENT_ID, CLIENT_SECRET, code) # make a new account create_response = wepay.call( '/account/create', { 'name': 'kitty expenses fund', 'description': 'all the money for my kitty' }) # give the account a new picture wepay.call( '/account/modify', { 'account_id': create_response['account_id'], 'image_uri': 'http://www.placekitten.com/500/500' }) # redirect to the new account web.redirect(create_response['account_uri']) except WePay.WePayError as e: return "Received a WePay Error: " + repr(e)
def test_default_timeout_is_passed_to_requests(): api = WePay() api.requests = Mock() api.call('/some_uri') eq_([call('https://wepayapi.com/v2/some_uri', headers={'Content-Type': 'application/json', 'User-Agent': 'WePay Python SDK'}, data=None, timeout=30)], api.requests.post.call_args_list)
def test_urllib_connection_error(self): api = WePay(production=False, use_requests=False, timeout=0.001) self.assertRaises(WePayConnectionError, api.call, '/app') try: api.call('/app') except WePayConnectionError as e: self.assertIsInstance(e.error, urllib.error.URLError) self.assertEqual(str(e), "URLError - <urlopen error timed out>") self.assertEqual(repr(e), "<WePayConnectionError> " + str(e))
def test_urllib(self): api = WePay(production=False, use_requests=False) self.assertRaises(WePayError, api.call, '/app') try: api.call('/app') except WePayClientError as e: self.assertIsInstance(e.http_error, urllib.error.HTTPError) self.assertEqual(e.status_code, 400) self.assertEqual(e.error, "invalid_request") self.assertEqual(e.error_code, 1004) self.assertEqual(e.error_description, "client_id parameter is required") self.assertEqual(repr(e), "<WePayClientError> " + str(e))
def test_headers(self): api = WePay(production=False) api._post = MagicMock() api._post.configure_mock(**{'__call__': {'result': 'fake_success'}}) access_token, api_version = 'dummy_access_token', '2011-01-15' expected_headers = { 'Content-Type': 'application/json', 'User-Agent': 'Python WePay SDK (third party)', 'Authorization': 'Bearer %s' % access_token, 'Api-Version': api_version } api.call('/user', access_token=access_token, api_version=api_version) api._post.assert_called_once_with( 'https://stage.wepayapi.com/v2/user', {}, expected_headers, 30)
def create_checkout(self, redirect_uri): """ Performs WePay checkout/create API call request. Returns checkout_uri to create checkout form. """ production = settings.WEPAY['in_production'] access_token = self.wepay_access_token wepay = WePay(production, access_token) name = self.user.first_name + " " + self.user.last_name desc = "Purchasing " + self.produce + " from " + name price = str(self.produce_price) account_id = str(self.get_account_id()) app_fee = str(Decimal('0.1') * self.produce_price) params = { 'account_id': account_id, 'short_description': desc, 'type': 'GOODS', 'app_fee': app_fee, 'amount': price, 'mode': 'iframe' } try: create_response = wepay.call('/checkout/create', params) checkout_uri = create_response['checkout_uri'] return True, checkout_uri except WePayError as e: return False, e
def wepay_membership_response(user): """ Make a WePay API call for membership payment and return the response. """ # Generate verification_key for wepay payment. random_string = base64.urlsafe_b64encode(os.urandom(30)) verification_key = hashlib.sha224(random_string + user.email + user.name).hexdigest() user.wepay_verification = verification_key db.session.commit() # WePay Application settings account_id = app.config['WEPAY_ACCT_ID'] access_token = app.config['WEPAY_ACC_TOK'] production = app.config['WEPAY_IN_PROD'] wepay = WePay(production, access_token) redirect_url = app.config['HOST_URL'] + '/verify/' + verification_key response = wepay.call( '/checkout/create', { 'account_id': account_id, 'amount': '20.00', 'short_description': '1 year ACM Club Membership', 'mode': 'regular', 'type': 'SERVICE', 'redirect_uri': redirect_url }) return response
def wepay_membership_response(user): """ Make a WePay API call for membership payment and return the response. """ random_string = base64.urlsafe_b64encode(os.urandom(30)) verification_key = hashlib.sha224(random_string + user.email + user.name).hexdigest() user.wepay_verification = verification_key db.session.commit() # Application settings account_id = 319493 access_token = '6dd6802f8ebef4992308a0e4f7698c275781ac36854f9451127115d995d8cda7' production = False wepay = WePay(production, access_token) redirect_url = 'http://acm.frvl.us:5000/verify/' + verification_key response = wepay.call('/checkout/create', { 'account_id': account_id, 'amount': '20.00', 'short_description': '1 year ACM Club Membership', 'mode': 'regular', 'type': 'SERVICE', 'redirect_uri': redirect_url }) return response
def wepay_membership_response(user): """ Make a WePay API call for membership payment and return the response. """ # Generate verification_key for wepay payment. random_string = base64.urlsafe_b64encode(os.urandom(30)) verification_key = hashlib.sha224(random_string + user.email + user.name).hexdigest() user.wepay_verification = verification_key db.session.commit() # WePay Application settings account_id = app.config['WEPAY_ACCT_ID'] access_token = app.config['WEPAY_ACC_TOK'] production = app.config['WEPAY_IN_PROD'] wepay = WePay(production, access_token) redirect_url = app.config['HOST_URL'] + '/verify/' + verification_key response = wepay.call('/checkout/create', { 'account_id': account_id, 'amount': '20.00', 'short_description': '1 year ACM Club Membership', 'mode': 'regular', 'type': 'SERVICE', 'redirect_uri': redirect_url }) return response
def test_silent_and_warnings(self): # production=False, silent=None or False -> raises WePayWarning self.assertRaises(WePayWarning, self.api.user.modify, foo='bar') # production=True or False, silent=True -> suppresses param check completely api = WePay(production=False, silent=True) self.assertRaises(WePayError, api.user.modify, foo='bar') # production=True, silent=None -> prints warning and will raise WePayError api = WePay(production=True) api.call = MagicMock() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") api.user.modify(foo='bar') self.assertEqual(len(w), 1) self.assertIs(w[-1].category, WePayWarning) # production=True, silent=False -> raises WePayWarning api = WePay(production=True, silent=False) api.call = MagicMock() self.assertRaises(WePayWarning, api.user.modify, foo='bar')
def GET(self, query): wepay = WePay(IN_PRODUCTION) code = web.input(code='')['code'] try: # try to get a token with our code wepay.get_token(web.ctx.homedomain + '/callback', CLIENT_ID, CLIENT_SECRET, code) # make a new account create_response = wepay.call('/account/create', { 'name': 'kitty expenses fund', 'description': 'all the money for my kitty' }) # give the account a new picture wepay.call('/account/modify', { 'account_id': create_response['account_id'], 'image_uri': 'http://www.placekitten.com/500/500' }) # redirect to the new account web.redirect(create_response['account_uri']) except WePay.WePayError as e: return "Received a WePay Error: " + repr(e)
def create_wepay_account(access_token): # set production to True for live environments production = settings.WEPAY_PRODUCTION # Use access token to create account for a user. wepay = WePay(production, access_token) response = wepay.call('/account/create', { 'name': 'CrowdEmpowered Project Contribution', 'description': 'Crowdfunding Platform' }) return response
def GET(self, query): wepay = WePay(IN_PRODUCTION) code = web.input(code="")["code"] try: # try to get a token with our code wepay.get_token(web.ctx.homedomain + "/callback", CLIENT_ID, CLIENT_SECRET, code) # make a new account create_response = wepay.call( "/account/create", {"name": "kitty expenses fund", "description": "all the money for my kitty"} ) # give the account a new picture wepay.call( "/account/modify", {"account_id": create_response["account_id"], "image_uri": "http://www.placekitten.com/500/500"}, ) # redirect to the new account web.redirect(create_response["account_uri"]) except WePay.WePayError as e: return "Received a WePay Error: " + repr(e)
def get(self, request, *args, **kwargs): if self.request.GET.get('checkout_id'): wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call('/checkout/', { 'checkout_id': self.request.GET.get('checkout_id'), }) for obj in serializers.deserialize("xml", wepay_data['long_description'], ignorenonexistent=True): obj.object.created = datetime.datetime.now() obj.object.checkout_id = self.request.GET.get('checkout_id') obj.save() action.send(self.request.user, verb='placed a $' + str(obj.object.price) + ' bounty on ', target=obj.object.issue) post_to_slack(obj.object) return super(IssueDetailView, self).get(request, *args, **kwargs)
def get(self, request, *args, **kwargs): try: self.object = self.get_object() except Http404: messages.error(self.request, 'That issue was not found.') return redirect("/") context = self.get_context_data(object=self.object) return self.render_to_response(context) if self.request.GET.get('paymentId'): import paypalrestsdk paypalrestsdk.configure({ 'mode': settings.MODE, 'client_id': settings.CLIENT_ID, 'client_secret': settings.CLIENT_SECRET }) payment = paypalrestsdk.Payment.find(self.request.GET.get('paymentId')) custom = payment.transactions[0].custom if payment.execute({"payer_id": self.request.GET.get('PayerID')}): for obj in serializers.deserialize("json", custom, ignorenonexistent=True): obj.object.created = datetime.datetime.now() obj.object.checkout_id = self.request.GET.get('checkout_id') obj.save() action.send(self.request.user, verb='placed a $' + str(obj.object.price) + ' bounty on ', target=obj.object.issue) post_to_slack(obj.object) if not settings.DEBUG: create_comment(obj.object.issue) else: messages.error(request, payment.error) if self.request.GET.get('checkout_id'): wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call('/checkout/', { 'checkout_id': self.request.GET.get('checkout_id'), }) for obj in serializers.deserialize("xml", wepay_data['long_description'], ignorenonexistent=True): obj.object.created = datetime.datetime.now() obj.object.checkout_id = self.request.GET.get('checkout_id') obj.save() action.send(self.request.user, verb='placed a $' + str(obj.object.price) + ' bounty on ', target=obj.object.issue) post_to_slack(obj.object) if not settings.DEBUG: create_comment(obj.object.issue) return super(IssueDetailView, self).get(request, *args, **kwargs)
class WePayGateway(Gateway): display_name = "WePay" homepage_url = "https://www.wepay.com/" default_currency = "USD" supported_countries = ["US"] supported_cardtypes = [Visa, MasterCard] def __init__(self): merchant_settings = getattr(settings, "MERCHANT_SETTINGS") if not merchant_settings or not merchant_settings.get("we_pay"): raise GatewayNotConfigured("The '%s' gateway is not correctly " "configured." % self.display_name) super(WePayGateway, self).__init__() production = not self.test_mode self.we_pay = WePay(production) self.we_pay_settings = merchant_settings["we_pay"] def purchase(self, money, credit_card, options=None): options = options or {} params = {} params.update({ 'account_id': options.pop("account_id", self.we_pay_settings.get("ACCOUNT_ID", "")), 'short_description': options.pop("description", ""), 'amount': money, }) if credit_card and not isinstance(credit_card, CreditCard): params["payment_method_id"] = credit_card params["payment_method_type"] = "credit_card" token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) params.update(options) try: response = self.we_pay.call('/checkout/create', params, token=token) except WePayError, error: transaction_was_unsuccessful.send(sender=self, type="purchase", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="purchase", response=response) return {'status': 'SUCCESS', 'response': response}
def periodic(): global wake_time, checkout_uri if wake_time and wake_time < time.time(): print "Trigger capture." wake_time = None wepay = WePay(IN_PRODUCTION, ACCESS_TOKEN) response = wepay.call('/checkout/create', { 'account_id': ACCOUNT_ID, 'amount': saved_data['amount'], 'short_description': saved_data['desc'], 'type': 'GOODS', 'preapproval_id': preapproval_id }) checkout_uri = response['checkout_uri']
def create_account(self): """ Create a WePay account to deposit any money for produce. """ name = self.user.first_name + ' ' + self.user.last_name desc = name + ' account' production = settings.WEPAY['in_production'] access_token = self.wepay_access_token wepay = WePay(production, access_token) try: create_response = wepay.call('/account/create', {'name': name, 'description': desc}) self.wepay_account_id = create_response['account_id'] self.save() return True, create_response except WePayError as e: return False, e
class WePayGateway(Gateway): display_name = "WePay" homepage_url = "https://www.wepay.com/" default_currency = "USD" supported_countries = ["US"] supported_cardtypes = [Visa, MasterCard] def __init__(self): merchant_settings = getattr(settings, "MERCHANT_SETTINGS") if not merchant_settings or not merchant_settings.get("we_pay"): raise GatewayNotConfigured("The '%s' gateway is not correctly " "configured." % self.display_name) super(WePayGateway, self).__init__() production = not self.test_mode self.we_pay = WePay(production) self.we_pay_settings = merchant_settings["we_pay"] def purchase(self, money, credit_card, options = None): options = options or {} params = {} params.update({ 'account_id': self.we_pay_settings.get("ACCOUNT_ID", ""), 'short_description': options.pop("description", ""), 'amount': money, }) params.update(options) if credit_card and not isinstance(credit_card, CreditCard): params["payment_method_id"] = credit_card params["payment_method_type"] = "credit_card" token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call('/checkout/create', params, token=token) except WePayError, error: transaction_was_unsuccessful.send(sender=self, type="purchase", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="purchase", response=response) return {'status': 'SUCCESS', 'response': response}
def wepay_checkout(access_token, account_id, amount, campaign_title,redirect_uri=None): # = settings.WEPAY_DONATION_SUCCESS_REDIRECT_URI # set production to True for live environments production = settings.WEPAY_PRODUCTION wepay = WePay(production, access_token) parameters = { 'account_id': account_id, 'amount': amount, 'short_description': 'Contribution to CrowdEmpowered\'s {}'.format(campaign_title), 'type': 'donation', 'currency': 'USD', 'hosted_checkout': { "mode": "iframe" }, } # Wepay won't redirect to localhost so we check for that here # in case we are running the project on localhost if redirect_uri is not None and "localhost" not in redirect_uri: parameters['callback_uri'] = redirect_uri response = wepay.call('/checkout/create', parameters) return response
def post(self): global sleep_time saved_data.update(json.loads(self.request.body)) wepay = WePay(IN_PRODUCTION, ACCESS_TOKEN) response = wepay.call('/preapproval/create', { 'account_id': ACCOUNT_ID, 'period': 'once', 'amount': saved_data['amount'], 'mode': 'regular', 'short_description': saved_data['desc'], 'redirect_uri': 'http://54.84.158.190:8888/success' }) sleep_time = int(saved_data['time']) preapproval_id = response['preapproval_id'] d = response ret = json.dumps({ 'url' : d['preapproval_uri'] }) self.write(ret)
def get(self, request, *args, **kwargs): if self.request.GET.get('checkout_id'): wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call( '/checkout/', { 'checkout_id': self.request.GET.get('checkout_id'), }) for obj in serializers.deserialize("xml", wepay_data['long_description'], ignorenonexistent=True): obj.object.created = datetime.datetime.now() obj.object.checkout_id = self.request.GET.get('checkout_id') obj.save() action.send(self.request.user, verb='placed a $' + str(obj.object.price) + ' bounty on ', target=obj.object.issue) post_to_slack(obj.object) if not settings.DEBUG: create_comment(obj.object.issue) return super(IssueDetailView, self).get(request, *args, **kwargs)
def create_issue_and_bounty(request): languages = [] for lang in Issue.LANGUAGES: languages.append(lang[0]) user = request.user if not user.is_authenticated(): return render(request, 'post.html', { 'languages': languages, 'message': 'You need to be authenticated to post bounty' }) if request.method == 'GET': return render(request, 'post.html', { 'languages': languages, }) if request.method == 'POST': url = request.POST.get('issueUrl','') if not url: messages.error(request, 'Please provide an issue url') return render(request, 'post.html', { 'languages': languages }) issue_data = get_issue(request, url) if issue_data: service = Service.objects.get(name=issue_data['service']) instance = Issue(created = user,number = issue_data['number'], project=issue_data['project'],user = issue_data['user'],service=service) else: return render(request, 'post.html', { 'languages': languages, 'message':'Please provide a propper issue url', }) form = IssueCreateForm(request.POST, instance=instance) bounty_form = BountyCreateForm(request.POST) bounty_form_is_valid = bounty_form.is_valid() if form.is_valid() and bounty_form_is_valid: if not instance.pk: issue = form.save() else: issue = instance #issue already exists, post additional bounty #this doesn't seem to be working yet price = bounty_form.cleaned_data['price'] bounty_instance = Bounty(user = user,issue = issue,price = price) #save this data and post it with the return_uri from wepay data = serializers.serialize('xml', [ bounty_instance, ]) bounty_instance.save() wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call('/checkout/create', { 'account_id': settings.WEPAY_ACCOUNT_ID, 'amount': request.POST.get('grand_total'), 'short_description': 'CoderBounty', 'long_description': data, 'type': 'service', 'currency': 'USD' }) print wepay_data #return redirect(wepay_data['checkout_uri']) return render(request, 'post.html', { 'languages': languages, 'message':'Successfully saved issue' }) else: return render(request, 'post.html', { 'languages': languages, 'message':'Error', 'errors': form.errors, 'bounty_errors':bounty_form.errors, })
from wepay import WePay # Application settings account_id = 319493 access_token = '6dd6802f8ebef4992308a0e4f7698c275781ac36854f9451127115d995d8cda7' production = False wepay = WePay(production, access_token) response = wepay.call('/checkout/create', { 'account_id': account_id, 'amount': '20.00', 'short_description': '1 year ACM Club Membership', 'mode': 'regular', 'type': 'SERVICE' }) print response
# download the Python SDK at https://github.com/wepay/Python-SDK from wepay import WePay wepay = WePay() wepay = WePay(production=False,access_token='STAGE_df1684a1c7b91f0de51b72e5890891b92d34e47fb3cb48d4dbd8d2a89fa253cc') response = wepay.call('/checkout/create', { 'account_id': 161624111, 'amount': '24.95', 'short_description': 'A brand new soccer ball', 'type': 'GOODS' }) print response # redirect user to response['checkout_uri'] ''' Creating a checkout object In order to charge your customer, you'll have to create a checkout object. You can use the checkout API to create one so the user can enter his/her payment information. Once you make the API call using your Python script, you will see this response: { "checkout_id":12345, "checkout_uri":"https://stage.wepay.com/api/checkout/12345" } The checkout_id refers to the checkout object that you just created. The checkout_uri is a unique url that is generated. This is where you should redirect the user in order for them enter their payment information. Once they complete the checkout, your accounts will receive the funds. '''
# download the Python SDK at https://github.com/wepay/Python-SDK from wepay import WePay wepay = WePay() wepay = WePay(production=False,access_token='STAGE_df1684a1c7b91f0de51b72e5890891b92d34e47fb3cb48d4dbd8d2a89fa253cc') response = wepay.call('/checkout/create', { 'account_id': 161624111, 'amount': '24.95', 'short_description': 'A brand new soccer ball', 'type': 'GOODS', 'redirect_uri': 'http://yourwebsite.com' }) print response # redirect user to response['checkout_uri'] ''' Send the customer to a confirmation page By default, WePay provides a generic confirmation page. After the user enters their payment information, you'll can send the user to your confirmation page. This is the page where the user can print out a confirmation number or their receipt. The previous exercise code has been modified on line 10 to add the redirect_uri parameter. This value specifies where the user will go. That's it! You have completed the checkout API tutorial. We hoped the tutorial was simple and easy for you. '''
def verify_and_log_wepay_checkout(cls, checkout_id, editor, anonymous, can_contact): logging.debug("Processing WePay checkout...") # Looking up updated information about the object wepay = WePay( production=current_app.config["PAYMENT_PRODUCTION"], access_token=current_app.config["WEPAY_ACCESS_TOKEN"] ) details = wepay.call("/checkout", {"checkout_id": checkout_id}) if "error" in details: logging.warning("WePay: Error: %s", details["error_description"]) return False if "gross" not in details: logging.warning("WePay: The total dollar amount paid is missing") return False if details["gross"] < 0.50: # Tiny donation logging.info("WePay: Tiny donation ($%s).", details["gross"]) return True if details["state"] in ["settled", "captured"]: # Payment has been received # Checking that txn_id has not been previously processed if cls.get_by_transaction_id(details["checkout_id"]) is not None: logging.info("WePay: Transaction ID %s has been used before.", details["checkout_id"]) return new_donation = cls( first_name=details["payer_name"], last_name="", email=details["payer_email"], editor_name=editor, can_contact=can_contact, anonymous=anonymous, amount=details["gross"] - details["fee"], fee=details["fee"], transaction_id=checkout_id, payment_method=PAYMENT_METHOD_WEPAY, ) if "shipping_address" in details: address = details["shipping_address"] new_donation.address_street = "%s\n%s" % (address["address1"], address["address2"]) new_donation.address_city = address["city"] if "state" in address: # US address new_donation.address_state = address["state"] else: new_donation.address_state = address["region"] if "zip" in address: # US address new_donation.address_postcode = address["zip"] else: new_donation.address_postcode = address["postcode"] db.session.add(new_donation) db.session.commit() logging.info("WePay: Payment added. ID: %s.", new_donation.id) send_receipt( new_donation.email, new_donation.payment_date, new_donation.amount, "%s %s" % (new_donation.first_name, new_donation.last_name), new_donation.editor_name, ) elif details["state"] in ["authorized", "reserved"]: # Payment is pending logging.info('WePay: Payment is pending. State: "%s".', details["state"]) pass elif details["state"] in ["expired", "cancelled", "failed", "refunded", "chargeback"]: # Payment has failed logging.warning('WePay: Payment has failed. State: "%s".', details["state"]) pass else: # Unknown status logging.warning("WePay: Unknown status.") return False return True
def donate(): """Donation processor for WePay. We use official Python SDK to make API calls. Its source code is available at https://github.com/wepay/Python-SDK. Description of all WePay API endpoints and much more useful information is available at https://www.wepay.com/developer/reference/. Users can make two types of donations: - one time single payment (https://www.wepay.com/developer/reference/checkout) - recurring monthly donation (https://www.wepay.com/developer/reference/preapproval) """ form = forms.DonationForm() if not form.validate(): return redirect(url_for('donations.error')) operation_type = 'preapproval' if form.recurring.data is True else 'checkout' wepay = WePay(production=current_app.config['PAYMENT_PRODUCTION'], access_token=current_app.config['WEPAY_ACCESS_TOKEN']) params = { 'account_id': current_app.config['WEPAY_ACCOUNT_ID'], 'amount': float(form.amount.data), 'redirect_uri': url_for( 'donations.complete', _external=True, _scheme=current_app.config['PREFERRED_URL_SCHEME'], ), 'mode': 'regular', 'require_shipping': True, } # Setting callback_uri that will receive IPNs if endpoint is not local if not (request.headers['Host'].startswith('localhost') or request.headers['Host'].startswith('127.0.0.1')): # Also passing arguments that will be returned with IPNs params['callback_uri'] = url_for( '.ipn', _external=True, _scheme=current_app.config['PREFERRED_URL_SCHEME'], editor=form.editor.data, anonymous=form.anonymous.data, can_contact=form.can_contact.data, ) # Setting parameters that are specific for selected type of donation if form.recurring.data is True: params['period'] = 'monthly' params['auto_recur'] = True params['short_description'] = 'Recurring donation to MetaBrainz Foundation' else: params['type'] = 'DONATION' params['short_description'] = 'Donation to MetaBrainz Foundation' response = wepay.call('/%s/create' % operation_type, params) if 'error' in response: return redirect(url_for('donations.error')) else: return redirect(response['%s_uri' % operation_type])
from wepay import WePay # application settings account_id = 1178716227 access_token = 'STAGE_91d23ae0d1b8ed89e4d5585137748aad7c0e1ff58ea725b16455af78bd3b8ca5' production = False # credit card id to charge credit_card_id = 2207927703 # set production to True for live environments wepay = WePay(production, access_token) # charge the credit card response = wepay.call('/checkout/create', { 'account_id': account_id, 'amount': '25.50', 'short_description': 'A brand new soccer ball', 'type': 'GOODS', 'payment_method_id': credit_card_id, # the user's credit_card_id 'payment_method_type': 'credit_card' }) # display the response print response
# ACCESS_TOKEN of your app ACCESS_TOKEN = '' # ACCOUNT_ID of your app ACCOUNT_ID = '' # Internal calls, set to to True for making internal calls INTERNAL_CALLS = False # Create the wepay API instance wepay = WePay(TARGET_ENVIRONMENT, ACCESS_TOKEN, INTERNAL_CALLS) # Call /user user_reps = wepay.call('/user') print(user_reps) # Call /app params = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET} app_reps = wepay.call('/app', params) print(app_reps) # Call /credit_card/create params = {"client_id": CLIENT_ID, "user_name": "Bob Smith", "email": "*****@*****.**", "cc_number": "5496198584584769", "cvv": "123", "expiration_month": 4, "expiration_year": 2020, "address": {"address1": "test", "city": "test", "state": "CA", "country": "US", "zip": "94025"}} call_reps = wepay.call('/credit_card/create', params) print(call_reps) # Call /credit_card GET if 'credit_card_id' in call_reps: params = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "credit_card_id": call_reps["credit_card_id"]}
def create_issue_and_bounty(request): languages = [] for lang in Issue.LANGUAGES: languages.append(lang[0]) user = request.user if request.method == 'GET': if request.GET.get('url'): issue_data = get_issue(request, request.GET.get('url')) if not issue_data: messages.error(request, 'Please provide an valid issue url') return redirect('/post') form = IssueCreateForm( initial={ 'issueUrl': request.GET.get('url'), 'title': issue_data['title'], 'content': issue_data['content'] or "Added from Github" }) else: form = IssueCreateForm() return render(request, 'post.html', { 'languages': languages, 'form': form, }) if request.method == 'POST': url = request.POST.get('issueUrl','') if not url: messages.error(request, 'Please provide an issue url') return render(request, 'post.html', { 'languages': languages }) issue_data = get_issue(request, url) if issue_data: service = Service.objects.get(name=issue_data['service']) instance = Issue(number = issue_data['number'], project=issue_data['project'],user = issue_data['user'],service=service) else: return render(request, 'post.html', { 'languages': languages, 'message':'Please provide a propper issue url', }) form = IssueCreateForm(request.POST, instance=instance) bounty_form = BountyCreateForm(request.POST) bounty_form_is_valid = bounty_form.is_valid() if form.is_valid() and bounty_form_is_valid: price = bounty_form.cleaned_data['price'] if int(price) < 5: return render(request, 'post.html', { 'languages': languages, 'message':'Bounty must be greater than $5', }) try: issue = form.save() except: issue = Issue.objects.get(number = issue_data['number'], project=issue_data['project'],user = issue_data['user'],service=service) #issue exists bounty_instance = Bounty(user = user,issue = issue,price = price) data = serializers.serialize('xml', [ bounty_instance, ]) wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call('/checkout/create', { 'account_id': settings.WEPAY_ACCOUNT_ID, 'amount': request.POST.get('grand_total'), 'short_description': 'CoderBounty', 'long_description': data, 'type': 'service', 'redirect_uri': request.build_absolute_uri(issue.get_absolute_url()), 'currency': 'USD' }) if "error_code" in wepay_data: messages.error(request, wepay_data['error_description']) return render(request, 'post.html', { 'languages': languages }) return redirect(wepay_data['checkout_uri']) else: return render(request, 'post.html', { 'languages': languages, 'message':form.errors, 'errors': form.errors, 'form':form, 'bounty_errors':bounty_form.errors, })
def create_issue_and_bounty(request): languages = [] for lang in Issue.LANGUAGES: languages.append(lang[0]) user = request.user if request.method == 'GET': url = request.GET.get('url') if url: helper = get_issue_helper(request, url) issue_data = helper.get_issue(request, url) if not issue_data: messages.error(request, 'Please provide an valid issue url') return redirect('/post') form = IssueCreateForm( initial={ 'issueUrl': request.GET.get('url'), 'title': issue_data['title'], 'content': issue_data['content'] or "Added from Github" }) else: form = IssueCreateForm() return render(request, 'post.html', { 'languages': languages, 'form': form, }) if request.method == 'POST': url = request.POST.get('issueUrl', '') if not url: messages.error(request, 'Please provide an issue url') return render(request, 'post.html', {'languages': languages}) try: helper = get_issue_helper(request, url) issue_data = helper.get_issue(request, url) if issue_data and "service" in issue_data: service = Service.objects.get(name=issue_data['service']) instance = Issue(number=issue_data['number'], project=issue_data['project'], user=issue_data['user'], service=service) except: return render( request, 'post.html', { 'languages': languages, 'message': 'Please provide a propper issue url like \ - https://github.com/CoderBounty/coderbounty/issues/83', }) form = IssueCreateForm(request.POST, instance=instance) bounty_form = BountyCreateForm(request.POST) bounty_form_is_valid = bounty_form.is_valid() if form.is_valid() and bounty_form_is_valid: price = bounty_form.cleaned_data['price'] if int(price) < 5: return render( request, 'post.html', { 'languages': languages, 'message': 'Bounty must be greater than $5', }) try: issue = form.save() except: issue = Issue.objects.get(number=issue_data['number'], project=issue_data['project'], user=issue_data['user'], service=service) bounty_instance = Bounty(user=user, issue=issue, price=price) if int(request.user.userprofile.balance or 0) >= int( request.POST.get('grand_total')): profile = request.user.userprofile profile.balance = int(request.user.userprofile.balance) - int( request.POST.get('grand_total')) profile.save() bounty_instance.save() if not settings.DEBUG: create_comment(issue) return redirect(issue.get_absolute_url()) else: data = serializers.serialize('xml', [ bounty_instance, ]) wepay = WePay(settings.WEPAY_IN_PRODUCTION, settings.WEPAY_ACCESS_TOKEN) wepay_data = wepay.call( '/checkout/create', { 'account_id': settings.WEPAY_ACCOUNT_ID, 'amount': request.POST.get('grand_total'), 'short_description': 'CoderBounty', 'long_description': data, 'type': 'service', 'redirect_uri': request.build_absolute_uri(issue.get_absolute_url()), 'currency': 'USD' }) if "error_code" in wepay_data: messages.error(request, wepay_data['error_description']) return render(request, 'post.html', {'languages': languages}) return redirect(wepay_data['checkout_uri']) else: return render( request, 'post.html', { 'languages': languages, 'message': form.errors, 'errors': form.errors, 'form': form, 'bounty_errors': bounty_form.errors, })
class ApiTestCase(unittest.TestCase): def setUp(self): self.api = WePay(production=False) def test_uris_production(self): api = WePay() self.assertEqual(api.api_endpoint, "https://wepayapi.com/v2") self.assertEqual(api.browser_uri, "https://www.wepay.com") self.assertEqual(api.browser_js, "https://www.wepay.com/min/js/wepay.v2.js") self.assertEqual(api.browser_iframe_js, "https://www.wepay.com/min/js/iframe.wepay.js") self.assertEqual(api.browser_endpoint, "https://www.wepay.com/v2") def test_uris(self): self.assertEqual(self.api.api_endpoint, "https://stage.wepayapi.com/v2") self.assertEqual(self.api.browser_uri, "https://stage.wepay.com") self.assertEqual(self.api.browser_js, "https://stage.wepay.com/js/wepay.v2.js") self.assertEqual(self.api.browser_iframe_js, "https://stage.wepay.com/js/iframe.wepay.js") self.assertEqual(self.api.browser_endpoint, "https://stage.wepay.com/v2") def test_call(self): self.assertRaises(WePayError, self.api.call, '/app') def test_error(self): try: self.api.call('/foo') except WePayServerError as e: self.assertIsInstance(e.http_error, requests.exceptions.HTTPError) self.assertEqual(e.status_code, 501) self.assertEqual(e.error, "invalid_request") self.assertEqual(e.error_code, 1001) self.assertEqual(e.error_description, "that is not a recognized WePay API call") self.assertEqual(str(e), "HTTP 501 - invalid_request (1001): " "that is not a recognized WePay API call") def test_silent_and_warnings(self): # production=False, silent=None or False -> raises WePayWarning self.assertRaises(WePayWarning, self.api.user.modify, foo='bar') # production=True or False, silent=True -> suppresses param check completely api = WePay(production=False, silent=True) self.assertRaises(WePayError, api.user.modify, foo='bar') # production=True, silent=None -> prints warning and will raise WePayError api = WePay(production=True) api.call = MagicMock() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") api.user.modify(foo='bar') self.assertEqual(len(w), 1) self.assertIs(w[-1].category, WePayWarning) # production=True, silent=False -> raises WePayWarning api = WePay(production=True, silent=False) api.call = MagicMock() self.assertRaises(WePayWarning, api.user.modify, foo='bar') def test_urllib(self): api = WePay(production=False, use_requests=False) self.assertRaises(WePayError, api.call, '/app') try: api.call('/app') except WePayClientError as e: self.assertIsInstance(e.http_error, urllib.error.HTTPError) self.assertEqual(e.status_code, 400) self.assertEqual(e.error, "invalid_request") self.assertEqual(e.error_code, 1004) self.assertEqual(e.error_description, "client_id parameter is required") self.assertEqual(repr(e), "<WePayClientError> " + str(e)) def test_requests_missing(self): from wepay import utils has_requests = utils.HAS_REQUESTS utils.HAS_REQUESTS = False # test the warning, if requests are misiing self.assertRaises(WePayWarning, WePay, production=False, use_requests=True, silent=False) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") WePay(production=False, use_requests=True) self.assertEqual(len(w), 1) self.assertIs(w[-1].category, WePayWarning) utils.HAS_REQUESTS = has_requests def test_urllib_connection_error(self): api = WePay(production=False, use_requests=False, timeout=0.001) self.assertRaises(WePayConnectionError, api.call, '/app') try: api.call('/app') except WePayConnectionError as e: self.assertIsInstance(e.error, urllib.error.URLError) self.assertEqual(str(e), "URLError - <urlopen error timed out>") self.assertEqual(repr(e), "<WePayConnectionError> " + str(e)) def test_requests_connection_error(self): try: self.api.call('/app', timeout=0.001) except WePayConnectionError as e: self.assertIsInstance(e.error, requests.exceptions.Timeout) def test_headers(self): api = WePay(production=False) api._post = MagicMock() api._post.configure_mock(**{'__call__': {'result': 'fake_success'}}) access_token, api_version = 'dummy_access_token', '2011-01-15' expected_headers = { 'Content-Type': 'application/json', 'User-Agent': 'Python WePay SDK (third party)', 'Authorization': 'Bearer %s' % access_token, 'Api-Version': api_version } api.call('/user', access_token=access_token, api_version=api_version) api._post.assert_called_once_with( 'https://stage.wepayapi.com/v2/user', {}, expected_headers, 30) def test_base_call(self): call = Call(self.api) self.assertRaises(NotImplementedError, lambda: call.call_name) def test_cached_property(self): class T(object): @cached_property def foo(self): return self.getter() t = T() t.getter = MagicMock(return_value='foo') self.assertEqual(t.foo, 'foo') self.assertEqual(t.foo, 'foo') t.foo = 'bar' self.assertEqual(t.foo, 'bar') self.assertEqual(t.foo, 'bar') t.getter.assert_called_once_with()
if p >= .99: #hallando porcentaje deseado 99% print(i) #imprimiendo porcentaje return(i) i += 1 find() #llamando funcion que encuentra porcentaje #utilizando api de wepay # download the Python SDK at https://github.com/wepay/Python-SDK o pipi install wepay from wepay import WePay wepay = WePay() wepay = WePay(production=False,access_token='STAGE_df1684a1c7b91f0de51b72e5890891b92d34e47fb3cb48d4dbd8d2a89fa253cc') response = wepay.call('/preapproval/create', { 'account_id': 161624111, 'period': 'monthly', 'end_time': '2013-12-25', 'amount': '19.99', 'short_description': 'A subscription to our magazine.', 'redirect_uri': 'http://example.com/success/', 'auto_recur': True }) print response # redirect user to response['checkout_uri'] ## imap testing import imaplib email = imaplib.IMAP4_SSL('service.service.com') email.login('*****@*****.**','passwd') email.logout()
from wepay import WePay # Application settings account_id = 319493 access_token = '6dd6802f8ebef4992308a0e4f7698c275781ac36854f9451127115d995d8cda7' production = False wepay = WePay(production, access_token) response = wepay.call( '/checkout/create', { 'account_id': account_id, 'amount': '20.00', 'short_description': '1 year ACM Club Membership', 'mode': 'regular', 'type': 'SERVICE' }) print response
def verify_and_log_wepay_checkout(cls, checkout_id, editor, anonymous, can_contact): logging.debug('Processing WePay checkout...') # Looking up updated information about the object wepay = WePay(production=current_app.config['PAYMENT_PRODUCTION'], access_token=current_app.config['WEPAY_ACCESS_TOKEN']) details = wepay.call('/checkout', {'checkout_id': checkout_id}) if 'error' in details: logging.warning('WePay: Error: %s', details['error_description']) return False if 'gross' not in details: logging.warning('WePay: The total dollar amount paid is missing') return False if details['gross'] < 0.50: # Tiny donation logging.info('WePay: Tiny donation ($%s).', details['gross']) return True if details['state'] in ['settled', 'captured']: # Payment has been received # Checking that txn_id has not been previously processed if cls.get_by_transaction_id(details['checkout_id']) is not None: logging.info('WePay: Transaction ID %s has been used before.', details['checkout_id']) return new_donation = cls( first_name=details['payer_name'], last_name='', email=details['payer_email'], editor_name=editor, can_contact=can_contact, anonymous=anonymous, amount=details['gross'] - details['fee'], fee=details['fee'], transaction_id=checkout_id, payment_method=PAYMENT_METHOD_WEPAY, ) if 'shipping_address' in details: address = details['shipping_address'] new_donation.address_street = "%s\n%s" % (address['address1'], address['address2']) new_donation.address_city = address['city'] if 'state' in address: # US address new_donation.address_state = address['state'] else: new_donation.address_state = address['region'] if 'zip' in address: # US address new_donation.address_postcode = address['zip'] else: new_donation.address_postcode = address['postcode'] db.session.add(new_donation) db.session.commit() logging.info('WePay: Payment added. ID: %s.', new_donation.id) send_receipt( new_donation.email, new_donation.payment_date, new_donation.amount, '%s %s' % (new_donation.first_name, new_donation.last_name), new_donation.editor_name, ) elif details['state'] in ['authorized', 'reserved']: # Payment is pending logging.info('WePay: Payment is pending. State: "%s".', details['state']) pass elif details['state'] in ['expired', 'cancelled', 'failed', 'refunded', 'chargeback']: # Payment has failed logging.warning('WePay: Payment has failed. State: "%s".', details['state']) pass else: # Unknown status logging.warning('WePay: Unknown status.') return False return True
class WePayGateway(Gateway): display_name = "WePay" homepage_url = "https://www.wepay.com/" default_currency = "USD" supported_countries = ["US"] supported_cardtypes = [Visa, MasterCard] def __init__(self): merchant_settings = getattr(settings, "MERCHANT_SETTINGS") if not merchant_settings or not merchant_settings.get("we_pay"): raise GatewayNotConfigured("The '%s' gateway is not correctly " "configured." % self.display_name) super(WePayGateway, self).__init__() production = not self.test_mode self.we_pay = WePay(production) self.we_pay_settings = merchant_settings["we_pay"] def purchase(self, money, credit_card, options=None): options = options or {} params = {} params.update({ 'account_id': options.pop("account_id", self.we_pay_settings.get("ACCOUNT_ID", "")), 'short_description': options.pop("description", ""), 'amount': money, }) if credit_card and not isinstance(credit_card, CreditCard): params["payment_method_id"] = credit_card params["payment_method_type"] = "credit_card" token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) params.update(options) try: response = self.we_pay.call('/checkout/create', params, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="purchase", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="purchase", response=response) return {'status': 'SUCCESS', 'response': response} def authorize(self, money, credit_card, options=None): options = options or {} resp = self.store(credit_card, options) if resp["status"] == "FAILURE": transaction_was_unsuccessful.send(sender=self, type="authorize", response=resp['response']) return resp token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: resp = self.we_pay.call('/credit_card/authorize', { 'client_id': self.we_pay_settings["CLIENT_ID"], 'client_secret': self.we_pay_settings["CLIENT_SECRET"], 'credit_card_id': resp['response']['credit_card_id'] }, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="authorize", response=error) return {'status': 'FAILURE', 'response': error} params = { "auto_capture": False } params.update(options) response = self.purchase(money, resp["credit_card_id"], params) if response["status"] == "FAILURE": transaction_was_unsuccessful.send(sender=self, type="authorize", response=response["response"]) return response transaction_was_successful.send(sender=self, type="authorize", response=response["response"]) return response def capture(self, money, authorization, options=None): options = options or {} params = { 'checkout_id': authorization, } token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call('/checkout/capture', params, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="capture", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="capture", response=response) return {'status': 'SUCCESS', 'response': response} def void(self, identification, options=None): options = options or {} params = { 'checkout_id': identification, 'cancel_reason': options.pop("description", "") } token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call('/checkout/cancel', params, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="void", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="void", response=response) return {'status': 'SUCCESS', 'response': response} def credit(self, money, identification, options=None): options = options or {} params = { 'checkout_id': identification, 'refund_reason': options.pop("description", ""), } if money: params.update({'amount': money}) token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call('/checkout/refund', params, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="credit", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="credit", response=response) return {'status': 'SUCCESS', 'response': response} def recurring(self, money, credit_card, options=None): options = options or {} params = { 'account_id': self.we_pay_settings.get("ACCOUNT_ID", ""), "short_description": options.pop("description", ""), "amount": money, } params.update(options) token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call("/preapproval/create", params, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="recurring", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="recurring", response=response) return {'status': 'SUCCESS', 'response': response} def store(self, credit_card, options=None): options = options or {} if not self.validate_card(credit_card): raise InvalidCard("Invalid Card") token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"]) try: response = self.we_pay.call('/credit_card/create', { 'client_id': self.we_pay_settings["CLIENT_ID"], 'user_name': credit_card.name, 'email': options.pop("customer")["email"], 'cc_number': credit_card.number, 'cvv': credit_card.verification_value, 'expiration_month': credit_card.month, 'expiration_year': credit_card.year, 'address': options.pop("billing_address") }, token=token) except WePayError as error: transaction_was_unsuccessful.send(sender=self, type="store", response=error) return {'status': 'FAILURE', 'response': error} transaction_was_successful.send(sender=self, type="store", response=response) return {'status': 'SUCCESS', 'response': response}
def pay(): """Payment processor for WePay. We use official Python SDK to make API calls. Its source code is available at https://github.com/wepay/Python-SDK. Description of all WePay API endpoints and much more useful information is available at https://www.wepay.com/developer/reference/. Users can make two types of donations: - one time single payment (https://www.wepay.com/developer/reference/checkout) - recurring monthly donation (https://www.wepay.com/developer/reference/preapproval) """ is_donation = request.args.get('is_donation') == "True" if is_donation: form = forms.DonationForm() else: form = forms.PaymentForm() if not form.validate(): return redirect(url_for('payments.error', is_donation=is_donation)) operation_type = 'preapproval' if form.recurring.data is True else 'checkout' wepay = WePay(production=current_app.config['PAYMENT_PRODUCTION'], access_token=current_app.config['WEPAY_ACCESS_TOKEN']) params = { 'account_id': current_app.config['WEPAY_ACCOUNT_ID'], 'amount': float(form.amount.data), 'redirect_uri': url_for( 'payments.complete', is_donation=is_donation, _external=True, _scheme=current_app.config['PREFERRED_URL_SCHEME'], ), 'mode': 'regular', 'require_shipping': True, } # Setting callback_uri that will receive IPNs if endpoint is not local if not (request.headers['Host'].startswith('localhost') or request.headers['Host'].startswith('127.0.0.1')): # Also passing arguments that will be returned with IPNs if is_donation: params['callback_uri'] = url_for( '.ipn', _external=True, _scheme=current_app.config['PREFERRED_URL_SCHEME'], is_donation=is_donation, editor=form.editor.data, anonymous=form.anonymous.data, can_contact=form.can_contact.data, ) else: params['callback_uri'] = url_for( '.ipn', _external=True, _scheme=current_app.config['PREFERRED_URL_SCHEME'], is_donation=is_donation, invoice_number=form.invoice_number.data, ) # Setting parameters that are specific for selected type of payment if is_donation: if form.recurring.data is True: params['period'] = 'monthly' params['auto_recur'] = True params['short_description'] = 'Recurring donation to the MetaBrainz Foundation' else: params['type'] = 'DONATION' params['short_description'] = 'Donation to the MetaBrainz Foundation' else: if form.recurring.data is True: params['period'] = 'monthly' params['auto_recur'] = True params['short_description'] = 'Recurring payment to the MetaBrainz Foundation' else: params['type'] = 'SERVICE' params['short_description'] = 'Payment to the MetaBrainz Foundation' response = wepay.call('/%s/create' % operation_type, params) if 'error' in response: return redirect(url_for('payments.error', is_donation=is_donation)) else: return redirect(response['%s_uri' % operation_type])
def verify_and_log_wepay_checkout(cls, checkout_id, editor, anonymous, can_contact): logging.debug('Processing WePay checkout...') # Looking up updated information about the object wepay = WePay(production=current_app.config['PAYMENT_PRODUCTION'], access_token=current_app.config['WEPAY_ACCESS_TOKEN']) details = wepay.call('/checkout', {'checkout_id': checkout_id}) if 'error' in details: logging.warning('WePay: Error: %s', details['error_description']) return False if 'gross' not in details: logging.warning('WePay: The total dollar amount paid is missing') return False if details['gross'] < 0.50: # Tiny donation logging.info('WePay: Tiny donation ($%s).', details['gross']) return True if details['state'] in ['settled', 'captured']: # Payment has been received # Checking that txn_id has not been previously processed if cls.get_by_transaction_id(details['checkout_id']) is not None: logging.info('WePay: Transaction ID %s has been used before.', details['checkout_id']) return new_donation = cls( first_name=details['payer_name'], last_name='', email=details['payer_email'], editor_name=editor, can_contact=can_contact, anonymous=anonymous, amount=details['gross'] - details['fee'], fee=details['fee'], transaction_id=checkout_id, payment_method=PAYMENT_METHOD_WEPAY, ) if 'shipping_address' in details: address = details['shipping_address'] new_donation.address_street = "%s\n%s" % (address['address1'], address['address2']) new_donation.address_city = address['city'] if 'state' in address: # US address new_donation.address_state = address['state'] else: new_donation.address_state = address['region'] if 'zip' in address: # US address new_donation.address_postcode = address['zip'] else: new_donation.address_postcode = address['postcode'] db.session.add(new_donation) db.session.commit() logging.info('WePay: Payment added. ID: %s.', new_donation.id) send_receipt( new_donation.email, new_donation.payment_date, new_donation.amount, '%s %s' % (new_donation.first_name, new_donation.last_name), new_donation.editor_name, ) elif details['state'] in ['authorized', 'reserved']: # Payment is pending logging.info('WePay: Payment is pending. State: "%s".', details['state']) pass elif details['state'] in [ 'expired', 'cancelled', 'failed', 'refunded', 'chargeback' ]: # Payment has failed logging.warning('WePay: Payment has failed. State: "%s".', details['state']) pass else: # Unknown status logging.warning('WePay: Unknown status.') return False return True
def pay(): """Payment processor for WePay. We use official Python SDK to make API calls. Its source code is available at https://github.com/wepay/Python-SDK. Description of all WePay API endpoints and much more useful information is available at https://www.wepay.com/developer/reference/. Users can make two types of donations: - one time single payment (https://www.wepay.com/developer/reference/checkout) - recurring monthly donation (https://www.wepay.com/developer/reference/preapproval) """ is_donation = request.args.get("is_donation") == "True" if is_donation: form = forms.DonationForm() else: form = forms.PaymentForm() if not form.validate(): return redirect(url_for("payments.error", is_donation=is_donation)) operation_type = "preapproval" if form.recurring.data is True else "checkout" wepay = WePay( production=current_app.config["PAYMENT_PRODUCTION"], access_token=current_app.config["WEPAY_ACCESS_TOKEN"] ) params = { "account_id": current_app.config["WEPAY_ACCOUNT_ID"], "amount": float(form.amount.data), "redirect_uri": url_for( "payments.complete", is_donation=is_donation, _external=True, _scheme=current_app.config["PREFERRED_URL_SCHEME"], ), "mode": "regular", "require_shipping": True, } # Setting callback_uri that will receive IPNs if endpoint is not local if not (request.headers["Host"].startswith("localhost") or request.headers["Host"].startswith("127.0.0.1")): # Also passing arguments that will be returned with IPNs if is_donation: params["callback_uri"] = url_for( ".ipn", _external=True, _scheme=current_app.config["PREFERRED_URL_SCHEME"], is_donation=is_donation, editor=form.editor.data, anonymous=form.anonymous.data, can_contact=form.can_contact.data, ) else: params["callback_uri"] = url_for( ".ipn", _external=True, _scheme=current_app.config["PREFERRED_URL_SCHEME"], is_donation=is_donation, invoice_number=form.invoice_number.data, ) # Setting parameters that are specific for selected type of payment if is_donation: if form.recurring.data is True: params["period"] = "monthly" params["auto_recur"] = True params["short_description"] = "Recurring donation to the MetaBrainz Foundation" else: params["type"] = "DONATION" params["short_description"] = "Donation to the MetaBrainz Foundation" else: if form.recurring.data is True: params["period"] = "monthly" params["auto_recur"] = True params["short_description"] = "Recurring payment to the MetaBrainz Foundation" else: params["type"] = "SERVICE" params["short_description"] = "Payment to the MetaBrainz Foundation" response = wepay.call("/%s/create" % operation_type, params) if "error" in response: return redirect(url_for("payments.error", is_donation=is_donation)) else: return redirect(response["%s_uri" % operation_type])
class WePayPaymentPlatform(PaymentPlatform): class Meta(PaymentPlatformMeta): key = Service.SERVICE_WEPAY title = "WePay" thumbnail = "/img/media/wepay.png" description = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus placerat venenatis libero vel pellentesque.""" authorization_type = AUTHORIZATION_OAUTH donation_type = DONATION_REDIRECT country = "United States" country_class = "label-info" DEFAULT_AUTH_SCOPE = "manage_accounts,collect_payments,view_user" def __init__(self): PaymentPlatform.__init__(self) self.wepay = WePay( production=settings.FRUCTUS_KEYS.WEPAY_PRODUCTION, store_token=False ) def get_oauth_url(self, redirect_uri, **kwargs): _scope = self.DEFAULT_AUTH_SCOPE if 'scope' in kwargs: _scope = kwargs['scope'] return self.wepay.get_authorization_url( redirect_uri, settings.FRUCTUS_KEYS.WEPAY_CLIENT_ID, scope=_scope ) def service_create(self, owner, **kwargs): if 'code' not in kwargs: raise TypeError() if 'redirect_uri' not in kwargs: raise TypeError() # Get the OAuth token token_result = self.wepay.get_token( kwargs['redirect_uri'], settings.FRUCTUS_KEYS.WEPAY_CLIENT_ID, settings.FRUCTUS_KEYS.WEPAY_CLIENT_SECRET, kwargs['code'] ) if 'error' in token_result: return False, None # Get User Info user_result = self.wepay.call( '/user', token=token_result['access_token'] ) if 'error' in user_result: return False, None if user_result['state'] != 'registered': return False, None # Store details in database return self.db_service_create( owner, Service.SERVICE_WEPAY, token_result['user_id'], link_type=Service.LINK_TYPE_OAUTH, data={ 'access_token': token_result['access_token'], 'token_type': token_result['token_type'], 'email': user_result['email'], 'name': user_result['user_name'], 'first_name': user_result['first_name'], 'last_name': user_result['last_name'] } ) def account_find(self, payee, **kwargs): if not payee or not payee.userservice or not payee.userservice.valid(): return None params = {} if 'name' in kwargs: params['name'] = kwargs['name'] if 'reference_id' in kwargs: params['reference_id'] = kwargs['reference_id'] return self.wepay.call( '/account/find', params, token=payee.userservice.data['access_token'] ) def donation_create(self, entity, recipient, payee, amount, tip=0.0, **kwargs): amount = float(amount) tip = float(tip) if payee is None or payee.userservice is None: return None, None donation = self.db_donation_create(entity, recipient, payee, amount, tip=tip) # Create donation descriptions short_description = self.short_description(recipient, tip) long_description = self.long_description(recipient, amount, tip) params = { 'account_id': payee.account_id, 'short_description': short_description, 'long_description': string_length_limit(long_description, max_length=2047), 'type': 'DONATION', 'amount': amount + tip, 'app_fee': tip, 'fee_payer': 'Payee' } # TODO: this could do with a cleanup if 'base_url' in kwargs: if 'redirect_name' in kwargs: params['redirect_uri'] = kwargs['base_url'] + reverse( kwargs['redirect_name'], args=[donation.token] ) if 'callback_name' in kwargs: params['callback_uri'] = kwargs['base_url'] + reverse( kwargs['callback_name'] ) create_result = self.wepay.call( '/checkout/create', params, token=payee.userservice.data['access_token'] ) if 'checkout_id' in create_result: donation.checkout_id = create_result['checkout_id'] donation.save() if 'checkout_uri' in create_result: return donation, create_result['checkout_uri'] else: return donation, None def donation_confirm(self, donation, **kwargs): pass def donation_update(self, donation): result = self.wepay.call( '/checkout', { 'checkout_id': donation.checkout_id }, token=donation.payee.userservice.data['access_token'] ) if 'error' in result: return False donation.state = result['state'] donation.save() return True
# download the Python SDK at https://github.com/wepay/Python-SDK from wepay import WePay wepay = WePay() wepay = WePay(production=False,access_token='STAGE_df1684a1c7b91f0de51b72e5890891b92d34e47fb3cb48d4dbd8d2a89fa253cc') response = wepay.call('/preapproval/create', { 'account_id': 161624111, 'period': 'monthly', 'end_time': '2013-12-25', 'amount': '19.99', 'short_description': 'A subscription to our magazine.', 'redirect_uri': 'http://example.com/success/', 'auto_recur': True }) print response # redirect user to response['checkout_uri'] ''' Send the customer to a confirmation page By default, WePay provides a generic confirmation page. After the user enters their payment information, you'll can send the user to your confirmation page. This is the page where the user can print out a confirmation number or their receipt. On line 11, redirect_uri parameter determines where the user will go. That's it! You have completed the preapproval API tutorial. We hoped the tutorial was simple and easy for you. '''