Send message via Facebook Chat API (XMPP) C#

Magnus Karlsson picture Magnus Karlsson · Oct 25, 2013 · Viewed 9.7k times · Source

OBSERVE https://developers.facebook.com/docs/chat/

The service and API this document covers has been deprecated with the release of Platform API v2.0. Once version 1.0 is deprecated, chat.facebook.com will no longer be available.

Important! Read this and you probably want to do something completely different than anything that has to do with this question.

I'm creating a chat with WebForms C# connecting to Facebook Chat API.

I have also looked at this SO question (and all links). Some parts are no longer relevant since Facebook requires auth_token now.

To replicate this, you should set up a Facebook web app, use the appId and a user account with xmpp_login permission set. Then create a Chat.aspx with code behind and paste this code accordingly. And replace the hard-coded users to interact with.

I have two (maybe three) issues which I believe prevent me from succeeding with my goal to send a chat message.

  1. The process noted as // finishes auth process in the documentation does not match the documentation description (I'm not getting any respones after I have received my SSL/TLS based success message from Facebook.)
  2. I have no idea how the 'send chat message'-part should be set up, and since I don't receive any messages from Facebook its hard to tell what might be wrong.

Here is my code in its entirety, on PasteBin.

I also have some helpers for adding xmpp_login permissions and such.. removed for clarity.

Global variables:

public partial class Chat : Page
{
    public TcpClient client = new TcpClient();
    NetworkStream stream;
    private SslStream ssl;
    private string AppId { get; set; }
    public string AppSecret { get; set; }
    public string AppUrl { get; set; }
    public string UserId { get; set; }
    public string AccessToken { get; set; }
    private string _error = string.Empty;//global error string for watch debugging in VS. 

    public const string FbServer = "chat.facebook.com";
    private const string STREAM_XML = "<stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" xmlns=\"jabber:client\" to=\"chat.facebook.com\" xml:lang=\"en\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">";
    private const string AUTH_XML = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-FACEBOOK-PLATFORM'></auth>";
    private const string CLOSE_XML = "</stream:stream>";
    private const string RESOURCE_XML = "<iq type=\"set\" id=\"3\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>fb_xmpp_script</resource></bind></iq>";
    private const string SESSION_XML = "<iq type=\"set\" id=\"4\" to=\"chat.facebook.com\"><session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/></iq>";
    private const string START_TLS = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>";

Then in Page_Load all the steps required are (or are supposed to be) performed. Worth noting is the SendMessage("test");. I just tried to put it there to see if it would succeed in sending a chat message... SetUserNameAndAuthToken sets my auth token and user name to global variables. The AuthToken works.

protected void Page_Load(object sender, EventArgs e)
{
    this.AppId = "000000082000090";//TODO get from appsettings.
    //AddAdditionalPermissions("xmpp_login");//TODO handle xmpp_login persmission
    this.AppSecret = "d370c1bfec9be6d9accbdf0117f2c495"; //TODO Get appsecret from appsetting.
    this.AppUrl = "https://fbd.anteckna.nu";

    SetUserNameAndAuthToken();

    Connect(FbServer);

    // initiates auth process (using X-FACEBOOK_PLATFORM)
    InitiateAuthProcess(STREAM_XML);

    // starting tls - MANDATORY TO USE OAUTH TOKEN!!!!
    StartTlsConnection(START_TLS);

    // gets decoded challenge from server
    var decoded = GetDecodedChallenge(AUTH_XML);

    // creates the response and signature
    string response = CreateResponse(decoded);

    //send response to server
    SendResponseToServer(response);

    SendMessage("test");

    // finishes auth process
    FinishAuthProcess();

    // we made it!
    string streamresponseEnd = SendWihSsl(CLOSE_XML);

}

So I get a response then I send the response to server:

private void SendResponseToServer(string response)
{
    string xml = String.Format("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">{0}</response>", response);
    string response2 = SendWihSsl2(xml);
    if (!response2.ToLower().Contains("success"))
        _error = response2;
}

This takes 1 minute 40 seconds... and response is:

<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>

Finally I do the FinishAuthPorcess()

private void FinishAuthProcess()
{
    string streamresponse = SendWithSsl(STREAM_XML);
    if (!streamresponse.Contains("STREAM:STREAM"))
        _error = streamresponse;

    string streamresponse2 = SendWihSsl(RESOURCE_XML);
    if (!streamresponse2.Contains("JID"))
        _error = streamresponse2;

    string streamresponse3 = SendWihSsl(SESSION_XML);
    if (!streamresponse3.Contains("SESSION"))
        _error = streamresponse2;
}

All responses are "". Looking at the Read method in SendWithSsl: it's 0 bytes. Trying to send a message also gives me 0 bytes Read data from Facebook. I have no clue as to why?

Answer

Jin Thakur picture Jin Thakur · Mar 7, 2020

There is new api now. How does the Messenger Platform work? When a person sends a message to a business on Messenger and as long as this Page uses an app to partially or fully automate conversations, the following will happen. The Facebook server sends webhooks to the URL of the business server, where the messaging app is hosted. Using the Send API, the app can respond to the person on Messenger. In this way, developers can build guided conversations to lead people through an automated flow or build an app to serve as a bridge between your agents and your business presence on Messenger.

The Messenger Platform does not require any payment to use. It is meant for businesses to handle inquiries from their customers. Once you build your experience for your customers to interact with, you can then leverage Ads to bring people to your experience, like for example Click-to-Messenger Ads or Inbox Ads.

What does a Messenger for Business experience look like? We have a sample eCommerce business that you can chat with on Messenger called Original Coast Clothing.

Chat with Sample Business Here

How do I get started? You can get started by creating a test page and test app that allows you to try your experience within Messenger. We have some examples that can get you started. Once your app is ready to deploy, you can submit it for review. When your app passes our review process, it will be ready to interact with the public.

In order to get started, you will need Messenger, a Facebook Page, and a url where the webhooks to be sent to.

Here is a step-by-step guide to deploy the above experience into your test page to get you started.

Ready to Build? Get Started

https://developers.facebook.com/products/messenger/

https://developers.facebook.com/docs/messenger-platform/reference/send-api/