web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

How to cancel a SalesOrder using WEB API action CancelSalesOrder?

(0) ShareShare
ReportReport
Posted on by 32

How to cancel a SalesOrder using WEB API action CancelSalesOrder

My Code is :

var parameters = {};
var orderclose = {};
orderclose["salesorderid"] = "84fb9b1f-7e5e-ea11-a811-000d3aa087c4"; //Delete if creating new record 
orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.salesorder";
parameters.OrderClose = orderclose;
parameters.Status = 3;

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/CancelSalesOrder", true);
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));

but it return with

{
	"error": {
		"code": "0x80040216",
		"message": "An unexpected error occurred.",
		"innererror": {
			"message": "An unexpected error occurred.",
			"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
			"stacktrace": "   at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext, Dictionary`2 optionalParameters)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Execute(OrganizationRequest request, ExecutionContext executionContext)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.ExecuteOperation(CrmODataExecutionContext context, EdmOperation edmOperation, Dictionary`2 parameters, Dictionary`2 boundParameters)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.ProcessOperationRequest(String operationName, Dictionary`2 operationParameters, EntityReference entityReference, String boundEntityName, String boundEntityType)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.<>c__DisplayClass9_0.b__0()\r\n   at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n   at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
		}
	}
}

I have the same question (0)
  • Verified answer
    cloflyMao Profile Picture
    25,210 on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Hi Flex Xuan,

    1. odata.bind is also required for salesorderid property.

    2. odata.type should equals to Microsoft.Dynamics.CRM.orderclose.

    3. Status reason should equals to 4.

    Try excute code below, I got success from it:

    var parameters = {};
    var orderclose = {};
    orderclose["salesorderid@odata.bind"] = "/salesorders(xxxx)"; //Delete if creating new record 
    orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.orderclose";
    parameters.OrderClose = orderclose;
    parameters.Status = 4;
    
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/CancelSalesOrder", true);
    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) { alert("Ok!!");
                //Success - No Return Data - Do Something
            } else {
                Xrm.Utility.alertDialog(this.response);
            }
        }
    };
    req.send(JSON.stringify(parameters));

    A previous thread which has same issue as yours.

    https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/227813/error-500-when-calling-cancelsalesorder-action-using-webapi-javascript?pifragment-97030=1

    Regards,

    Clofly

  • Suggested answer
    H V Profile Picture
    351 on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Hi,

    Please use below code to cancel sales order:

        var objSalesorder = {};
    	    objSalesorder.statecode = 2;
    	    objSalesorder.statuscode = 4;
    	    var stringJSONSalesOrder = JSON.stringify(objSalesorder);
    	    
    	    var query = Xrm.Utility.getGlobalContext().getClientUrl()   "/api/data/v9.0/salesorders(4a6e9193-337e-ea11-a811-000d3a300e5b)";
        
                var req = new XMLHttpRequest();
                req.open("PATCH", encodeURI(query), true);
                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 || this.status === 200) {
                            alert("success");
                        } else {
                            alert("Error");
                        }
                    }
                };
                req.send(stringJSONSalesOrder);

  • Community Member Profile Picture
    on at
    RE: How to cancel a SalesOrder using WEB API action CancelSalesOrder?

    Query which is being executed is missing the key attributes or having the wrong attributes value as mentioned below.

    • odata.bind is also required for salesorderid property.

    • odata.type should equals to Microsoft.Dynamics.CRM.orderclose.

    • Status reason should equal to 4.

    Once these changes will be done, query will be executed successfully without any error and will cancel the sales order.

    Example:

    var orderclose = {};

    orderclose["salesorderid"] = "84fb9b1f-7e5e-ea11-a811-000d3aa087c4"; //Delete if creating new record

    orderclose["@odata.type"] = "Microsoft.Dynamics.CRM.salesorder";

    parameters.OrderClose = orderclose;

    parameters.Status = 3;

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 228

#2
Tom_Gioielli Profile Picture

Tom_Gioielli 156 Super User 2025 Season 2

#3
MVP-Daniyal Khaleel Profile Picture

MVP-Daniyal Khaleel 149

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans