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 GET(self): wepay = WePay(IN_PRODUCTION) # redirect to wepay for authorization web.redirect( wepay.get_authorization_url(web.ctx.homedomain + '/callback', CLIENT_ID))
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 __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 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_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_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_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_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 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)
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)
p = 0.0 while True: if bouncy(i): b+= 1 #contador de numeros bouncy p = (b / i) 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']
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
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, })
def setUp(self): self.api = WePay(production=False)
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 setUp(self): self.api = WePay(silent=False) self.api.call = MagicMock()