FriendlyScore: Software as a Service

Step 1 - Register company

Please register your company. After registration you will be able to access OAuth2 API credentials for integration with FriendlyScore.

Step 2 - Forward users to FriendlyScore

Currently there are two ways of forwarding users to FriendlyScore. First and recommended is by using widget button – your company FriendlyScore landing page will then open in popup. Second is by pointing user web browser directly to your FriendlyScore landing page.

Widget button (recommended)

Copy JavaScript code in place where you want to have Widget. Example:


<script type="text/javascript" id="__fs-widget">
var __lc = {};
__lc.application = 1019;
__lc.borrowerIdentifier = undefined; // your borrower identifier ex. from database
__lc.lang = undefined;
__lc.buttonText = 'Score yourself';
// __lc.bgColor = '#e61b72'; // uncomment if you'd like to change background color
// __lc.fontSize = '12px';   // uncomment if you'd like to change font size

(function() {
var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.friendlyscore.com/widgets.js?app='+__lc.application;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
parameter desription
__lc.application Your application id
__lc.borrowerIdentifier If you leave undefined friendlyScore will ask your user about e-mail. Otherwise use here USER ID from your database
__lc.lang Supported: en, pt-br, nl, pl, ro
__lc.buttonText Change text on button
__lc.bgColor Change background color
__lc.fontSize Change font size

Direct link to landing page

If you don't want to use FriendlyScore in pop-up, then send users directly to our landing page:

<a href="https://friendlyscore.com/{Lang}/landing/process/{ApplicationId}/{BorrowerIdentifier}">
   Click to Score yourself
</a>

URL Parameters in details:

parameter desription
Lang default language is english, others posibilities: pl,nl,ro,pt-br
ApplicationId This is application that is calculating credit scoring, see your customer panel for list of your applications
BorrowerIdentifier your DATABASE USER ID

Step 3 - OAuth2 API

Use our FriendlyScore OAuth2 API to automate decisions and back-test the scorecard model

OAuth2 API is for:

Playground – Login with FriendlyScore

If You'd like to test api calls with our Playground, please log in with your FriendlyScore Customer Account.

Note that all calls to API will be signed by your application

Login with FriendlyScore

FriendlyScore OAuth2 API

FriendlyScore can be accessed via OAuth2 authorized API. Its main purpose is to simplify integration of existing scoring application with FriendlyScore Machine Learning Engine.

Client id and client secret

To authenticate via OAuth2, we need to obtain CLIENT_ID and CLIENT_SECRET. To do so, first one needs to navigate to https://friendlyscore.com/login and log in to company backend. After user is logged in OAuth2 credentials can be found by going to Scorecard – from main menu, settings for selected scorecard and then tab OAuth2 API. If OAuth2 client is created Client ID and Client secret fields should be visible on top of chosen tab. If they are not present, we need to create client, by filling in one or more redirect uris and submiting form. It does not matter which url of your application redirect uris will point to, due to we are going to use client credentials grant type in OAuth2 authentication process.

Endpoints

This section describes how to authorize OAuth2 client with API, how to score user using FriendlyScore, obtain user data, set user attributes (positive, status, status_description) and how to get list of users.

EndpointMethodDescription
https://friendlyscore.com/oauth/v2/token POST Obtain access token
ParameterDescription
{client_id} Client ID for your OAuth2 application
{client_secret} Client secret for your OAuth2 application
{grant_type} Should be set to: client_credentials
https://friendlyscore.com/api/v2/users/{id-type}/{id}/calculate_score.json POST Schedules user for score calculation
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
{access_tokens} Array with keys: facebook, linkedin, twitter_user_id, google, paypal
{webhook} Webhook address to call when data is ready
{ip} IP address
{user_agent} User agent object – see examples
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show.json GET Returns user main data details
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show/social-network-data.json GET Returns user social network data
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show/ip-address-data.json GET Returns user data obtained from IP addresses
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show/data-points.json GET Returns user data points
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show/heat-map-coordinates.json GET Returns user heat map coordinates
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/performance-data.json POST Sets user performance date
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
{loan_application_customer_id} Text field: application customer id
{loan_application_date} Date field: format (YYYY-mm-dd H:i:s)
{loan_application_status} Text field: loan application status. Options: accepted, declined, drop-off.
{loan_value} Float field: loan value
{loan_paid_capital} Float field: loan paid capital
{loan_currency} Text field: loan currency
{loan_term} Integer field: loan term days
{loan_status} Text field: loan status. Options: active, arrears, paid.
{loan_arrears_days} Integer field: loan arrears days
{loan_arrears_amount_overdue} Float field: loan arrears amount overdue
{loan_is_installment} Is installment
{comments} Array with keys: positive, negative, neutral.
https://friendlyscore.com/api/v2/users/{id-type}/{id}/positive/{positive-val}.json PUT Sets _positive_ property to value _POSITIVE\_VAL_
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
{positive-val} Set user positive flag: 1 for positive, 0 for negative
https://friendlyscore.com/api/v2/users/{id-type}/{id}/status.json POST Sets user status and status description
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
{status} Text field: user status
{status_description} Text field: user status description
https://friendlyscore.com/api/v2/users/{id-type}/{id}/show/min-fraud-data.json GET Return user fraud data
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/fraudalerts/{id-type}/{id}/show.json GET Get user fraud alert list
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/places.json GET Get user places extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/days-of-birth.json GET Get user days of birth extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/skills.json GET Get user skills extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/phones.json GET Get user phone numbers extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/work-periods.json GET Get user work periods extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/universities.json GET Get user universities extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users/{id-type}/{id}/google/raw-file-data/emails.json GET Get user e-mails extracted from gmail attachments CV parser
ParameterDescription
{id-type} There are 2 options: either 'id' which means internal FriendlyScore identifier or 'partner-id' which means identifier provied by the client's company (internal id from your database)
{id} Users id or partner-id depending on what has been set in {id-type} parameter
https://friendlyscore.com/api/v2/users.json GET Lists all users
ParameterDescription
{page} Page number to be displayed. Default is 1.
{max_results} How many results API should return per page. Default is 20 and maximum is 200.

Where:

Performing request without OAuth2 access token will lead to access_denied response.

{
  "error": "access_denied",
  "error_description": "OAuth2 authentication required"
}

For non existing endpoints (e.g. when some part of URL is missing) API returns 404 response.

{
    "code":404,
    "message":"Endpoint: users/partner-id//show.json not found"
}

Obtaining Oauth2 access token

Before scoring user in FriendlyScore API, scoring application needs to be authorized by requesting an access token. This can be made requesting address:

https://friendlyscore.com/oauth/v2/token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials

Parameters YOUR_CLIENT_ID and YOUR_CLIENT_SECRET are respectively your OAuth2 client identifier and your OAuth2 client secret. Those can be passed by URL parameters (example above) or via JSON, for example using cURL. The key access_token needs to be stored somwhere for feature use.

To get your access token using cURL, type (more examples):

curl -H 'Content-Type: application/json' -X POST \
     -d '{
            "grant_type": "client_credentials",
            "client_id": "YOUR_CLIENT_ID",
            "client_secret": "YOUR_CLIENT_SECRET"
        }' \
      'https://friendlyscore.com/oauth/v2/token'

To get your access token using cURL, type (sample client and more examples):

require_once '/path/to/FriendlyScore.php';

$fs = new \FriendlyScore\OAuth2\Client\Provider\FriendlyScore([
        'clientId'     => '...',
        'clientSecret' => '...',
        'redirectUri'  => '...',
]);

$accessToken = $fs->getAccessToken('client_credentials');

To get your access token using cURL, type (sample client and more examples):

require 'oauth2-client'
require 'json'

client = OAuth2Client::Client.new(
    'https://friendlyscore.com',
    CLIENT_ID,
    CLIENT_SECRET
)

client.token_path = '/oauth/v2/token'
token = client.client_credentials.get_token
access_token = JSON.parse(token.body)

To get your access token using cURL, type (sample client and more examples):

import requests
import json

class FriendlyScore:

    CLIENT_ID         = ''
    CLIENT_SECRET     = ''
    BASE_URL          = 'https://friendlyscore.com/'
    REQUEST_TOKEN_URL = BASE_URL+'oauth/v2/token'

    def getToken(self):
        credentials = { 'client_id': self.CLIENT_ID, 'client_secret': self.CLIENT_SECRET, 'grant_type': 'client_credentials' }
        r = requests.post(self.REQUEST_TOKEN_URL, json=credentials)
        token = r.json()
        return r.status_code, token

fs = FriendlyScore()
http_code, access_token = fs.getToken()

Example response is shown below.

{
    "access_token":"MzA0MzE4MmQ0YWVkZDQzYzVlM2JkMDY1ZGZlYzgzNzVjMDdhYWNlYTM1MDQ3NTEwNmE0NDhiMWUxNGNmYjlmZQ",
    "expires_in":3600,
    "token_type":"bearer",
    "scope":null
}

Scoring user in FriendlyScore using API

Scoring user in FriendlyScore using API is divided into two steps. First we need to provide user access_tokens, which will result scheduling user for score calculation. Second step is to obtain calculated score from API – we can ask FriendlyScore API whether data is ready or be informed by webhook provided during score calculation request.

Scheduling score calculation

Having valid access_token user scoring can be performed by sending request to https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/calculate_score.json or https://friendlyscore.com/api/v2/users/id/FS-USER-ID/calculate_score.json. Caution: second endpoint can be used only for rescoring existing user – FS-USER-ID parameter is ID returned in show.json endpoint. PARTNER-ID is identifier from partner system. Access token can be send both via parameter or via authorization header. Two mandatory parameters are ip – user ip address and user_agent – user agent string from user's browser. Other mandatory parameter is access_tokens with scrutcture shown in JSON format.

The key twitter_user_id can be reaplaced with twitter_screen_name. All access tokens should be valid. Currently only facebook access token is mandatory. Last optional parameter is webhook. If we want to be informed when our data is ready, we can provide webhook to scoring application e.g. https://YOUR-SCORING-APPLICATION.com/scoring-finished?user_id=THE-ID

If everything went fine, response code from calculate_score endpoint is 202 (Accepted) and content looks like in JSON example.

Parameter access_tokens structure:

{
    "facebook":        "USER_FACEBOOK_ACCESS_TOKEN",
    "linkedin":        "USER_LINKEDIN_ACCESS_TOKEN",
    "twitter_user_id": "USER_TWITER_ID",
    "google":          "USER_GOOGLE_ACCESS_TOKEN",
    "paypal":          "USER_PAYPAL_ACCESS_TOKEN"
}

Successful response from calculate_score endpoint:

{
    "result": "success",
    "message": "Queued for calculation.",
    "user_id": "USER-ID"
}

Fetching calculated score

To fetch data from FriendlyScore API, we need to call https://friendlyscore.com/api/v2/users/partner-id/PARTNER_ID/show.json or https://friendlyscore.com/api/v2/users/id/FS_USER_ID/show.json endpoint.

Responses

Sample responses from show endpoint are shown below.

Data found

If everything went fine and our data is ready we get HTTP status code: 200 Success.

Now we can obtain additional data: - social network data, - data obtained from ip adresses, - user data points, - user heat map coordinates.

For more information check available endpoints or examples in cURL, PHP, Ruby or Python.

{
    "id": "1234",
    "partner_user_id": "myuser-1234",
    "score": "61%",
    "score_points" : "940",
    "score_points_total" : "1000",
    "created_at": "2014-10-25 09:53:24",
    "updated_at": "2014-10-25 10:23:21",
    "facebook_score": "0%",
    "google_score": "0%",
    "linkedin_score": "0%",
    "twitter_score": "0%",
    "paypal_score": "0%",
    "custom_score": "26%",
    "status": "",
    "status_description": "",
    "is_positive": 0,
    "name": "John",
    "lastname": "Smith",
    "all_names": {
        "facebook": "John Smith",
        "linkedin": "",
        "twitter": "",
        "google": "",
        "paypal": ""
    },
    "name_similarities": {
        "facebook": 1,
        "linkedin": 0,
        "twitter": 0,
        "google": 0,
        "paypal": 0,
        "overall": 1
    },
    "email": "john.smith@example.com",
    "risk_score": "1.00",
    "proxy_score": "0.00",
    "friendlyscore_friends": 41,
    "facebook_id": "123456789",
    "rank": "D",
    "default_probability": "> 20%",
    "facebook_days": 123,
    "social_datas": {
        "facebook_data": "...",
        [...]
    },
    "social_ids": {
        "facebok_id": "...",
        [...]
    },
    "social_lost_access": {
        "lost_fb_access":       false,
        "lost_linkedin_access": false,
        "lost_twitter_access":  false,
        "lost_google_access":   false,
        "lost_paypal_access":   false
    },
    "friends_friendlyscore": {
        "friends_friendlyscore": 0,
        "friends_friendlyscore_facebook": 0,
        "friends_friendlyscore_twitter": 0
    },
    "social_last_activity": {
        "last_twitter_activity_check_out_at": "2016-11-05T11:30:16+0100"
    },
    "raw_names": {
        "name_twitter": "John",
        "lastname_twitter": "Smith",
        "name_google": "John",
        "lastname_google": "Smith"
    },
    "full_data": {
        "has_full_facebook_data": true,
        "has_full_linkedin_data": false,
        "has_full_twitter_data": true,
        "has_full_paypal_data": false
    },
    "last_data": {
        "last_facebook_data_obtained_at": "2017-03-01T14:37:23+0100",
        "last_google_data_obtained_at": "2017-04-18T16:52:45+0200",
        "last_twitter_data_obtained_at": "2017-03-01T12:16:18+0100"
    },
    "status_updates": [],
    "other": {
        "os": "Linux",
        "os_version": "-",
        "browser": "Chrome",
        "browser_major_version": "57",
        "browser_version": "57.0.2987.133",
        "flash": "no check",
        "cookies": true,
        "screen_size": "1920 x 1080",
        "tags": "",
        "hash": "39e1a..."
    },
    "main_data": {
        "employer_name": "",
        "user_adress": "",
        "user_city": "",
        "user_post_code": "",
        "user_country_name": ""
    },
    "pictures": {
        "total": 1,
        "data": [
            {
                "url": "https:\/\/...",
                "source": "facebook"
            }
        ]
    },
    "activity_times": {
        "morning": 0,
        "daytime": 3,
        "evening": 0,
        "night": 0
    }
}
Data not ready (user does not exists, but data has already been scheduled for calculation)

If our data is not yet ready, the HTTP Status code will be 202 Accepted.

{
    "code": "202",
    "message": "Data for user PARTNER-ID not ready. Try again later."
}
User does not exist and is not scheduled for calculation

If user identified with PARTNER-ID has not been scheduled for score calculation API will return HTTP Status code 404 Not Found.

{
    "code": "404",
    "message": "No user partner-id: PARTNER-ID in app YOUR-APPLICATION-ID"
}

If user identified with FS-USER-ID has not been scheduled for score calculation API will return HTTP Status code 404 Not Found.

{
    "code": "404",
    "message": "No user id: FS-USER-ID in app YOUR-APPLICATION-ID"
}

Examples

Performing requests with cURL

Below are examples how API can be queried using cURL command line tool.

Fetching an access token

curl -H "Content-Type: application/json" \
     -X POST \
     -d JSON_DATA \
     'https://friendlyscore.com/oauth/v2/token'

where JSON_DATA is JSON with following fields:

{
    "client_id"     : "YOUR_CLIENT_ID",
    "client_secret" : "YOUR_CLIENT_SECRET",
    "grant_type"    : "client_credentials"
}

Scheduling calculation

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -X POST \
     -d JSON_DATA \
     'https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/calculate_score.json'

Where ACCESS_TOKEN is the access_token obtained via /oauth/v2/token action and JSON_DATA is JSON with following fields:

{
    "access_tokens": [
        "facebook":        "USER_FACEBOOK_ACCESS_TOKEN",
        "linkedin":        "USER_LINKEDIN_ACCESS_TOKEN",
        "twitter_user_id": "USER_TWITTER_ID",
        "google":          "USER_GOOGLE_ACCESS_TOKEN",
        "paypal":          "USER_PAYPAL_ACCESS_TOKEN"
    ],
    "webhook": "https://example.com/api/my-webhook?user=SAMPLE_USER_ID&is_ok=1",
    "ip": "127.7.7.7",
    "user_agent": {
      "os":                  "Linux",
      "osVersion":           "-",
      "browser":             "Chrome",
      "browserMajorVersion": "49",
      "browserVersion":      "49.0.2623.87",
      "mobile":              false,
      "flash":               "no check",
      "cookies":             true,
      "screenSize":          "1920 x 1080"
    }
}

Getting ready data

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -X GET \
     'https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/show.json'

Where ACCESS_TOKEN is the access_token obtained via /oauth/v2/token action and PARTNER-ID is user id from your database.

List of your users in friendlyscore

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -H "Accept: application/json;q=0.9,*/*;q=0.8" \
     -X GET \
     https://friendlyscore.com/api/v2/users.json

Where ACCESS_TOKEN is the access_token obtained via /oauth/v2/token action.

Changing positive parameter for user

For changing positive to true:

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -X PUT \
     'https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/positive/1.json'

For changing positive to false:

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -X PUT \
     'https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/positive/0.json'

Changing user status

curl -H "Authorization: Bearer ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -X POST \
     -d JSON_DATA \
     'https://friendlyscore.com/api/v2/users/partner-id/PARTNER-ID/status.json'

Where JSON_DATA contains two fields – status and status_description as shown below:

{
    "status": "processing",
    "status_description": "processing user data"
}

Performing requests with Ruby

Install oauth2-client:

gem install oauth2-client

Sample client:

require 'oauth2-client'
require 'json'

CLIENT_ID     = ' ... '
CLIENT_SECRET = ' ... '

client = OAuth2Client::Client.new(
    'https://friendlyscore.com',
    CLIENT_ID,
    CLIENT_SECRET
)

client.token_path = '/oauth/v2/token'

token = client.client_credentials.get_token

access_token = JSON.parse(token.body)['access_token']

res = client.connection.send_request(
    :get,
    '/api/v2/users.json', {
        :headers => {
            'Authorization' => 'Bearer ' + access_token
        }
    }
)

puts res.body

Performing requests with Python

#
# pip install requests
#

import requests
import json
from pprint import pprint

class FriendlyScore:

    CLIENT_ID         = ' ... '
    CLIENT_SECRET     = ' ... '
    BASE_URL          = 'https://friendlyscore.com/'
    REQUEST_TOKEN_URL = BASE_URL+'oauth/v2/token'

    def getToken(self):
        credentials = { 'client_id': self.CLIENT_ID, 'client_secret': self.CLIENT_SECRET, 'grant_type': 'client_credentials' }
        r = requests.post(self.REQUEST_TOKEN_URL, json=credentials)
        token = r.json()
        self.auth_headers = { 'Authorization': 'Bearer '+token['access_token'] }
        return r.status_code, token

    def url(self, endpoint):
        return self.BASE_URL+'api/v2/'+endpoint+'.json'

    def get(self, endpoint, params = {}):
        r = requests.get(self.url(endpoint), params=params, headers=self.auth_headers)
        return r.status_code, r.json()

    def put(self, endpoint, params = {}):
        r = requests.put(self.url(endpoint), json=params, headers=self.auth_headers)
        return r.status_code, r.json()

    def post(self, endpoint, params = {}):
        r = requests.post(self.url(endpoint), json=params, headers=self.auth_headers)
        return r.status_code, r.json()

    def getUsers(self, page=1, per_page=20):
        return self.get('users', { 'page': page, 'max_results': per_page })


fs = FriendlyScore()
fs.getToken()
code, users = fs.getUsers()
user        = users['results'][5]

# print("Response code is "+str(code)+"\n")
# pprint(users['results'][5])

print('User ID: ' + str(user['id']) + "\n")
print('  Status: ' + user['status'] + "\n")
print('  Status Description: ' + user['status_description'] + "\n")
print('  Positive: ' + str(user['is_positive']) + "\n")

code, resp = fs.put('users/id/'+user['id']+'/positive/1');
pprint(resp)

code, resp = fs.post('users/id/'+user['id']+'/status', {
    'status': 'Test',
    'status_description': 'Test desc'
});
pprint(resp)

code, user = fs.get('users/id/'+user['id']+'/show')

print('User ID: ' + str(user['id']) + "\n")
print('  Status: ' + user['status'] + "\n")
print('  Status Description: ' + user['status_description'] + "\n")
print('  Positive: ' + str(user['is_positive']) + "\n")

Performing requests with PHP

Below are examples how API can be queried using _PHP_ client.

composer require "friendlyscore/oauth2-client":"dev-master"

Usage:

$fs = new \FriendlyScore\OAuth2\Client\Provider\FriendlyScore([
	'clientId'    => ' -- client id here -- ',
	'clientSecret'=> ' -- client secret here -- ',
	'redirectUri' => ' -- redirect uri here -- ',
]);

try {
	// Try to get an access token using the client credentials grant.
	$accessToken = $fs->getAccessToken('client_credentials');

	echo "\ncalculateScore:\n";
	$res = $fs
		->with($accessToken)
		->byPartnerId('test-partner-id')
		->calculateScore([
			'access_tokens'     =>   [
				'facebook' => ' -- facebook access token -- '
			],
			'webhook'    => 'http://example.com/webhook.php?score-ready-for=test-partner-id',
			'ip'         => '1.2.3.4',
			'user_agent' => '{
				"os" : "Linux",
				"osVersion": "-",
				"browser": "Chrome",
				"browserMajorVersion": 50,
				"browserVersion": "50.0.2661.75",
				"mobile": false,
				"flash": "no check",
				"cookies": true,
				"screenSize": "1920 x 1080"
			}'
        ]);

	print_r($res);

	echo "\ngetUser:\n";
	$user = $fs
		// we don't need to call with and byPartnerId as those are stored in API client
		->getUser();

	echo "Score is not ready? Wait until API calls webhook when data is ready, and then rest of code should be executed.\n";
	echo "Hit enter to continue...\n";
	$fp = fopen("php://stdin", "r");
	$in = trim(fgets($fp));
	fclose($fp);

	echo "\ngetUser:\n";
	$user = $fs
		// we don't need to call with and byPartnerId as those are stored in API client
		->getUser();

	echo "USER:\n";
	print_r($user);
	echo "USER IP DATA:\n";
	print_r($fs->getUserIpData());
	$resp = $fs->setPositive(true);
	$user = $fs->byId($user->id)->getUser();
	print_r($user);
	$resp = $fs->setStatus('test', 'testing api calls');
	$user = $fs->getUser();
	print_r($user);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
	// Failed to get the access token
	exit($e->getMessage());
} catch (\GuzzleHttp\Exception\ClientException $e) {
	$code = $e->getResponse()->getStatusCode();
	$resp = $e->getResponse()->getBody();
	echo "User not found?\nResponse code from server was: {$code}.\nResponse was: {$resp}.\nClient thrown an exception:\n\n";
	echo $e->getMessage();
}