Пример #1
0
 def get(cls, options=None, api=None):
     options = options or {}
     if isinstance(options, string_types):
         options = {'access_token': options}
     options = util.merge_dict({'schema': 'openid'}, options)
     api = api or default_api()
     return cls.post(cls.path, options, api=api)
Пример #2
0
    def __init__(self, options=None, **kwargs):
        """Create API object

        Usage::

            >>> import paypalrestsdkold
            >>> api = paypalrestsdkold.Api(mode="sandbox", client_id='CLIENT_ID', client_secret='CLIENT_SECRET',
             ssl_options={"cert": "/path/to/server.pem"})
        """
        kwargs = util.merge_dict(options or {}, kwargs)

        self.mode = kwargs.get("mode", "sandbox")
        
        if self.mode != "live" and self.mode != "sandbox":
            raise exceptions.InvalidConfig("Configuration Mode Invalid", "Received: %s" % (self.mode), "Required: live or sandbox")

        self.endpoint = kwargs.get("endpoint", self.default_endpoint())
        self.token_endpoint = kwargs.get("token_endpoint", self.endpoint)
        # Mandatory parameter, so not using `dict.get`
        self.client_id = kwargs["client_id"]
        # Mandatory parameter, so not using `dict.get`
        self.client_secret = kwargs["client_secret"]
        self.proxies = kwargs.get("proxies", None)
        self.token_hash = None
        self.token_request_at = None
        # setup SSL certificate verification if private certificate provided
        ssl_options = kwargs.get("ssl_options", {})
        if "cert" in ssl_options:
            os.environ["REQUESTS_CA_BUNDLE"] = ssl_options["cert"]

        if kwargs.get("token"):
            self.token_hash = {
                "access_token": kwargs["token"], "token_type": "Bearer"}

        self.options = kwargs
Пример #3
0
    def request(self, url, method, body=None, headers=None, refresh_token=None):
        """Make HTTP call, formats response and does error handling. Uses http_call method in API class.

        Usage::

            >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment?count=10", "GET", {})
            >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment", "POST", "{}", {} )

        """

        http_headers = util.merge_dict(
            self.headers(refresh_token=refresh_token, headers=headers or {}), headers or {})

        if http_headers.get('PayPal-Request-Id'):
            log.info('PayPal-Request-Id: %s' %
                     (http_headers['PayPal-Request-Id']))

        self._check_openssl_version()

        try:
            return self.http_call(url, method, data=json.dumps(body), headers=http_headers)

        # Format Error message for bad request
        except exceptions.BadRequest as error:
            return {"error": json.loads(error.content)}

        # Handle Expired token
        except exceptions.UnauthorizedAccess as error:
            if(self.token_hash and self.client_id):
                self.token_hash = None
                return self.request(url, method, body, headers)
            else:
                raise error
Пример #4
0
def logout_url(options=None, api=None):
    api = api or default_api()
    options = util.merge_dict(
        {
            'logout': 'true',
            'redirect_uri': redirect_uri(api)
        }, options or {})
    return session_url(end_session_path, options, api=api)
Пример #5
0
def authorize_url(options=None, api=None):
    api = api or default_api()
    options = util.merge_dict(
        {
            'response_type': 'code',
            'scope': 'openid',
            'client_id': client_id(api),
            'redirect_uri': redirect_uri(api)
        }, options or {})
    return session_url(start_session_path, options, api=api)
Пример #6
0
 def post(cls, action, options=None, headers=None, api=None):
     api = api or default_api()
     url = util.join_url(endpoint(api), action)
     body = util.urlencode(options or {})
     headers = util.merge_dict(
         {
             'User-Agent': cls.user_agent,
             'Content-Type': 'application/x-www-form-urlencoded'
         }, headers or {})
     data = api.http_call(url, 'POST', data=body, headers=headers)
     return cls(data, api=api)
Пример #7
0
    def create_with_refresh_token(cls, options=None, api=None):
        options = options or {}
        api = api or default_api()
        if isinstance(options, string_types):
            options = {'refresh_token': options}
        options = util.merge_dict(
            {
                'grant_type': 'refresh_token',
                'client_id': client_id(api),
                'client_secret': client_secret(api)
            }, options)

        return cls.post(cls.path, options, api=api)
Пример #8
0
    def create(cls, options=None, api=None):
        options = options or {}
        api = api or default_api()
        if isinstance(options, string_types):
            options = {'code': options}

        options = util.merge_dict(
            {
                'grant_type': 'authorization_code',
                'client_id': client_id(api),
                'client_secret': client_secret(api)
            }, options)
        return cls.post(cls.path, options, api=api)
Пример #9
0
    def get_token_hash(self, authorization_code=None, refresh_token=None, headers=None):
        """Generate new token by making a POST request

            1. By using client credentials if validate_token_hash finds
            token to be invalid. This is useful during web flow so that an already
            authenticated user is not reprompted for login
            2. Exchange authorization_code from mobile device for a long living
            refresh token that can be used to charge user who has consented to future
            payments
            3. Exchange refresh_token for the user for a access_token of type Bearer
            which can be passed in to charge user

        """
        path = "/v1/oauth2/token"
        payload = "grant_type=client_credentials"

        if authorization_code is not None:
            payload = "grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code=" + \
                authorization_code

        elif refresh_token is not None:
            payload = "grant_type=refresh_token&refresh_token=" + refresh_token

        else:
            self.validate_token_hash()
            if self.token_hash is not None:
                # return cached copy
                return self.token_hash

        token = self.http_call(
            util.join_url(self.token_endpoint, path), "POST",
            data=payload,
            headers=util.merge_dict({
                "Authorization": ("Basic %s" % self.basic_auth()),
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json", "User-Agent": self.user_agent
            }, headers or {}))

        if refresh_token is None and authorization_code is None:
            # cache token for re-use in normal case
            self.token_request_at = datetime.datetime.now()
            self.token_hash = token
        return token
Пример #10
0
    def create(self, refresh_token=None, correlation_id=None):
        """Creates a resource e.g. payment

        Usage::

            >>> payment = Payment({})
            >>> payment.create() # return True or False
        """

        headers = {}
        if correlation_id is not None:
            headers = util.merge_dict(
                self.http_headers(), {
                    'Paypal-Application-Correlation-Id': correlation_id,
                    'Paypal-Client-Metadata-Id': correlation_id
                })
        else:
            headers = self.http_headers()

        new_attributes = self.api.post(self.path, self.to_dict(), headers,
                                       refresh_token)
        self.error = None
        self.merge(new_attributes)
        return self.success()
Пример #11
0
 def http_headers(self):
     """Generate HTTP header
     """
     return util.merge_dict(
         self.header, self.headers,
         {'PayPal-Request-Id': self.generate_request_id()})
Пример #12
0
 def userinfo(self, options=None, api=None):
     return Userinfo.get(util.merge_dict(
         {'access_token': self.access_token}, options or {}),
                         api=api)
Пример #13
0
 def refresh(self, options=None, api=None):
     options = util.merge_dict({'refresh_token': self.refresh_token},
                               options or {})
     tokeninfo = self.__class__.create_with_refresh_token(options, api=api)
     self.merge(tokeninfo.to_dict())
     return self
Пример #14
0
 def logout_url(self, options=None, api=None):
     return logout_url(util.merge_dict({'id_token': self.id_token}, options
                                       or {}),
                       api=api)