You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SharePoint页面通过JavaScript+ODATA查询Dynamics CRM的SystemUserId

如何在SharePoint页面通过JavaScript结合OData查询Dynamics CRM的SystemUserId

Hey there, let's walk through exactly how to pull the Dynamics CRM SystemUserId from a SharePoint page using JavaScript and OData. I'll break this down into clear, actionable steps with code examples you can adapt for your environment.

1. 获取并转换SharePoint当前用户的全名格式

First up, we need to grab the current user's full name from SharePoint (which comes in the Surname, Forename format) and reformat it to match how names are stored in CRM (Forename Surname).

Here's the code to do that using SharePoint's Client Object Model:

// Initialize SharePoint client context
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var currentUser = web.get_currentUser();

// Load only the user's Title (full name) to keep the request lightweight
ctx.load(currentUser, 'Title');

// Execute the asynchronous request to SharePoint
ctx.executeQueryAsync(
    function onSuccess() {
        // Get the raw full name from SharePoint: "Surname, Forename"
        var spFullName = currentUser.get_title();
        
        // Split and reformat to "Forename Surname"
        var nameParts = spFullName.split(', ');
        var userFullName = nameParts[1] + ' ' + nameParts[0];
        
        // Pass the reformatted name to our CRM query function
        fetchCrmSystemUserId(userFullName);
    },
    function onError(sender, args) {
        console.error('Failed to retrieve SharePoint user info:', args.get_message());
    }
);

A quick note: Double-check that SharePoint's user title uses the exact Surname, Forename format with a comma and space. If your environment uses a different separator, adjust the split(', ') argument accordingly.

2. 构建OData查询并获取CRM的SystemUserId

Next, we'll use the reformatted full name to build an OData request against Dynamics CRM's Organization Data Service. This will let us pull the matching SystemUserId.

Add this function to handle the CRM query:

function fetchCrmSystemUserId(userFullName) {
    // Replace #CRM_URL# with your actual CRM organization URL (e.g., https://yourorg.crm.dynamics.com)
    var crmBaseUrl = "#CRM_URL#/XRMServices/2011/OrganizationData.svc/";
    
    // Build the OData query: filter by FullName, select only SystemUserId, limit to 50 results
    var odataQuery = `SystemUserSet?$top=50&$select=SystemUserId&$filter=FullName eq '${userFullName}'`;
    var fullRequestUrl = crmBaseUrl + odataQuery;
    
    // Send the GET request to CRM
    var xhr = new XMLHttpRequest();
    xhr.open('GET', fullRequestUrl, true);
    xhr.setRequestHeader('Accept', 'application/json');
    
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            var response = JSON.parse(xhr.responseText);
            var matchingUsers = response.d.results;
            
            if (matchingUsers.length > 0) {
                // Grab the first matching user's SystemUserId
                var systemUserId = matchingUsers[0].SystemUserId;
                console.log('Found CRM SystemUserId:', systemUserId);
                // Add your logic here to use the ID (e.g., store it, display it on the page)
            } else {
                console.warn('No CRM user found with FullName:', userFullName);
            }
        } else {
            console.error('Failed to fetch CRM data:', xhr.statusText);
        }
    };
    
    xhr.onerror = function() {
        console.error('Network error occurred while contacting CRM');
    };
    
    xhr.send();
}

Key Considerations to Avoid Headaches:

  • CORS Issues: If SharePoint and CRM are on different domains, direct XMLHttpRequest calls will hit CORS restrictions. Fix this by either:
    • Deploying a proxy page in SharePoint to forward requests to CRM
    • Using CRM's newer Web API (if your version supports it) and configuring CORS for your CRM instance
  • Duplicate Full Names: CRM might have multiple users with the same full name. To avoid grabbing the wrong ID, add more filter criteria (like EmailAddress1 eq 'user@domain.com') to your OData query.
  • Permissions: Make sure the current SharePoint user has permission to access CRM's Organization Data Service. Without this, you'll get 401/403 errors.
  • URL Replacement: Don't forget to swap #CRM_URL# with your actual CRM URL (e.g., https://yourcompany.crm.dynamics.com).

内容的提问来源于stack exchange,提问作者Jason James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:55:14