Integration methods

Updated at:

Integrate the outbound bot configuration page into your system using an iframe.

For more information, see Alibaba Cloud logon-free solution.

Procedure

Create a RAM user and grant permissions (skip this step if a RAM user already exists)

1.1. Grant the AliyunSTSAssumeRoleAccess permission to the RAM user

image

1.2. Create a RAM role

Log on to the RAM console using your Alibaba Cloud account and create a RAM role. You can also create a RAM role by calling the CreateRole API operation.

image

image

image

1.3. Grant permissions to the role

1.4. Obtain the roleArn parameter

image

1.5. pom.xml

SDK download URL

<dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-sts</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
 </dependencies>

1.6. Code sample

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class Test {

    private static final String SIGN_IN_DOMAIN = "https://signin.aliyun.com/federation";

    private static String getRoleArn(String accountId, String roleName) {
        return String.format("acs:ram::%s:role/%s", accountId, roleName);
    }

    /**
     * Obtain a logon token using a security token.
     * https://help.aliyun.com/document_detail/91913.html
     *
     * @param accesskeyId
     * @param accessKeySecret
     * @param securityToken
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private static String getSignInToken(String accesskeyId, String accessKeySecret, String securityToken)
            throws IOException, URISyntaxException {
        URIBuilder builder = new URIBuilder(SIGN_IN_DOMAIN);

        builder.setParameter("Action", "GetSigninToken")
                .setParameter("AccessKeyId", accesskeyId)
                .setParameter("AccessKeySecret", accessKeySecret)
                .setParameter("SecurityToken", securityToken)
                .setParameter("TicketType", "mini");

        HttpGet request = new HttpGet(builder.build());
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try (CloseableHttpResponse response = httpclient.execute(request)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String context = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(context);
                return jsonObject.getString("SigninToken");
            } else {
                System.out.println(response.getStatusLine());
            }
        }
        return null;
    }

    private static String getChatbotLoginUrl(String pageUrl, String signInToken) throws URISyntaxException {
        URIBuilder builder = new URIBuilder(SIGN_IN_DOMAIN);
        builder.setParameter("Action", "Login");
        // The URL to which the user is redirected when the logon expires. This is typically a URL on your own web server that performs a 302 redirect.
        builder.setParameter("LoginUrl", "https://signin.aliyun.com/login.htm");
        // The actual chatbot page to access, such as the Dialog Studio management page or the details page of an instance.
        builder.setParameter("Destination", pageUrl);
        builder.setParameter("SigninToken", signInToken);
        HttpGet request = new HttpGet(builder.build());
        return request.getURI().toString();
    }

    /**
     * Obtain temporary identity credentials for a user by calling the AssumeRole operation.
     * For more information, see https://help.aliyun.com/document_detail/28763.html
     *
     * @param accountId
     * @param accessKeyId
     * @param accessKeySecret
     * @param ramRole
     * @return
     * @throws ClientException
     */
    private static AssumeRoleResponse.Credentials assumeRole(String accountId, String accessKeyId,
                                                             String accessKeySecret, String ramRole)
            throws ClientException {
        String defaultRegion = "cn-hangzhou";
        IClientProfile profile = DefaultProfile.getProfile(defaultRegion, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        // Set the RAM ARN. The accountId is the UID of the resource owner, which is your Alibaba Cloud account.
        request.setRoleArn(getRoleArn(accountId, ramRole));
        // A custom parameter to differentiate tokens for user-level access auditing. The value must match the following regular expression: ^[a-zA-Z0-9\.@\-_]+$
        request.setRoleSessionName("session-name");
        // The expiration time in seconds. The value must be between 900 and 3600. The default value is 3600.
        request.setDurationSeconds(3600L);
        AssumeRoleResponse response = client.getAcsResponse(request);
        return response.getCredentials();

    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        try {
            /*
             * Step 0: Prepare a RAM user and grant permissions.
             */
            // The ID of your Alibaba Cloud account.
            String accountId = "your_account_id";
            // The RAM role used to access the outbound bot product. You can grant the AliyunOutboundbotFullAccess permission to this role as needed.
            // The ramRole is an example value. Replace it with the name of the role you just created.
            String ramRole = "your_ram_role_name";
            // The AccessKey ID and AccessKey secret of a RAM user that has the AliyunSTSAssumeRoleAccess permission.
            // The accessKeyId and accessKeySecret are example values. Replace them with your actual credentials.
            String accessKeyId = "your_access_key_id";
            String accessKeySecret = "your_access_key_secret";


            /*
             * Step 1: Obtain a temporary AccessKey pair and a security token by calling the AssumeRole operation.
             */
            AssumeRoleResponse.Credentials credentials = assumeRole(accountId, accessKeyId, accessKeySecret, ramRole);

            System.out.println("Expiration: " + credentials.getExpiration());
            System.out.println("Access Key Id: " + credentials.getAccessKeyId());
            System.out.println("Access Key Secret: " + credentials.getAccessKeySecret());
            System.out.println("Security Token: " + credentials.getSecurityToken());

            /*
             * Step 2: Obtain a SigninToken.
             */
            String signInToken = getSignInToken(credentials.getAccessKeyId(),
                    credentials.getAccessKeySecret(),
                    credentials.getSecurityToken());

            System.out.println("Your SigninToken is: " + signInToken);

            /*
             * Step 4: Construct a logon-free URL. https://outboundbot4service.console.aliyun.com is the address of the logon-free console for Outbound Bot Service for resellers.
             */
            // Integrate the list of LLM scenarios.
            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script?instanceId=your_instance_id&nluServiceType=DialogStudio";
            // Integrate the global configuration for LLMs.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script/global_variable?instanceId=your_instance_id&nluServiceType=DialogStudio";
            // Integrate the flow management for LLMs.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script/flow?instanceId=c5c293dc-bbe0-4eb5-a590-0e9a22ba4fc8&nluServiceType=DialogStudio";
            // Integrate the voice cloning for LLMs.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script/llm_voice_clone?instanceId=c5c293dc-bbe0-4eb5-a590-0e9a22ba4fc8&nluServiceType=DialogStudio";
            // Integrate the details of LLM scenario management.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script/prompt_script_detail?instanceId=your_instance_id&scriptId=your_script_id&nluServiceType=DialogStudio";
            // Integrate the Q&A pair management for LLMs.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_prompt_script/llm_faq?instanceId=your_instance_id&nluServiceType=DialogStudio";
            // Integrate the scenario management for small models.
//            String pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_script?instanceId=your_instance_id&nluServiceType=DialogStudio";
             // Integrate the details of small model scenario management.
//            String  pageUrl = "https://outboundbot4service.console.aliyun.com/#/outboundbot_script/ds_scriptsdetail?instanceId=your_instance_id&scriptId=your_script_id";

            String accessUrl = getChatbotLoginUrl(pageUrl, signInToken);
            System.out.println("Your PageUrl is : " + accessUrl);
        } catch (ClientException e) {
            System.out.println("Failed:");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
    }
}

Note the following in Step 4:
•	Replace the value of `instanceId` as needed.
        •	Replace the value of `scriptId` as needed.
1.7. Frontend integration
1.	You can open the generated link directly in a browser.
2.	To embed the link in your business system as an iframe, enable the following two configurations for the iframe: 
allow="microphone *" allowfullscreen

Note: When nested in an iframe, if the outbound bot system detects that the user logon has expired when making an API request, it sends a message to the parent application using postMessage. The parent application can then refresh the page or redirect to a logon page as needed.
Sample code:
<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Iframe Test</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <script>
    // When the outbound bot page calls an API and the logon cookie is invalid, it sends a postMessage to the parent page. The parent page can then handle the message.
    function handleMessage(e) {
      // Accept messages only from the outbound bot domain name.
      if (!['https://outboundbot4service.console.aliyun.com'].includes(e.origin)) {
        return;
      }
      // e.data = {code: 'ConsoleNeedLogin', message: 'Logon timed out. Please log on again.'}
      if (e.data && e.data.code === 'ConsoleNeedLogin') {
        // TODO: Redirect to the logon page or refresh the main site page.
      }
    }
    window.addEventListener('message', handleMessage);
  </script>
</head>
<body>
  <iframe src="http://signin.aliyun.com/federation?Action=Login&LoginUrl=https%3A%2F%2Fsignin.aliyun.com%2Flogin.htm&Destination=http%3A%2F%2Foutboundbot4service.console.aliyun.com%2F%23%2Foutboundbot_script%3FinstanceId%3D2a10e7f2-8f13-4a99-9f57-fea3b0f9c6f8%26nluServiceType%3DDialogStudio&SigninToken=svX6LAkjGGjnQTYHFNh2tdAMRoNeseZyFMuVWpZpceayC3wSTpvPidzMqcSpDxsUtwZCSUwEVNvJQpTuoozLV3R9BRyscrJQWedCxuguTRTrFBqvLFrVMkTD2ouWFb6KEJGS7vHbCUH5TkA6Y4LRa7Lyjsyz614LrpBkdkudWDZ4rGbXriQbyhCTJVn5LhXGwvyDprNcAPFAybfUzMLtQPgFtEhji9bU" width="100%" style="height: calc(100vh);" allow="microphone *" allowfullscreen></iframe>
</body>
</html>