# Integrate with Segment.com

### How to integrate with Segment.com?

We already have the possibility to natively retrieve analytics information from Segment. This means that you will get all your tracking information (track/screen/page method) inside your Flagship reports depending on your visitors' assignment.\
You can follow our [support article](https://flagship.zendesk.com/hc/en-us/articles/360012284159-Segment-integration) to better know how our native Segment.com integration works.

Now, you might also want to send data from Flagship to Segment.com, to retrieve them into other tools. Hopefully, the method we're providing will help you reach that goal.

{% hint style="info" %}
📘 Reminder

The following custom integration isn’t under maintenance. It has been design to be generic, to work on the largest set of cases and codebase.\
As a Yoda Master developer, you are the king of your own code.
{% endhint %}

The following code example takes into account that you already started your Flagship SDK and synchronized your user to get the flag (the modification) he should be assigned to.\
The user is now seeing the flag, and you need to activate it, to alert us and count one more user in the corresponding report.\
When activating it with our Flagship method, you will trigger the Segment method at the same time and send the information you need to, like in the code example below.

It also implies that you imported the Segment library before calling their method.// ... some other codes

{% tabs %}
{% tab title="JavaScript" %}

```javascript
// ... some other codes

Flagship.start("<ENV_ID>", "<API_KEY>", {
  onVisitorExposed: ({ exposedVisitor, fromFlag }) => {
    analytics.track(exposedVisitor.id, 'Flagship_Source_JS', fromFlag.metadata)
  }
})

//... do some stuff

// Then Calling flag.getValue() or flag.visitorExposed() anywhere will trigger onVisitorExposed callback
```

{% endtab %}

{% tab title="React  / React native" %}

```jsx
//... some other codes

<FlagshipProvider 
   onVisitorExposed={({ exposedVisitor, fromFlag }) => {
    analytics.track(exposedVisitor.id, 'Flagship_Source_JS', fromFlag.metadata)
  }} >
 //... do some stuff

// Then Calling flag.getValue() or flag.visitorExposed() anywhere will trigger onVisitorExposed callback
</FlagshipProvider>
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

require_once __DIR__.'/vendor/autoload.php';

use Flagship\Config\DecisionApiConfig;
use Flagship\Enum\CacheStrategy;
use Flagship\Flagship;
use Flagship\Model\ExposedFlagInterface;
use Flagship\Model\ExposedVisitorInterface;
use Segment\Segment;

// callback
function onVisitorExposed(ExposedVisitorInterface $visitorExposed, ExposedFlagInterface $fromFlag)
{
    // Forward the information to your third party
    // This block is excuted each time the visitorExposed is called and sucess

    //Get metadata of exposed flag
    $trackProperties = json_decode(json_encode($fromFlag->getMetadata()), true);
    
    Segment::init("YOUR_WRITE_KEY");

    // Send information to Segment
    Segment::track([
        "userId" => $visitorExposed->getId(),
        "event" => "flagship_event",
        "properties" => $trackProperties
    ]);
}

// Start SDK
Flagship::start("your_env_id", "your_api_key", DecisionApiConfig::decisionApi()
        ->setCacheStrategy(CacheStrategy::BATCHING_AND_CACHING_ON_FAILURE)
        ->setOnVisitorExposed('onVisitorExposed')); // set the callback

// Create visitor
$visitor = Flagship::newVisitor('visitorId')->build();

//Fetch flags
$visitor->fetchFlags();

// Ex: get flag for vip feature
$flag = $visitor->getFlag("displayVipFeature", false);

// Use this flag value to enable displaying the vip feature.
$flag->getValue();

// You should keep in mind by default on getting the flag value ,the SDK expose the visitor.

// batch and send all hits in the pool 
Flagship::close();

// when the expose sucess ==>  the callback defined in the "setOnVisitorExposed" config will be triggered
```

{% endtab %}

{% tab title=".NET" %}

```csharp
// ... some other codes

//Define the function that should be called when the OnVisitorExposed event is triggered
void Config_OnVisitorExposed(Flagship.FsVisitor.IExposedVisitor exposedVisitor, Flagship.FsFlag.IExposedFlag exposedFlag)
{
    Analytics.Client.Track(exposedVisitor.Id, "Flagship_Source_DotNet", new Properties() {
    { "CampaignId", exposedFlag.Metadata.CampaignId },
    { "VariationGroupId", exposedFlag.Metadata.VariationGroupId },
    { "VariationId", exposedFlag.Metadata.VariationId },
});
}

//Create sdk config object
var config = new Flagship.Config.DecisionApiConfig();

//Add OnVisitorExposed event
config.OnVisitorExposed += Config_OnVisitorExposed;

// Start the SDK
Flagship.Main.Fs.Start("your_env_id", "your_api_key", config);

//... do some stuff

// Then Calling flag.GetValue() or flag.VisitorExposed() anywhere will trigger onVisitorExposed event
```

{% endtab %}

{% tab title="iOS" %}

```swift
// We assume you created visitor and fetched flags

// Retrieve the current visitor
if let currentVisitor = Flagship.sharedInstance.sharedVisitor{
    
    // Get the flag object
    let myFlagObject = currentVisitor.getFlag(key: "my_flag", defaultValue:"defaultValue")
    
    // Expose the campaign
    myFlagObject.userExposed()
    
    // Get Flagship campaign information and send it to Segment
    let campaign_metadata =  myFlagObject.metadata().toJson()
    Analytics.shared().track("Flagship_Source_ios", properties: campaign_metadata)
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
Flagship.start(
	getApplication(),
  _ENV_ID_,
  _API_KEY_,
  FlagshipConfig.DecisionApi()
    .withOnVisitorExposed { visitorExposed : VisitorExposed, exposedFlag: ExposedFlag<*> ->
      
    // Get Flagship campaign information, map it, and send it to Segment
  	val campaignMetadata = myFlag.metadata().toJson()
    campaignMetadata.keys().asSequence().associateWith { campaignMetadata[it]}.let { map ->
       val properties = Properties()
       properties.putAll(map)
       Analytics.with(appContext).track("Flagship_Source_Android", properties)
    }
  }

//Later in your app, trigger a visitor flag exposition:
val myFlag = visitor.getFlag("myFlag", "defaultValue")
myFlag.visitorExposed()
```

{% endtab %}

{% tab title="Java" %}

```java
// Flagship campaign user exposition
    
    Flag<String> myFlag = flagshipVisitor.getFlag("myFlag", "defaultValue");
    myFlag.userExposed();

// Get Flagship campaign information, map it, and send it to Segment

    JSONObject json = myFlag.metadata().toJSON();
    if (json != null) {
        Iterator<String> iterator = json.keys();
        HashMap<String, Object> values = new HashMap<>();
        while (iterator.hasNext()) {
            String name = iterator.next();
            values.put(name, json.opt(name));
        }
        Properties properties = new Properties();
        properties.putAll(values);
        Analytics.with(appContext).track("Flagship_Source_Java", properties);
    }
```

{% endtab %}

{% tab title="Python" %}

```python
# Flagship campaign activation

    flagship_visitor.activate_modification("my_flag")

# Get Flagship campaign information and send it to Segment 

    campaign_info = flagship_visitor.get_modification_info("my_flag")
    analytics.track("#User123", "Flagship_Source_Python", campaign_info)
```

{% endtab %}

{% tab title="Go" %}

```go
# Flagship campaign activation
  fsVisitor.ActivateModification("my_flag")

# Get Flagship campaign information and send it to Segment 
  modifInfos, _ := fsVisitor.GetModificationInfo("my_flag")

  data := analytics.Track{
    UserId: fsVisitor.ID,
    Event:  "Flagship_Source_Go",
    Properties: analytics.NewProperties().
      Set("cid", modifInfos.CampaignID).
      Set("vgid", modifInfos.VariationGroupID).
      Set("vid", modifInfos.VariationID).
      Set("isref", modifInfos.IsReference).
      Set("val", modifInfos.Value),
  }
  segmentClient.Enqueue(data)
```

{% endtab %}
{% endtabs %}

### How to verify the hit in Segment?

After you successfully integrate with Segment, you can check in your [Segment's Source Debugger](https://segment.com/docs/connections/sources/debugger/) if the hit is correctly sent with all the information needed.

An example of properties passed for an iOS application:

![](/files/kItOkv7cQkiUrwn5jZzq)

Any feedback? [We would be really happy to have a quick chat!](mailto:product.feedback@abtasty.com?subject=Flagship%20Segment%20Integration%20Feedback)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.abtasty.com/server-side/integrations/analytics/integrate-with-segmentcom.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
