def _mass_pay(request, payment_paypal_dict):
    PAYPAL_CONFIG = PayPalConfig(
        API_USERNAME=settings.PAYPAL_API_USERNAME,
        API_PASSWORD=settings.PAYPAL_API_PASSWORD,
        API_SIGNATURE=settings.PAYPAL_API_SIGNATURE,
        API_ENVIRONMENT=settings.PAYPAL_API_ENVIRONMENT,
        DEBUG_LEVEL=0,
    )
    paypal_interface = PayPalInterface(config=PAYPAL_CONFIG)
    payment_dict = {"RECEIVERTYPE": "EmailAddress"}

    for i, item in enumerate(payment_paypal_dict.items()):
        payment_account = (item[0])[0 : item[0].find("_")]
        participant = item[1]
        payment_credit = participant.award_credit - participant.donate_credit
        if payment_credit > 0:
            if payment_account:
                payment_dict["L_EMAIL%s" % i] = payment_account
                payment_dict["L_AMT%s" % i] = payment_credit
                payment_dict["L_NOTE%s" % i] = participant.research.name
                participant.superuser_award_dt = now()
                participant.payment_type = "paypal"
                participant.payment_account = payment_account

    try:
        resp = paypal_interface._call("MassPay", **payment_dict)
        if resp["ACK"] == "Success":
            for payment_account, participant in payment_paypal_dict.items():
                participant.payment_status = True
                participant.payment_resp = "MassPay Success"
                participant.save()
            success(request, _(u"Payment of payment successful"))
    except PayPalAPIResponseError as e:
        error(request, _(u"%s") % e.message)
예제 #2
0
def confirm(order_obj, token, paypal_cfg):
    interface = PayPalInterface(PayPalConfig(**paypal_cfg.CONFIG))
    details = interface.get_express_checkout_details(**{
        "token": token,
    })
    dic = {
        "token": token,
        "desc": paypal_cfg.ORDER_DESCRIPTION,
        "amt": "%.2f" % (order_obj.nett_price),
        "currencycode": paypal_cfg.CURRENCY_CODE,
        "paymentaction": "sale",
        "payerid": details["PAYERID"],
    }
    confirmation = interface.do_express_checkout_payment(**dic)
    return details, confirmation["ACK"] == u'Success', confirmation
예제 #3
0
def get_interface_obj():
    """
    Use this function to get a PayPalInterface object with your test API
    credentials (as specified in api_details.py). Create new interfaces for
    each unit test module to avoid potential variable pollution. 
    """
    return PayPalInterface(config=api_details.CONFIG)
예제 #4
0
def get_checkout_url(order_obj, paypal_cfg, shipping=0, notes=0):
    interface = PayPalInterface(PayPalConfig(**paypal_cfg.CONFIG))
    resp = interface.set_express_checkout(**{
        "returnurl": paypal_cfg.RETURN_URL,
        "cancelurl": paypal_cfg.CANCEL_URL,
        "paymentaction": "sale",
        "amt": "%.2f" % (order_obj.nett_price),
        "currencycode": paypal_cfg.CURRENCY_CODE,
        "desc": paypal_cfg.ORDER_DESCRIPTION,
        "useraction": "commit",
        "noshipping": shipping,
        "allownote": 0
    })
    token = resp.token
    redir_url = interface.generate_express_checkout_redirect_url(token)
    return redir_url
예제 #5
0
    def handle(self, *args, **options):
        now = datetime.now() - timedelta(days=30)

        try:
            latest = Transaction.objects.latest('timestamp').timestamp
        except Transaction.DoesNotExist:
            latest = datetime.now() - timedelta(days=365 * 5)

        pprint(latest)
        paypal = PayPalInterface(CONFIG)
        result = paypal.transaction_search(startdate=latest)
        print "grabbed %d items" % len(result.items())
        for item in result.items():
            error = False
            transaction = Transaction(id=item['TRANSACTIONID'])
            transaction.timestamp = datetime.strptime(
                item[u'TIMESTAMP'],
                '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.UTC)
            transaction.type = item[u'TYPE']
            try:
                transaction.email = item[u'EMAIL']
            except KeyError:
                error = True
            transaction.name = item[u'NAME']
            transaction.status = item[u'STATUS']
            try:
                transaction.amount = Money(item[u'AMT'], item[u'CURRENCYCODE'])
            except KeyError:
                error = True
            try:
                transaction.fee_amount = Money(item[u'FEEAMT'],
                                               item[u'CURRENCYCODE'])
            except KeyError:
                error = True
            try:
                transaction.net_amount = Money(item[u'NETAMT'],
                                               item[u'CURRENCYCODE'])
            except KeyError:
                error = True

            if error:
                pprint(item)
            transaction.save()
예제 #6
0
def get_paypal_interface():
    '''
	Returns a paypal interface handle
	'''
    CONFIG = PayPalConfig(API_USERNAME=PAYPAL_API_USERNAME,
                          API_PASSWORD=PAYPAL_API_PASSWORD,
                          API_SIGNATURE=PAYPAL_API_SIGNATURE,
                          API_ENVIRONMENT="production",
                          DEBUG_LEVEL=0)

    return PayPalInterface(config=CONFIG)
예제 #7
0
 def _init_API(self ,app):
     """ initialises any stuff needed for the payment gateway API and should
     fail if anything is invalid or missing
     """
     config = PayPalConfig(
         API_ENVIRONMENT=app.config.get('PAYMENT_API_ENVIRONMENT', 'sandbox'),
         API_USERNAME=app.config.get('PAYPAL_API_USER'),
         API_PASSWORD=app.config.get('PAYPAL_API_PWD'),
         API_SIGNATURE=app.config.get('PAYPAL_API_SIGNATURE')
     )
     self.interface = PayPalInterface(config)
예제 #8
0
파일: pp.py 프로젝트: anthonysontag/ps1auth
    def handle(self, *args, **options):
        now = datetime.now() - timedelta(days=30)

        try:
            latest = Transaction.objects.latest('timestamp').timestamp
        except Transaction.DoesNotExist:
            latest = datetime.now() - timedelta(days=365*5)

        pprint(latest)
        paypal = PayPalInterface(CONFIG)
        result = paypal.transaction_search(startdate=latest)
        print "grabbed %d items" % len(result.items())
        for item in result.items():
            error = False
            transaction = Transaction(id=item['TRANSACTIONID'])
            transaction.timestamp = datetime.strptime(item[u'TIMESTAMP'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.UTC)
            transaction.type = item[u'TYPE']
            try:
                transaction.email = item[u'EMAIL']
            except KeyError:
                error = True
            transaction.name = item[u'NAME']
            transaction.status = item[u'STATUS']
            try:
                transaction.amount = Money(item[u'AMT'], item[u'CURRENCYCODE'])
            except KeyError:
                error = True
            try:
                transaction.fee_amount = Money(item[u'FEEAMT'], item[u'CURRENCYCODE'])
            except KeyError:
                error = True
            try:
                transaction.net_amount = Money(item[u'NETAMT'], item[u'CURRENCYCODE'])
            except KeyError:
                error = True

            if error:
                pprint(item)
            transaction.save()
예제 #9
0
    def get_paypal_interface_obj(self):
        context = self.context
        props = getToolByName(context, 'portal_properties').paypal_properties

        #TODO: Need to be moved in configlet with description
        # Enter your test account's API details here. You'll need the 3-token
        # credentials, not the certificate stuff.
        #CONFIG = PayPalConfig(API_USERNAME = "******",
        #                      API_PASSWORD = "******",
        #                      API_SIGNATURE = "AuyTYUFGIfqpMeM0seVte",
        #                      DEBUG_LEVEL=0)

        CONFIG = PayPalConfig(API_USERNAME=props.api_username,
                              API_PASSWORD=props.api_password,
                              API_SIGNATURE=props.api_signature,
                              API_ENVIRONMENT=props.test and 'SANDBOX'
                              or 'PRODUCTION',
                              DEBUG_LEVEL=0)

        return PayPalInterface(config=CONFIG)
예제 #10
0
class PayPalGateway:
    """ Specific Impementation for PayPal WPP"""
    
    def __init__(self, app):
        # Need to catch value error and throw as config error
        try:
            self._init_API(app)
        except KeyError:
            raise PaymentsConfigurationError
            
    def _init_API(self ,app):
        """ initialises any stuff needed for the payment gateway API and should
        fail if anything is invalid or missing
        """
        config = PayPalConfig(
            API_ENVIRONMENT=app.config.get('PAYMENT_API_ENVIRONMENT', 'sandbox'),
            API_USERNAME=app.config.get('PAYPAL_API_USER'),
            API_PASSWORD=app.config.get('PAYPAL_API_PWD'),
            API_SIGNATURE=app.config.get('PAYPAL_API_SIGNATURE')
        )
        self.interface = PayPalInterface(config)

    def setupRedirect(self, trans):
        """ this is for WPP only"""
        if trans.type == 'Express':
            return self._setupExpressTransfer(trans)
        else:
            raise PaymentTransactionValidationError()

    # why is this two methods surely this could be easier?

    def _setupExpressTransfer(self, trans):
        """ add details to transaction to allow it to be forwarded to the 
        third party gateway 
        """
        def keycase(key):
            return key.replace('_','').upper()
        params = dict([(keycase(k), v,) for k, v in trans.__dict__.iteritems()])
        r = self.SetExpressCheckout(**params)
        trans.token = r.token
        trans.next = self.interface.generate_express_checkout_redirect_url(
                r.token)
        return trans

    # Public methods of gateway 'interface'
    def authorise(self, trans):
        """Examines the type of transaction passed in and delegates to either
        the express payments flow or the direct payments flow, where further
        validation can take place.

        If its not a type of transaction which this gateway can process then it
        will throw its dummy out of the pram.
        """
        if trans.type == 'Express':
            return self._authoriseExpress(trans)
        elif trans.type == 'Direct':
            pass # not implemented yet
        else: raise PaymentTransactionValidationError()

    def _authoriseExpress(self, trans, action='Sale'):
        """ calls authorise on payment setup via redirect to paypal
        """
        r = self.DoExpressCheckoutPayment(token=trans.token,
                PAYMENTACTION=action, PAYERID=trans.payerid, AMT=trans.amt,
                CURRENCYCODE='JPY')
        trans.transactionid = r.TRANSACTIONID
        trans.raw = r
        trans.authorised = True
        return trans

    # API METHODS

    # PayPal python NVP API wrapper class.
    # This is a sample to help others get started on working
    # with the PayPal NVP API in Python. 
    # This is not a complete reference! Be sure to understand
    # what this class is doing before you try it on production servers!
    # ...use at your own peril.

    ## see https://www.paypal.com/IntegrationCenter/ic_nvp.html
    ## and
    ## https://www.paypal.com/en_US/ebook/PP_NVPAPI_DeveloperGuide/index.html
    ## for more information.

    # by Mike Atlas / LowSingle.com / MassWrestling.com, September 2007
    # No License Expressed. Feel free to distribute, modify, 
    # and use in any open or closed source project without credit to the author

    def SetExpressCheckout(self, **kwargs):
        return self.interface.set_express_checkout(**kwargs)
    
    def DoExpressCheckoutPayment(self, token, **kwargs):
        return self.interface.do_express_checkout_payment(token, **kwargs)

    # Get info on transaction
    def GetTransactionDetails(self, **kwargs):
        return self.interface.get_transaction_details(**kwargs)

    # Direct payment
    def DoDirectPayment(self, **kwargs):
        return self.interface.do_direct_payment(**kwargs)
from paypal import PayPalConfig
from paypal import PayPalInterface

config = PayPalConfig(
    API_USERNAME="******",
    API_PASSWORD="******",
    API_SIGNATURE="ARJ3i6R11uqkA7Oilyp9Gg-y3foBAXzMhlvgGUVkmd2KXZQsVtuWvNAy",
    DEBUG_LEVEL=0)

interface = PayPalInterface(config=config)
예제 #12
0
import discord, json, asyncio, requests, smtplib, random, string
from paypal import PayPalInterface
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from discord.ext.commands import Bot

bot = Bot(command_prefix='!')
notifChannel = '<channel ID>'
serverID = '<server ID>'
paypal_api = PayPalInterface(API_USERNAME="******",
                             API_PASSWORD="******",
                             API_SIGNATURE="<paypal api signature>",
                             DEBUG_LEVEL=0,
                             HTTP_TIMEOUT=30)


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)


async def send_mail(code, email):
    msg = MIMEText('<message contents> %s' % code)
    msg['From'] = '<from email>'
    msg['To'] = email
    msg['Subject'] = '<message subject>'
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    mail.ehlo()
    mail.starttls()