簡體   English   中英

如何使用C#Web API關閉CRM機會實體

[英]How to close CRM opportunity entity using C# web api

我是CRM的新手。 我已經為應用程序實現了OAuth。 我正在使用Web API方法來訪問特定的CRM用戶數據。 我已經成功地為“獲取用戶機會”,“更新用戶機會”實現了Web api。 但是我無法為“接近機會”或“獲勝機會”做同樣的事情。

注意:訪問用戶數據時,我沒有使用OrganizationService代理。 我正在使用OAuth令牌並調用特定的API請求URL。

請指導我實現相同目標。 如果有人可以在代碼上顯示任何示例,或者如何在郵遞員中進行測試,則非常感謝。

我的查詢:

1)是否可以使用OAuth令牌,我們可以在不傳遞用戶憑據的情況下連接到OrganizationServiceProxy嗎?

例如:獲得機會

要求網址: https : //testdevcrm.crm8.dynamics.com/api/data/v9.1/opportunities

標題:

授權:承載者(accessToken)

接受:應用/ JSON

的OData-MAXVERSION:4.0

OData兼容版本:4.0

方法類型:GET

  #region FectchUserOpportunities
    public async Task<JToken> FectchUserOpportunities(string systemuserid,string bearerToken)
    {
        JToken jResu = null;
        try
        {
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            string filter = "&$filter=_createdby_value eq '" + systemuserid + "' and opportunityid ne null and statuscode eq 1&$orderby=createdon asc&$top=5";
            string opportunitiesURL = string.Concat(GenericMethods.GetAppSetting("FetchCRMOpportunitiesAPI"), filter);
            var result = httpClient.GetAsync(opportunitiesURL).Result;

            if (result != null)
            {
                var opporJSON = await result.Content.ReadAsStringAsync();
                JToken jsonResult = JsonConvert.DeserializeObject<JObject>(opporJSON);
                jResu = jsonResult["value"];
            }
            else
            {
                jResu = null;
            }
        }
        catch (Exception ex)
        {
        }
        return jResu;
    }

    #endregion

嗯,有一個特定的動作,可以從WebAPI調用為WIN或LOSS的Close機會。 叫做

WinOpportunity

LoseOpportunity

現在,您如何通過Webapi調用它。 這是從前端方調用它的示例代碼。 您可以使用Postman輕松地復制它,並查看它如何幫助您。

var parameters = {};
var opportunityclose = {};
opportunityclose.activityid = "00000000-0000-0000-0000-000000000000"; //Delete if creating new record 
opportunityclose["@odata.type"] = "Microsoft.Dynamics.CRM.opportunityclose";
opportunityclose["opportunityid@odata.bind"] = "/opportunities(8CA20837-715F-E911-A83A-000D3A3852A3)";
parameters.OpportunityClose = opportunityclose;
parameters.Status = 0;

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/WinOpportunity", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(parameters));

var parameters = {};
var opportunityclose = {};
opportunityclose.activityid = "00000000-0000-0000-0000-000000000000"; //Delete if creating new record 
opportunityclose["@odata.type"] = "Microsoft.Dynamics.CRM.opportunityclose";
opportunityclose["opportunityid@odata.bind"] = "/opportunities(8CA20837-715F-E911-A83A-000D3A3852A3)";
parameters.OpportunityClose = opportunityclose;
parameters.Status = 0;

    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/LoseOpportunity", false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                //Success - No Return Data - Do Something
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(parameters));

最后,我使用Web api實現了C#代碼,以獲取WON的機會。

碼:

    #region UpdateUserOpportunityWon

    public async Task<string> UpdateUserOpportunityWon(string bearerToken, string opportunityid, string wonsubject, string actualend = "", int actualrevenue = 0, string wondesc = "")
    {
        string jResu = "";
        try
        {
            string opportunitiesURL = string.Format(GenericMethods.GetAppSetting("UpdateCRMOpportunityAPI"), opportunityid);
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            //httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            string jsonBody = "";
            if (String.IsNullOrEmpty(actualend))
            {
                jsonBody = "{'Status':3,'OpportunityClose':{'subject':'" + wonsubject + "','actualrevenue':" + actualrevenue + ",'description':'" + wondesc + "','opportunityid@odata.bind':'" + opportunitiesURL + "'}}";
            }
            else
            {
                jsonBody = "{'Status':3,'OpportunityClose':{'subject':'" + wonsubject + "','actualrevenue':" + actualrevenue + ",'actualend':'" + actualend + "','description':'" + wondesc + "','opportunityid@odata.bind':'" + opportunitiesURL + "'}}";
            }
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            string opportunitiesWonURL = string.Format(GenericMethods.GetAppSetting("UpdateOpportunityWon"), opportunityid);

            var result = httpClient.PostAsync(opportunitiesWonURL, content).Result;
          //  TelemetryHelper.Trace("API res", result.ToString());
            string statuscode = result.StatusCode.ToString();
            if (result != null)
            {
                var opporJSON = await result.Content.ReadAsStringAsync();
                if (statuscode.ToLower() == "nocontent")
                {
                    jResu = statuscode; //success
                }
                else
                {
                    JToken jsonResult = JsonConvert.DeserializeObject<JObject>(opporJSON);
                    if (jsonResult["error"] != null)
                    {
                        jResu = jsonResult["error"]["message"].ToString();
                    }
                }
            }
            else
            {
                jResu = Resources.CommonAPIError + statuscode;
            }
        }
        catch (Exception ex)
        {
            TelemetryHelper.Trace("API Ex", ex.Message.ToString());
        }
        return jResu;
    }

    #endregion

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM