This example demonstrates how to integrate server side SDK.

Configuring and running the server side SDK

  1. Register an account or login to the Mobile Connect Developer Portal and create an application to obtain your sandbox credentials.
  2. Install Docker.

    sudo apt install docker.io
    systemctl start docker
    systemctl enable docker
  3. Create at host machine folder /home/serverside/ for example and go into it.

  4. Download the Mobile Connect server side project.

    git init
    git pull https://github.com/Mobile-Connect/php_server_side_library.git
  5. Run docker image:
    sudo docker run -p 80:80 -it -v /home/serverside/:/opt/lampp/htdocs/ cswl/xampp bash
  6. In Docker container run the next commands:
    cd /opt/lampp/htdocs/php-server-side-library
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
    composer install
    mv .env.example .env
    php artisan key:generate
    chmod -R 777 /opt/lampp/htdocs/php-server-side-library/
    chmod -R 777 /opt/lampp/htdocs/mobile-connect-sdk/
    mysql</opt/lampp/htdocs/init_db.sql 
  7. Note: please use your actual path to PHP server side library in Docker image instead of /opt/lampp/htdocs/ if it is different.

  8. Open the configuration file: \php-server-side-library\app\data\data.json.
  9. Note: if you operate in the EU then you should use EU Discovery Service domain in discovery url: https://eu.discover.mobileconnect.io.

    Here are 10 parameters:

    {
      “msisdn”: your msisdn
      "client_id": your client Id,
      "clientSecret": your client Secret,
      "discoveryURL": your Discovery endpoint,
      "redirectURL": "http://your redirect url",
      "xRedirect": "True",
      "includeRequestIP": "False",
      "apiVersion": api version: "mc_v1.1" or "mc_v2.0" or "mc_di_r2_v2.3",
      "scope": scopes,
      "client_name":  your client name
    }

    Installation is finished.

    You can open the configuration file .env at the root of the project and set correct values for variables DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME and DB_PASSWORD .
    After changing configuration files you have to restart the docker container:

    sudo docker run -p 80:80 -it -v /home/serverside/:/opt/lampp/htdocs/ cswl/xampp bash
    mysql</opt/lampp/htdocs/init_db.sql 

    Prepare client side application (IOS or Android application) or Demo App for Server Side application.


Using the server side application

The server side SDK for PHP automates much of the basic housekeeping and configuration tasks of your application’s integration with Mobile Connect. Many of these functions activate in the Discovery phase, independently of the Identity Gateway endpoint your application will ultimately call, and so are described here for your reference.

Discovery

Discovery is the process of determining an end-user's Mobile Connect Identity Provider, i.e. the Operator ID Gateway. The discovery response will provide with a number of endpoints and the operator-specific credentials which will need to use with this ID Gateway.
The server side SDK has a method that accepts user's data as parameters and needs MobileConnectConfig object initialized as part of the MobileConnectWebInterface object - that's enough to make a successful call to the Mobile Connect Discovery endpoint, and the methods attemptDiscovery, attemptDiscoveryAfterOperatorSelection, and handleUrlRedirect do just that, building and making the call, and then handling the response. The server side library also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout.

Provider Metadata

A successful call to the Mobile Connect Discovery endpoint returns the end user’s Mobile Network Operator (MNO) and describes the Mobile Connect services that MNO supports, via a URI to the MNO’s Provider Metadata. The metadata describes the Identity Gateway endpoints (Mobile Connect services) your application or service can use and how those endpoints are configured – for example, the response types an endpoint can return, the subject identifier types supported, or the Identity Services encryption algorithms in use.
Although Provider Metadata is the primary source of information detailing the Identity Gateway configuration, it does not change often, so a cached version can be used without risk of expired data causing errors. The Mobile Connect server-side library handles both the querying of the Provider Metadata and the caching.

  • If the Provider Metadata URI returns no data, the cached metadata is used.
  • Where the cached data is out of date (defaulting to 15-minute intervals) a subsequent query of the URI is attempted, and in the event of a second failed response, expired cached data is used.
  • Should neither the cached data nor the Provider Metadata URI return data (such as an error upon first user login) default values are used.

Regardless of the source, the server side library parses the Provider Metadata into a discrete list of properties. See the OpenID Provider Metadata definition for a list of the metadata available, although you should note that Mobile Connect's implementation may not be exhaustive.
The ProviderMetadata object is available on DiscoveryResponse.ProviderMetadata.

Supported Services

Before your application or service can call an Identity Gateway endpoint (scope), you need to know if the MNO supports the scope you are calling. The Mobile Connect SDK provides the method IsMobileConnectServiceSupported($scope) in the discoveryReponse, which can be accessed as follows:

 $supported = $discoveryResponse->IsMobileConnectServiceSupported(“mc_authz mc_identity_signup”)

The method accepts a comma- or space-separated list of scopes, which it then checks against the list of supported scopes in the Provider Metadata.

  • If all of the scopes passed as arguments are present in the Provider Metadata, the function returns true.
  • If any of the passed scopes are not present in the metadata, the function returns false.
  • If the Provider Metadata is not available, or the scopes attribute is missing, null, or an empty string, the function returns an exception: “Provider Metadata scopes unavailable”

.

Mobile Connect Version Compatibility

The SDK implements version autodetection, this is a mechanism which helps to detect version by configuration parsing, provided values and additional analysis.

Identify gateway supported versions:

  • If a Provider Metadata document is available then get a list of supported versions based on the mc_version value.
  • If the Provider Metadata document is not available the supported version will be mc_v1.1.

Identify request version:

  • If the version value is not empty and the SDK supports this version (see note), then use this.
  • If the version value is empty or the SDK doesn’t support the selected version then the scope and list of supported versions (based the ID Gateway) will be analysed to detect the version of MC API, which can be used. Verification order:
    • If the list of supported versions contains mc_di_r2_v2.3 and the scope is valid for this version, then this version will be used.
    • Otherwise, if the list of supported versions contains mc_v2.0 and the scope is valid for this version, then this version will be used.
    • Otherwise, if list of supported versions contains mc_v1.1 and the scope is valid only for this version, then this version will be used.
    • Otherwise, if the list of supported versions contains only mc_v1.2 and the scope is valid for this version, then this version will be used (but a warning will indicate that version is deprecated).
    • If current scope doesn’t match with versions included in list of supported versions, the SDK will throw invalid scope exception.

NOTE: mc_v1.1, mc_v1.2, mc_v2.0, mc_di_r2_v2.3 are supported.

This algorithm is implemented in the VersionDetection class.

The getCurrentVersion method takes three parameters:

  • version (from configuration)
  • scope (from configuration)
  • ProviderMetadata (from DiscoveryResponse).

The method parses and verifies parameters and then returns the correct MC API version depending upon the conditions.

public static function getCurrentVersion($version, $scope, $providerMetadata) {
        $supportedVersions = VersionDetection::getSupportedVersions($providerMetadata);
        if (!empty($version) && VersionDetection::isVersionSupported($version)) {
            return $version;
        } else {
            $currentScopes = StringUtils::convertToListBySpace($scope);
            if (in_array(Version::MC_DI_R2_V2_3, $supportedVersions) && VersionDetection::containsScopesV2_3($currentScopes)) {
                return Version::MC_DI_R2_V2_3;
            } else if (in_array(Version::MC_V2_0, $supportedVersions) && VersionDetection::containsScopesV2_0($currentScopes)) {
                return Version::MC_V2_0;
            } else if (in_array(Version::MC_V1_1, $supportedVersions) && VersionDetection::containsScopesV1_1($currentScopes)) {
                return Version::MC_V1_1;
            } else if(in_array(Version::MC_V1_2, $supportedVersions) && sizeof($supportedVersions) == 1 && VersionDetection::containsScopesV2_0($currentScopes)) {
                return Version::MC_V1_2;
            } else {
                throw new InvalidScopeException($scope);
            }
        }
    }

The VersionDetection::getCurrentVersion method calls in each method of MobileConnectInterface class to detect correct version.

    public static function StartAuthentication(IAuthenticationService $authentication, DiscoveryResponse $discoveryResponse,
        $encryptedMSISDN, $state, $nonce, MobileConnectConfig $config, MobileConnectRequestOptions $options)
    {
        try {
            $clientId = $discoveryResponse->getResponseData()['response']['client_id'];
            $authorizationUrl = $discoveryResponse->getOperatorUrls()->getAuthorizationUrl();
            $authOptions = empty($options) ? new AuthenticationOptions() : $options->getAuthenticationOptions();
            $version = VersionDetection::getCurrentVersion($authOptions->getVersion(), $authOptions->getScope(), $discoveryResponse->getProviderMetadata());
            $response = $authentication->StartAuthentication($clientId, $authorizationUrl, $config->getRedirectUrl(),
                $state, $nonce, $encryptedMSISDN, $version, $authOptions);
        } catch (\InvalidArgumentException $e) {
            return MobileConnectStatus::Error("invalid_argument", "An argument was found to be invalid during the process. " . $e->getMessage(), $e);
        } catch (MCSDK\Exceptions\MobileConnectEndpointHttpException $e) {
            return MobileConnectStatus::Error("http_failure", "An HTTP failure occured while calling the discovery endpoint, the endpoint may be inaccessible", $e);
        } catch (Exception $e) {
            return MobileConnectStatus::Error("unknown_error", "An unknown error occured while calling the Discovery service to obtain operator details", $e);
        } catch (InvalidScopeException $e) {
            return MobileConnectStatus::Error("invalid_scope", $e->getMessage());
        }
        return MobileConnectStatus::Authorization($response->getUrl(), $state, $nonce);
    }

Using version the auto-detection mechanism in the MobileConnectInterface class ensures that the verifications and request generation in Authentication and Token Services are correct. Furthermore it allows the automatic processing of version, regardless of using only SDK library or Server Side SDK.

Application Short Name

The application you register with the Mobile Connect Developer Portal includes an Application Short Name, which is stored in the API Exchange and returned in responses from the Discovery service. The server side SDK captures the returned applicationShortName and includes it when constructing calls to the Mobile Connect Authorisation and Identity endpoints.

Mobile Connect Constants

The server side SDK provides a number of constants for referencing the Mobile Connect services by scope. They are available in the MCLibrary\MobileConnectConstants class, and can be called using the following syntax:

 MCLibrary\MobileConnectConstants::MOBILECONNECTIDENTITYPHONE

The above example calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the server side library will remove any duplicates before making the call to the Identity Gateway.

The following constants are available:

Mobile Connect Product Constant Identifier Literal Value
Authentication (v1.0) MOBILECONNECT "openid"
Authentication (v1.1) MOBILECONNECTAUTHENTICATION "openid mc_authn"
Authorisation MOBILECONNECTAUTHORIZATION "openid mc_authz"
Identity: Phone Number MOBILECONNECTIDENTITYPHONE "openid mc_identity_phonenumber"
Identity: Signup MOBILECONNECTIDENTITYSIGNUP "openid mc_identity_signup"
Identity: Signup Plus* MOBILECONNECTIDENTITYSIGNUPPLUS "openid mc_identity_signupplus"
Identity: National ID MOBILECONNECTIDENTITYNATIONALID "openid mc_identity_nationalid"
KYC plain MOBILECONNECTKYCPLAIN "openid mc_kyc_plain"
KYC hashed MOBILECONNECTKYCHASHED "openid mc_kyc_hashed"
ATTR VM Match MOBILE_CONNECT_ATTR_VM_MATCH "openid mc_attr_vm_match"
ATTR VM Hash MOBILE_CONNECT_ATTR_VM_MATCH_HASH "openid mc_attr_vm_match_hash"

*This constant is available to support possible future products.

Login Hint Support

You have the option to provide the login hint to the Identity Gateway using one of three formats: MSISDN, encrypted MSISDN, and PCR. Your decision on how to provide the login hint is governed by two factors:

  • The login hint formats supported by the Identity Gateway.
  • Whether you are a “Trusted Service Provider”; an unencrypted MSISDN is only accepted from a trusted provider – attempting to send one if you are not trusted returns an error.

The Mobile Connect server side SDK provides functions to test for login hint support in the Identity Gateway, namely:

  • LoginHint::IsSupportedForMSISDN()
  • LoginHint::IsSupportedForEncryptedMSISDN()
  • LoginHint::IsSupportedForPCR()

Each function checks the login_hint_methods_supported attribute in the Provider Metadata returned from the Discovery endpoint.

Once you have decided how to provide the login hint, the server side Library offers a further three functions to build it for you:

  • LoginHint::GenerateForMSISDN($MSISDN)
  • LoginHint::GenerateForEncryptedMSISDN($encryptedMSISDN)
  • LoginHint::GenerateForPCR ($PCR)

id_token Validation

A successful response from the Identity Gateway includes an id_token – a JSON Web Token, which validates against a JSON Web Keyset (JWKS), available at a URL specified in the Provider Metadata attribute jwks_uri.

The server side SDK performs a number of automatic validation actions to ensure the integrity of the response source, such as checking whether the token has expired. It also fetches the data from the jwks_uri location and stores it alongside the associated Discovery response, where it is cached. The following functions are then available to you to support id_token validation:

  • checkIDTokenSignature(id_token, $keyset) verifies the signature of the id_token based on the JWKS data. A successful validation returns true; a failed validation returns false; a missing JWKS certificate returns an error.
  • JWKeysetService::RetrieveJWKS($url) allows you to fetch all of the keys from the JWKS data.
  • returnMatchingJWKSEntries allows you to fetch specific keys matching the following parameters:

    • kty – key type (e.g. RSA)
    • alg – algorithm (e.g. RS256)
    • use – sig (signature) or enc (encryption)
    • kid – key identifier

 

Using Mobile Connect Authentication

Important. Headless mode is not used any more. Please, use Server Initiated API instead.

The server-side SDK allows you to call a method that accepts a reference to a configuration file as a parameter. With your developer credentials specified in the configuration file, you have everything you need to make a successful call to the Mobile Connect Discovery endpoint, and the methods AttemptDiscovery and HandleUrlRedirect do just that, building and making the call, and then handling the response. The server-side library also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout. Once the end user has entered their MSISDN or specified their operator, and a successful Discovery response is received, the server side library builds the call to the Authentication endpoint. A successful authentication returns an id_token containing the user’s PCR, which is unpacked and available for verification against your user register.

Server side application

With your configuration specified in the configuration file you have everything you need to make a successful call to the server side application.p/>

Client side application allows to sends a request to server side application in three modes: msisdn, mcc_mnc, none

Example request:
If you are using only msisdn the request to your server side part will be: http://localhost/php-server-side-library/public/server_side_api/start_discovery?msisdn=447700900901
When you are using mcc and mnc it will be: http://localhost/php-server-side-library/public/server_side_api/start_discovery?mcc=901&mnc=01
If you choose None mode: http://localhost/php-server-side-library/public/server_side_api/start_discovery
Also sourceIp can be included to request: http://localhost/php-server-side-library/public/server_side_api/start_discovery?sourceIp=10.0.0.1

Client side application sends a GET request with client data to server side application.
Then server side application makes startDiscovery method call with your data from configuration file. This method calls attemptDiscoveryWrapper method with your parameters from config file. And then startAuthentication method perfoms for getting authentication URL.

    public function startDiscovery(Request $request) {
        $msisdn = Input::get(Constants::MSISDN);
        $mcc = Input::get(Constants::MCC);
        $mnc = Input::get(Constants::MNC);
        $sourceIp = Input::get(Constants::SOURCE_IP);
        return $this->AttemptDiscoveryWrapper($msisdn, $mcc, $mnc, $sourceIp, $request);
    }

Note:If discovery request with msisdn, mcc_mnc or source ip fails - method perform Discovery UI flow to discover operator.

1) If you selected the msisdn mode: method generates auth URL and respond with 302 redirect to this URL. After you follow the redirect, and pass consent confirmation screen, redirect will be proceed by server side handleRedirect method.
2) mcc_mnc mode.
3) none mode.
If you selected the mcc_mnc mode or none mode:
you will be redirected to the operator selection page. Here you can type your msisdn and process page. Then the scenario should be the same as on first mode.

     
    public function handleRedirect(Request $request) {
        $mcc_mnc = Input::get(Constants::MCC_MNC);
        $code = Input::get(Constants::CODE);
        $state = Input::get(Constants::STATE);
        $databaseHelper =  new DatabaseHelper();
        $requestUri = $request->getRequestUri();
        if(!empty($code)){
            $discoveryResponse = $databaseHelper->getDiscoveryResponseFromDatabase($state);
            $nonce = $databaseHelper->getNonceFromDatabase($state);
            $authStatus = Controller::$_mobileConnect->HandleUrlRedirectWithDiscoveryResponse($requestUri, $discoveryResponse, $state, $nonce, new MobileConnectRequestOptions());
            $endPointStatus = EndpointUtils::startEndpointRequest(Controller::$_mobileConnect, Controller::$_config, $discoveryResponse, $authStatus);
            return !empty($endPointStatus) ? HttpUtils::createResponse($endPointStatus): HttpUtils::createResponse($authStatus);
        } elseif (!empty($mcc_mnc)){
            $response = Controller::$_mobileConnect->HandleUrlRedirectWithDiscoveryResponse($requestUri, null, $state, null, new MobileConnectRequestOptions());
            $authResponse = $this->StartAuth($response->getSDKSession(), $response->getDiscoveryResponse()->getResponseData()[Constants::SUB_ID],
                Controller::$_config);
            if (McUtils::isErrorInResponse($authResponse)) {
                return HttpUtils::createResponse($authResponse);
            } else {
                $databaseHelper->writeDiscoveryResponseToDatabase($authResponse->getState(), $response->getDiscoveryResponse());
                $databaseHelper->writeNonceToDatabase($authResponse->getState(), $authResponse->getNonce());
                return redirect($authResponse->getUrl());
            }
        }
        else{
            $errorCode = Input::get(Constants::ERROR);
            $errorDesc = Input::get(Constants::ERROR_DESCR);
            $databaseHelper->clearDiscoveryCacheByState($state);
            return HttpUtils::createResponse(MobileConnectStatus::Error($errorCode, $errorDesc, null));
        }
    }

     
    private function startAuthentication($sdkSession, $subscriberId, $options) {
        $status = Controller::$_mobileConnect->StartAuthentication($sdkSession, $subscriberId, null, null, $options);
        return $status;
    }

Discovery caching

Discovery response is cached in server-side library with following rules:
1) After succeeded Discovery request, Discovery response is cached with used mcc/mnc, msisdn or sourceIp.
2) Expiration time for Discovery Response cache is the same as "ttl" field in Discovery Response - if Discovery Response expired - that deleted from cache.
3) Next requests for Discovery with the same mcc/mnc, msisdn or sourceIp - Discovery request shouldn't be performed, Discovery response should be taken from cache.
4) If auth call responds with error - Discovery Response deleted from the cache, and server-side library redirects you to Discovery UI.

 

Using Mobile Connect Authorisation

The server side SDK allows you to call the Identity Gateway with the scope parameter set to “mc_authz”, which signifies an authorisation request for a single transaction (the id_token and access token returned from the Gateway have a timeout set to zero, so expire after a single use). You should check that the Identity Gateway supports version 2.0 of the Mobile Connect Profile (available in the Provider Metadata) before attempting a call.

To make a successful authorisation call, you must provide the following additional parameters:

  • client_name – specifies the name of the application/service requesting authorisation. This value is taken from Options and must match the Application Short Name.
  • context – specifies the reason for the authorisation request, and should be built from the data describing the transaction requiring authorisation. The context is displayed on the authenticating (mobile) device only.
  • binding_message – specifies a reference string to display on the device from which the authorisation request was invoked, and on the authenticating (mobile) device, allowing the user to visually verify that the confirmation message originated from their transaction request.

Note: the authorisation prompt displayed to the user combines all three parameters, which cannot exceed 93 bytes in total.

The following example shows how to add the additional Authorisation options to the Authentication call described in Using Mobile Connect Authentication.

Note: calls to Authorisation are structured in exactly the same way, but using the scopes “mc_authz”as applicable. Please check the "data.json" file for attributes:

 
	"scope":"openid mc_authz",
	"client_name": your client name,
	"context": your context,
	"binding_message": your binding message

startAuthorisation method generates URL for authorisation, which is sent to client side application.

    private function startAuthorisation($sdkSession, $subscriberId, $options) {
        $status = Controller::$_mobileConnect->StartAuthentication($sdkSession, $subscriberId, null, null, $options);
        return $status;
    }

After that client side makes redirects session and gets the code. Client side sends this code to server side, which uses this code for RequestToken method performing
    public static function RequestToken(IAuthenticationService $authentication, IJWKeysetService $jwks, DiscoveryResponse $discoveryResponse,
        $redirectedUrl, $expectedState, $expectedNonce, MobileConnectConfig $config, MobileConnectRequestOptions $options = null) {
        $response = null;
        $query = parse_url($redirectedUrl, PHP_URL_QUERY);
        parse_str($query, $queryValue);
        if(empty($expectedState)) {
            return MobileConnectStatus::Error("required_arg_missing", "ExpectedState argument was not supplied, this is needed to prevent Cross-Site Request Forgery", null);
        }
        if (empty($expectedNonce)) {
            return MobileConnectStatus::Error("required_arg_missing", "expectedNonce argument was not supplied, this is needed to prevent Replay Attacks", null);
        }
        $actualState = $queryValue['state'];
        if ($expectedState != $actualState) {
            return MobileConnectStatus::Error("invalid_state", "State values do not match, this could suggest an attempted Cross-Site Request Forgery", null);
        }
        try {
            $code = $queryValue['code'];
            $clientId = $config->getClientId();
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getResponseData()) && isset($discoveryResponse->getResponseData()['response']['client_id'])) {
                $clientId = $discoveryResponse->getResponseData()['response']['client_id'];
            }
            $clientSecret = $config->getClientSecret();
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getResponseData()) && isset($discoveryResponse->getResponseData()['response']['client_secret'])) {
                $clientSecret = $discoveryResponse->getResponseData()['response']['client_secret'];
            }
            $requestTokenUrl = null;
            if (!empty($discoveryResponse) && !empty($discoveryResponse->getOperatorUrls()) && !empty($discoveryResponse->getOperatorUrls()->getRequestTokenUrl())) {
                $requestTokenUrl = $discoveryResponse->getOperatorUrls()->getRequestTokenUrl();
            }
            $issuer = $discoveryResponse->getProviderMetadata()["issuer"];
            $response = $authentication->RequestToken($clientId, $clientSecret, $requestTokenUrl, $config->getRedirectUrl(), $code);
            $jwKeySet = $jwks->RetrieveJWKS($discoveryResponse->getOperatorUrls()->getJWKSUrl());
            $authOptions = empty($options) ? new AuthenticationOptions() : $options->getAuthenticationOptions();
            $version = VersionDetection::getCurrentVersion($authOptions->getVersion(), $authOptions->getScope(), $discoveryResponse->getProviderMetadata());
            return static::HandleTokenResponse($authentication, $response, $clientId, $issuer, $expectedNonce, $jwKeySet,
                $version, $options);
        } catch(Exception $ex) {
            return MobileConnectStatus::Error("unknown_error", "A failure occured while requesting a token", $ex);
        }
        return MobileConnectStatus::Complete($response);
    }

After RequestToken method performing server side returns the Token JSON response to client side application.

The level of authentication required to authorise the transaction defaults to LoA2 (Authorisation), but you can increase it by adding the optional parameter acr_value and setting the value to "3" (for Authorisation Plus).

 

Using Mobile Connect Identity and Attributes

A successful call to the Authorisation endpoint returns an id_token identifying the user, and an access token that grants your application permission to request their personal information (referred to as Claims). This information contains a range of data; the exact data you can request is specified in the access token, and is limited to those Claims the end user has permitted as part of the original authorisation request.

Note: the access token is for single use only, and expires immediately upon use.

You request access to the Identity endpoint by specifying the appropriate scope. The server side library provides constants that you can pass when requesting specific Identity products:

  • Identity: Phone Number – MOBILECONNECTIDENTITYPHONE
  • Identity: Sign-up – MOBILECONNECTIDENTITYSIGNUP
  • Identity: National Identity – MOBILECONNECTIDENTITYNATIONALID

Please check the "data.json" file for attributes:

 
	"scope":"openid mc_identity_signup",
	"client_name": your client name,
	"context": your context,
	"binding_message": your binding message

Upon successful authorisation, the server side library provides an IdentityResponse with the user information JSON available as a property. The following example can be used to convert the JSON data to a class - IdentityData - which is provided with all recognised claims.

    public static function startEndpointRequest($mobileConnect, $config, $discoveryResponse, $authResponse) {
        try {
            $status = null;
            $mobileConnectWebResponse = ResponseConverter::Convert($authResponse);
            $token = $mobileConnectWebResponse->getToken()[Parameters::ACCESS_TOKEN_HINT];
            $scopes = $config->getScopes();
            $apiVersion = VersionDetection::getCurrentVersion($config->getApiVersion(), $scopes, $discoveryResponse->getProviderMetadata());
            if ($apiVersion == (DefaultOptions::VERSION_1_1) & !empty($discoveryResponse->getOperatorUrls()->getUserInfoUrl())) {
                $status = EndpointUtils::requestUserInfo($mobileConnect, $discoveryResponse, $scopes, $token);
            } else if (($apiVersion == (DefaultOptions::VERSION_DI_2_3) || $apiVersion == (DefaultOptions::VERSION_2_0)) & !empty($discoveryResponse->getOperatorUrls()->getPremiumInfoUrl())) {
                $status = EndpointUtils::requestIdentity($mobileConnect, $discoveryResponse, $scopes, $token);
            }
        } catch (InvalidScopeException $e) {
            return MobileConnectStatus::Error("invalid_scope", $e->getMessage());
        }
        return $status;
    }
    private static function requestUserInfo($mobileConnect, $discoveryResponse, $scopes, $token) {
        foreach ( Constants::USERINFO_SCOPES as $userInfoScope) {
            if ( strpos($scopes, $userInfoScope) !== false) {
                $status = $mobileConnect->RequestUserInfoByDiscoveryResponse($discoveryResponse, $token, new MobileConnectRequestOptions());
                return $status;
            }
        }
    }
    private static function requestIdentity($mobileConnect, $discoveryResponse, $scopes, $token) {
        foreach (Constants::IDENTITY_SCOPES as $identityScope) {
            if (strpos($scopes, $identityScope) !== false) {
                $status = $mobileConnect->RequestIdentityByDiscoveryResponse($discoveryResponse, $token, new MobileConnectRequestOptions());
                return $status;
            }
        }
    }

The following example shows how to add the additional Authorisation and Identity options to the Authentication call described in Using Mobile Connect Authentication, resulting in a correctly configured call to the Identity: Phone Number service.

Note: calls to Identity: Sign-up and Identity: National ID are structured in exactly the same way, but using the scopes “mc_identity_signup” and “mc_identity_nationalid” as applicable.

 

KYC Support for DI 2.3

The SDK allows to use KYC product with the scope parameter set to "mc_kyc_plain" or "mc_kyc_hashed". Current version must be set to “mc_di_r2_v2.3”.
To make a successful authorisation call, you must provide the KYC Claims in "kycClaims.json" file:

  • KYC Plain:
    {
      "name": "henrydorsettcase",
      "address": "119840701chibacityjapan"
    }

    Please check the "data.json" file for attributes:

     
    	"scope":"openid mc_kyc_plain",
    	"client_name": your client name,
    	"context": your context,
    	"binding_message": your binding message
  • KYC Hashed:
    {
      "name": "10b182c8d5395b6f9279848b5bcc070071644cb09548b2fd5dad09dbb290ba3a",
      "address": "ab7898d762572dbe066ccd14f25d9b8f3c1dc405a24ae4f1b611755ac517b8ff"
    }

    Please check the "data.json" file for attributes:

     
    	"scope":"openid mc_kyc_hashed",
    	"client_name": your client name,
    	"context": your context,
    	"binding_message": your binding message
  • You can use split claims:

  • "Given_name", "family_name"; "houseno_or_housename", "postal_code", "town".
  • "Given_name_hashed", "family_name_hashed".
  • "Houseno_or_housename_hashed", "postal_code_hashed", "town_hashed".
  • or concatenated claims:

  • "Name", "address", "birthdate". "birthdate" is an optional claim.
  • "Name_hashed", "address_hashed", "birthdate_hashed". "birthdate_hashed" is an optional claim.
  • The server side SDK performs a number of automatic claims validation:

        private function validateKycParams($options) {
            $kycClaims = $options->getClaims();
            if((strpos($options->getScope(), Scope::KYC_PLAIN) !== false) && ($options->getVersion() == DefaultOptions::VERSION_DI_2_3)) {
                if (!empty($kycClaims->getName())) {
                    ValidationUtils::validateParameter($kycClaims->getAddress(), Parameters::ADDRESS);
                }
                else if (!empty($kycClaims->getGivenName())) {
                    $params = implode(Constants::SPACE, array(
                        empty($kycClaims->getFamilyName())? Parameters::FAMILY_NAME: null,
                        empty($kycClaims->getHousenoOrHousename())? Parameters::HOUSENO_OR_HOUSENAME: null,
                        empty($kycClaims->getPostalCode())? Parameters::POSTAL_CODE: null,
                        empty($kycClaims->getCountry())? Parameters::COUNTRY: null,
                        empty($kycClaims->getTown())? Parameters::TOWN: null));
                    ValidationUtils::validateParameter(null, $params);
                }
                else {
                    ValidationUtils::validateParameter(null, Parameters::NAME.Constants::OR.Parameters::GIVEN_NAME );
               }
            }
            if((strpos($options->getScope(), Scope::KYC_HASHED) !== false) && ($options->getVersion() == DefaultOptions::VERSION_DI_2_3)) {
                if (!empty($kycClaims->getNameHashed())) {
                    ValidationUtils::validateParameter($kycClaims->getAddressHashed(), Parameters::ADDRESS_HASHED);
                }
                else if (!empty($kycClaims->getGivenNameHashed())) {
                    $params = implode(Constants::SPACE, array(
                        empty($kycClaims->getFamilyNameHashed())? Parameters::FAMILY_NAME_HASHED: null,
                        empty($kycClaims->getHousenoOrHousenameHashed())? Parameters::HOUSENO_OR_HOUSENAME_HASHED: null,
                        empty($kycClaims->getPostalCodeHashed())? Parameters::POSTAL_CODE_HASHED: null,
                        empty($kycClaims->getCountryHashed())? Parameters::COUNTRY_HASHED: null,
                        empty($kycClaims->getTownHashed())? Parameters::TOWN_HASHED: null));
                    ValidationUtils::validateParameter(null, $params);
                }
                else {
                    ValidationUtils::validateParameter(null, Parameters::NAME_HASHED.Constants::OR.Parameters::GIVEN_NAME_HASHED);
                }
            }
        }

    After successful validation claims are added to authorization request as query parameter "claims". The value of claims parameter is presented as: {"premiuminfo": {"claim_name": {"value": "claim_value"}, ...}}

     

    Further Reference