创建简短的推荐人链接
生成简短、可共享的推荐人链接,以实现用户到用户归因并跟踪来自有机推荐的应用程序安装。
版本要求:此功能需要 SDK 3.1.8 或更高版本。短链接在创建后 30 天内保持有效。
概述
什么是推荐人短链接
短链接将冗长、充满参数的奇异链接转换为简洁、安全的 URL,便于通过短信、社交媒体或应用程序内的邀请进行分享。
动态创建短链接,以便用户与朋友分享,邀请他们下载和使用您的应用程序。每个短链接都会跟踪推荐用户,使您能够衡量病毒式增长,并将新安装归功于特定的拥护者。
实施要求
所需组件
在创建推荐人短链接之前,请先收集这些元素:
- 单一链接:引导用户下载应用程序的基本跟踪链接。有关设置说明,请参阅奇异链接常见问题
- 动态参数:用于为链接添加上下文的可选自定义参数。查看跟踪链接参数中的可用选项
- 推荐人信息:分享链接的用户的姓名和 ID,以便将新安装归因于推荐人
SDK 方法
创建推荐人短链接
生成带有自定义参数和成功与错误状态回调处理程序的短链接。
方法签名:
static createReferrerShortLink(
baseLink: string,
referrerName: string,
referrerId: string,
passthroughParams: Record<string, any>,
completionHandler: (data: string | null, error?: string) => void
): void
参数:
- baseLink:原始奇异追踪链接 URL
- referrerName:引用用户的显示名称:引用用户的显示名称
- referrerId:推荐用户的唯一标识符
- passthroughParams: 直通参数:包含附加动态参数的对象(可选,如果没有,则传递空对象或 null
-
completionHandler:完成处理程序:带参数的回调函数
(shortLinkURL: string | null, error?: string)
有关完整的方法文档,请参阅createReferrerShortLink 参考资料。
基本使用示例
使用自定义参数创建短链接,并在成功回调中实现共享逻辑。
// TurboModule direct API (React Native 0.76+ New Architecture)
import React from 'react';
import { View, Button, Alert, Share } from 'react-native';
import NativeSingular from 'singular-react-native/jsNativeSingular';
export default function ReferralScreen() {
const handleShareReferral = () => {
// Create custom parameters for the link
const parameters = {
channel: 'sms',
campaign_id: 'summer_promo_2025',
referral_type: 'friend_invite'
};
// Generate the short referrer link
NativeSingular.createReferrerShortLink(
'https://sample.sng.link/D52wc/cuvk?pcn=test', // Base Singular Link
'John Doe', // Referrer name
'user_12345', // Referrer ID
parameters, // Custom parameters
(shortLink, error) => {
if (error) {
// Error occurred during link creation
console.error('Error creating short link:', error);
Alert.alert('Error', 'Failed to create share link. Please try again.');
} else if (shortLink) {
// Success - short link was created
console.log('Generated short link:', shortLink);
// Share the link using React Native's Share API
shareLink(shortLink);
}
}
);
};
const shareLink = async (shortLink) => {
try {
const result = await Share.share({
message: `Join me on this awesome app! ${shortLink}`,
url: shortLink // iOS only
});
if (result.action === Share.sharedAction) {
if (result.activityType) {
console.log('Shared with activity type:', result.activityType);
} else {
console.log('Link shared successfully');
}
} else if (result.action === Share.dismissedAction) {
console.log('Share dismissed');
}
} catch (error) {
console.error('Error sharing link:', error);
Alert.alert('Error', 'Failed to share link');
}
};
return (
<View>
<Button title="Share Referral Link" onPress={handleShareReferral} />
</View>
);
}
import React from 'react';
import { View, Button, Alert, Share } from 'react-native';
import { Singular } from 'singular-react-native';
export default function ReferralScreen() {
const handleShareReferral = () => {
// Create custom parameters for the link
const parameters = {
channel: 'sms',
campaign_id: 'summer_promo_2025',
referral_type: 'friend_invite'
};
// Generate the short referrer link
Singular.createReferrerShortLink(
'https://sample.sng.link/D52wc/cuvk?pcn=test', // Base Singular Link
'John Doe', // Referrer name
'user_12345', // Referrer ID
parameters, // Custom parameters
(shortLink, error) => {
if (error) {
// Error occurred during link creation
console.error('Error creating short link:', error);
Alert.alert('Error', 'Failed to create share link. Please try again.');
} else if (shortLink) {
// Success - short link was created
console.log('Generated short link:', shortLink);
// Share the link using React Native's Share API
shareLink(shortLink);
}
}
);
};
const shareLink = async (shortLink) => {
try {
const result = await Share.share({
message: `Join me on this awesome app! ${shortLink}`,
url: shortLink // iOS only
});
if (result.action === Share.sharedAction) {
if (result.activityType) {
console.log('Shared with activity type:', result.activityType);
} else {
console.log('Link shared successfully');
}
} else if (result.action === Share.dismissedAction) {
console.log('Share dismissed');
}
} catch (error) {
console.error('Error sharing link:', error);
Alert.alert('Error', 'Failed to share link');
}
};
return (
<View>
<Button title="Share Referral Link" onPress={handleShareReferral} />
</View>
);
}
高级实现
通过重试逻辑、加载状态和剪贴板回退实现完整的推荐系统。
// TurboModule direct API (React Native 0.76+ New Architecture)
import React, { useState } from 'react';
import { View, Button, Alert, ActivityIndicator } from 'react-native';
import NativeSingular from 'singular-react-native/jsNativeSingular';
import Clipboard from '@react-native-clipboard/clipboard';
export default function ReferralManager({ userId, userName, baseLink }) {
const [isGenerating, setIsGenerating] = useState(false);
const [lastGeneratedLink, setLastGeneratedLink] = useState(null);
const generateShortLink = (retryCount = 0) => {
return new Promise((resolve, reject) => {
const parameters = {
channel: 'in_app',
campaign_id: 'organic_referral',
user_tier: 'premium',
referral_timestamp: Date.now().toString()
};
NativeSingular.createReferrerShortLink(
baseLink,
userName,
userId,
parameters,
(shortLink, error) => {
if (error) {
// Retry logic with exponential backoff
if (retryCount < 3) {
const delay = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
console.log(`Retrying in ${delay}ms... (Attempt ${retryCount + 1}/3)`);
setTimeout(() => {
generateShortLink(retryCount + 1)
.then(resolve)
.catch(reject);
}, delay);
} else {
reject(new Error(error));
}
} else if (shortLink) {
setLastGeneratedLink(shortLink);
resolve(shortLink);
} else {
reject(new Error('Unknown error occurred'));
}
}
);
});
};
const handleShare = async () => {
setIsGenerating(true);
try {
const shortLink = await generateShortLink();
console.log('Short link generated:', shortLink);
// Attempt to share
const { Share } = require('react-native');
const result = await Share.share({
message: `${userName} invited you to join! ${shortLink}`,
url: shortLink
});
if (result.action === Share.sharedAction) {
console.log('Link shared successfully');
// Track share event
NativeSingular.event('referral_link_shared');
}
} catch (error) {
console.error('Error in share flow:', error);
// Fallback: Copy to clipboard if available
if (lastGeneratedLink) {
Clipboard.setString(lastGeneratedLink);
Alert.alert(
'Link Copied',
'Failed to share, but the referral link has been copied to your clipboard!',
[{ text: 'OK' }]
);
} else {
Alert.alert(
'Error',
'Failed to generate referral link. Please check your connection and try again.',
[{ text: 'OK' }]
);
}
} finally {
setIsGenerating(false);
}
};
const copyToClipboard = () => {
if (lastGeneratedLink) {
Clipboard.setString(lastGeneratedLink);
Alert.alert('Copied!', 'Referral link copied to clipboard');
} else {
Alert.alert('No Link', 'Please generate a link first');
}
};
return (
<View>
{isGenerating ? (
<ActivityIndicator size="large" />
) : (
<>
<Button
title="Share Referral Link"
onPress={handleShare}
disabled={isGenerating}
/>
{lastGeneratedLink && (
<Button
title="Copy Link"
onPress={copyToClipboard}
/>
)}
</>
)}
</View>
);
}
import React, { useState } from 'react';
import { View, Button, Alert, ActivityIndicator, Clipboard } from 'react-native';
import { Singular } from 'singular-react-native';
export default function ReferralManager({ userId, userName, baseLink }) {
const [isGenerating, setIsGenerating] = useState(false);
const [lastGeneratedLink, setLastGeneratedLink] = useState(null);
const generateShortLink = (retryCount = 0) => {
return new Promise((resolve, reject) => {
const parameters = {
channel: 'in_app',
campaign_id: 'organic_referral',
user_tier: 'premium',
referral_timestamp: Date.now().toString()
};
Singular.createReferrerShortLink(
baseLink,
userName,
userId,
parameters,
(shortLink, error) => {
if (error) {
// Retry logic with exponential backoff
if (retryCount < 3) {
const delay = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
console.log(`Retrying in ${delay}ms... (Attempt ${retryCount + 1}/3)`);
setTimeout(() => {
generateShortLink(retryCount + 1)
.then(resolve)
.catch(reject);
}, delay);
} else {
reject(new Error(error));
}
} else if (shortLink) {
setLastGeneratedLink(shortLink);
resolve(shortLink);
} else {
reject(new Error('Unknown error occurred'));
}
}
);
});
};
const handleShare = async () => {
setIsGenerating(true);
try {
const shortLink = await generateShortLink();
console.log('Short link generated:', shortLink);
// Attempt to share
const { Share } = require('react-native');
const result = await Share.share({
message: `${userName} invited you to join! ${shortLink}`,
url: shortLink
});
if (result.action === Share.sharedAction) {
console.log('Link shared successfully');
// Track share event
Singular.event('referral_link_shared');
}
} catch (error) {
console.error('Error in share flow:', error);
// Fallback: Copy to clipboard if available
if (lastGeneratedLink) {
Clipboard.setString(lastGeneratedLink);
Alert.alert(
'Link Copied',
'Failed to share, but the referral link has been copied to your clipboard!',
[{ text: 'OK' }]
);
} else {
Alert.alert(
'Error',
'Failed to generate referral link. Please check your connection and try again.',
[{ text: 'OK' }]
);
}
} finally {
setIsGenerating(false);
}
};
const copyToClipboard = () => {
if (lastGeneratedLink) {
Clipboard.setString(lastGeneratedLink);
Alert.alert('Copied!', 'Referral link copied to clipboard');
} else {
Alert.alert('No Link', 'Please generate a link first');
}
};
return (
<View>
{isGenerating ? (
<ActivityIndicator size="large" />
) : (
<>
<Button
title="Share Referral Link"
onPress={handleShare}
disabled={isGenerating}
/>
{lastGeneratedLink && (
<Button
title="Copy Link"
onPress={copyToClipboard}
/>
)}
</>
)}
</View>
);
}
实施最佳实践
错误处理
在回调中实施强大的错误处理,以管理网络故障、无效参数或服务器问题。
- 重试逻辑:针对瞬时网络错误实施指数回退
- 用户反馈:链接创建失败时显示清晰的错误信息
- 回退选项:提供其他共享方式(例如,如果短链接创建失败,则共享完整的奇异链接
-
验证:在调用
createReferrerShortLink之前验证参数,以便及早发现问题
跟踪和分析
利用推荐人信息建立病毒循环并衡量有机增长。
最佳实践:使用与内部用户识别系统一致的推荐人 ID。这样您就可以
- 将新安装归因于特定的推荐用户
- 奖励成功推荐的用户
- 跟踪病毒系数和 K 因子指标
- 识别最有价值的品牌拥护者
链接过期
在分享策略中规划 30 天的链接生命周期。
重要:短链接在 30 天后失效。对于长期活动或持续分享功能,请定期生成新的短链接,或使用完整的奇异链接作为备用。
常用案例
应用内推荐计划
让用户可以通过个性化推荐链接直接从应用中邀请朋友。
- 奖励系统:跟踪推荐并奖励成功注册朋友的用户
- 社交分享:与 React Native 分享 API 集成,用于短信、WhatsApp、电子邮件和社交媒体
- 个人邀请:在共享消息中包含推荐人姓名,实现个性化定制
用户生成的内容
当用户生成想要与他人分享的内容时,创建可分享链接。
- 内容归因:跟踪哪些内容推动了最多的应用安装
- 创作者识别:将新用户归属于内容创作者,实现游戏化
- 活动标签:根据内容类型或类别添加动态参数
活动邀请
为活动邀请函生成唯一链接,跟踪哪些与会者带来了新用户。
- 活动背景:在链接参数中包含活动 ID 和详细信息
- 与会者跟踪:衡量活动之间的病毒传播
- 网络效应:识别转换率最高的活动