3
votes

In my firebase account, I create dynamic link manually and I got that dynamic link in my application, but the issue is that I need to create dynamic link randomly using core php.

I have tried below steps

1 Step : Goes to Firebase console account

2 Step : Select app and then under Grow > dynamic links > new dynamic link

Here I am able to create manually, but not able to create using core php.

2

2 Answers

12
votes

Easy way to do that

function shorten_URL ($longUrl) {
  $key = 'WEB_API_KEY';
  $url = 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=' . $key;
  $data = array(
     "dynamicLinkInfo" => array(
        "dynamicLinkDomain" => "YOUR_DOMAIN.page.link",
        "link" => $longUrl
     )
  );

  $headers = array('Content-Type: application/json');

  $ch = curl_init ();
  curl_setopt ( $ch, CURLOPT_URL, $url );
  curl_setopt ( $ch, CURLOPT_POST, true );
  curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
  curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
  curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($data) );

  $data = curl_exec ( $ch );
  curl_close ( $ch );

  $short_url = json_decode($data);
  if(isset($short_url->error)){
      return $short_url->error->message;
  } else {
      return $short_url->shortLink;
  }

}

// Call the function with the URL
shorten_URL('https://YOUR_LONG_URL');

All what you have to do is to add your firebase domain from dynamic links and your web api key from settings.

0
votes

You can use kreait/firebase-php composer package to create dynamic links via Firebase API. See setup guide and dynamic links API.

Also there's a simpler way. You may want to manually construct dynamic link instead of calling Firebase API. I used this guide and created mxl/firebase-dynamic-link composer package.

  1. Install it with composer:

    $ composer require mxl/firebase-dynamic-link
    
  2. Build dynamic link:

    use MichaelLedin\FirebaseDynamicLink\DynamicLink;
    
    DynamicLink::for('your_subdomain.page.link', 'https://your_domain.com/path/to/page')->build();