Skip to content
Open
100 changes: 85 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ It will be:
```kotlin
dependencies {
implementation("com.github.User:Repo:Tag") // Example
implementation("com.github.Short-io:android-sdk:v1.0.4") // Use this
implementation("com.github.Short-io:android-sdk:v1.0.9") // Use this
}
```
### 3. Sync the Project
Expand Down Expand Up @@ -80,51 +80,72 @@ import com.github.shortiosdk.ShortioSdk

### 🔗 SDK Usage

#### Initialize the SDK

To start using ShortioSdk, you need to initialize it early in your app lifecycle, preferably in your Activity's onCreate() method or in your custom Application class.

Example: Initialize in Activity

```kotlin
override fun onCreate() {
super.onCreate()
ShortioSdk.initialize(apiKey, domain)
}
```
* apiKey: Your API key string for SDK initialization.
* domain: The default domain to use for URL shortening.

### 💡 How It Works

The app demonstrates:

#### ✅ Generating Short Links

```kotlin
import com.github.shortiosdk.ShortioSdk
import com.github.shortiosdk.ShortIOParameters
import com.github.shortiosdk.ShortIOResult

try {
val params = ShortIOParameters(
domain = "your_domain", // Replace with your Short.io domain
originalURL = "your_originalURL" // Replace with your Short.io domain
)
} catch (e: Exception) {
Log.e("ShortIO", "Error: ${e.message}", e)
}
```

**Note**: Both `domain` and `originalURL` are the required parameters. You can also pass optional parameters such as `path`, `title`, `utmParameters`, etc.
**Note**: Only the `originalURL` is the required parameter as `domain` is passed in the initialize method of SDK. You can also pass optional parameters such as `path`, `title`, `utmParameters`, etc.

```kotlin
val apiKey = "your_public_apiKey" // Replace with your Short.io Public API Key

thread {
try {
when (val result = ShortioSdk.shortenUrl(apiKey, params)) {
when (val result = ShortioSdk.createShortLink(params)) {
is ShortIOResult.Success -> {
println("Shortened URL: ${result.data.shortURL}")
Log.d("ShortIOResult","Shortened URL: ${result.data.shortURL}")
}
is ShortIOResult.Error -> {
val error = result.data
println("Error ${error.statusCode}: ${error.message} (code: ${error.code})")
Log.d("ShortIOResult","Error ${error.statusCode}: ${error.message} (code: ${error.code})")
}
}
} catch (e: Exception) {
Log.e("ShortIO", "Error: ${e.message}", e)
}
}
```
**Note**: Deprecated: `createShortLink`(apiKey, params) is still supported for backward compatibility but is no longer recommended for use. Use `createShortLink(params)` instead.

## 📄 API Parameters

The `ShortIOParameters` struct is used to define the details of the short link you want to create. Below are the available parameters:


| Parameter | Type | Required | Description |
| ------------------- | ----------- | -------- | ------------------------------------------------------------ |
| `domain` | `String` | ✅ | Your Short.io domain (e.g., `example.short.gy`) |
| `originalURL` | `String` | ✅ | The original URL to be shortened |
| `domain` | `String` | ✅ (Deprecated) | Your Short.io domain (e.g., `example.short.gy`). ⚠️ Deprecated. No longer required — inferred from API key. May be removed in future versions. |
| `originalURL` | `String` | ✅ | The original URL to be shortened |
| `cloaking` | `Boolean` | ❌ | If `true`, hides the destination URL from the user |
| `password` | `String` | ❌ | Password to protect the short link |
| `redirectType` | `Int` | ❌ | Type of redirect (e.g., 301, 302) |
Expand Down Expand Up @@ -241,7 +262,7 @@ keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -sto

3. Tap on **“Add link”** under the **Open by Default** section.

4. Add your URL and make sure to enable the checkbox for your link.
4. Add your URL if not added and make sure to enable the checkbox for your link.

### 🔗 Step 4: Open the App Using a Deep Link

Expand All @@ -253,30 +274,79 @@ keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -sto

### 🧭 Step 5: Handle Incoming URLs with onNewIntent() Method

To retrieve the original URL from Short.io links in your Android app, you can handle incoming intents in onNewIntent(), which allows your activity to process links that are opened while it is already running.

1. Open your main activity file (e.g., MainActivity.kt).

2. Override the `onNewIntent()` method to receive new intents when the activity is already running:

```kotlin
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val result = ShortioSdk.handleIntent(intent)
Log.d("New Intent", "Host: ${result?.host}, Path: ${result?.path}")
lifecycleScope.launch {
val result = ShortioSdk.handleIntent(intent)
// Access the original URL
val originalUrl = result?.destinationUrl
Log.d("New Intent",
"Host: ${result?.host},
Path: ${result?.path},
Original URL: $originalUrl"
)
}
}
```

3. In the same activity, also handle the initial intent inside the `onCreate()` method:
3. In the same activity, To handle the initial intent inside the `onCreate()` method:

```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
val result = ShortioSdk.handleIntent(intent)
Log.d("New Intent", "Host: ${result?.host}, Path: ${result?.path}")
// Access the original URL
val originalUrl = result?.destinationUrl
Log.d("New Intent",
"Host: ${result?.host},
Path: ${result?.path},
Original URL: $originalUrl"
)
}
}
```

### 🔐 Secure Short Link

If you want to encrypt the original URL before shortening it. For privacy or security reasons — the SDK provides a utility function called createSecure. This function encrypts the original URL using AES-GCM and returns a secured URL with a separate decryption key.

```kotlin
val originalURL = "your_original_URL"
val result = ShortioSdk.createSecure(originalURL)
Log.d("SecureURL", "RESULT: ${result}")
Log.d("securedOriginalURL", "URL: ${result.securedOriginalURL}")
Log.d("securedShortUrl", "URL: ${result.securedShortUrl}")
```

### 🔄 Conversion Tracking

Track conversions for your short links to measure campaign effectiveness. The SDK provides a simple method to record conversions.

```kotlin
CoroutineScope(Dispatchers.IO).launch {
try {
val res = ShortioSdk.trackConversion(
domain: "https://{your_domain}", // ⚠️ Deprecated (optional):
clid: "your_clid", // ⚠️ Deprecated (optional):
conversionId: "your_conversionID" (optional)
)
// conversionId can be 'signup', 'purchase', 'download', etc.
Log.d("Handle Conversion Tracking", "Handle Conversion Tracking: $res")
} catch (e: Exception) {
Log.e("Handle Conversion Tracking", "Error calling trackConversion", e)
}
}
```

### ✅ Final Checklist
### ✅ Final Checklist for Deep Linking

* App is signed with the correct keystore.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package com.github.shortiosdk

val shortenUrl = "https://api.short.io/links/public"
val baseURL = "https://api.short.io/links/public"
Original file line number Diff line number Diff line change
@@ -1,32 +1,29 @@
package com.github.shortiosdk.Helpers

import okhttp3.OkHttpClient
import okhttp3.Request
import android.net.Uri


fun HandleClick(uri: String): String? {
val client = OkHttpClient()

val url = when {
uri.contains("utm_medium=android", ignoreCase = true) -> uri
uri.contains("?") -> "$uri&utm_medium=android"
else -> "$uri?utm_medium=android"
fun extractClidFromUrl(urlString: String): String? {
return try {
val uri = Uri.parse(urlString)
uri.getQueryParameter("clid")
} catch (e: Exception) {
e.printStackTrace()
null
}
}

val request = Request.Builder()
.url(url)
.addHeader("accept", "application/json")
.build()
fun removeUtmParams(url: String): String {
val uri = Uri.parse(url)
val builder = uri.buildUpon().clearQuery()

return try {
client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
response.code.toString()
} else {
"Link is not Valid"
uri.queryParameterNames
.filter { !it.startsWith("utm_", ignoreCase = true) }
.forEach { key ->
uri.getQueryParameters(key)?.forEach { value ->
builder.appendQueryParameter(key, value)
}
}
} catch (e: Exception) {
e.toString()
}

return builder.build().toString()
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.github.shortiosdk


data class ShortIOParameters(
val originalURL: String,
val cloaking: Boolean? = null,
Expand Down Expand Up @@ -30,7 +29,7 @@ data class ShortIOParameters(
val integrationFB: String? = null,
var integrationGA: String? = null,
val integrationGTM: String? = null,
val domain: String,
var domain: String? = null,
val folderId: String? = null
) {
init {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.github.shortiosdk

import com.github.shortiosdk.ShortIOResponseModel

public sealed class ShortIOResult {
sealed class ShortIOResult {
data class Success(val data: ShortIOResponseModel) : ShortIOResult()
data class Error(val data: ShortIOErrorModel) : ShortIOResult()
}

public sealed class StringOrInt {
sealed class StringOrInt {
data class Str(val value: String) : StringOrInt()
data class IntVal(val value: Int) : StringOrInt()
}

data class SecureResult(
val securedOriginalURL: String,
val securedShortUrl: String
)
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ data class UrlComponents(
val path: String?,
val query: String?,
val fragment: String?,
val fullUrl: String
val fullUrl: String,
val destinationUrl: String?
)
Loading