// © أنظمة ذكاء الأعمال (مِرسال). جميع الحقوق محفوظة. مرخّصة للاستخدام مع منصة مِرسال فقط. // WhatsApp Gateway — C# client (.NET Framework 4.6.1+ / .NET 6/8). Requires Newtonsoft.Json. // // طريقتين للربط: // 1) GatewayClient : لكل عميل رابط خدمة + اسم مستخدم + كلمة سر (نفس طريقة نظامك) // 2) PartnerClient : مفتاح API واحد للشركة، تضيف فيه عملاءك وتعرض رمز الربط داخل نظامك // // التوثيق الكامل: https://<الدومين>/developers using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace WhatsAppGateway { public class SendResult { public string number { get; set; } public string status { get; set; } // sent | failed public long? messageId { get; set; } public string id { get; set; } public string error { get; set; } } public class SendResponse { public bool success { get; set; } public string error { get; set; } // سبب الفشل (في GatewayClient: "true"/"false" للتوافق) public string message { get; set; } public int sent { get; set; } public int failed { get; set; } public SendResult[] results { get; set; } public int httpStatus { get; set; } } internal static class Shared { public static readonly HttpClient Http = new HttpClient { Timeout = TimeSpan.FromMinutes(3) }; public static object TextBody(string number, string message) => new { data = new { type = "text", message, numbers = new[] { number.Trim() } } }; public static object FileBody(string number, byte[] bytes, string fileName, string caption) => new { data = new { type = "file", message = caption, numbers = new[] { number.Trim() }, file = Convert.ToBase64String(bytes), filename = fileName } }; public static async Task Send(HttpMethod method, string url, AuthenticationHeaderValue auth, object body, string idempotencyKey = null) where T : class { using (var req = new HttpRequestMessage(method, url)) { req.Headers.Authorization = auth; if (!string.IsNullOrWhiteSpace(idempotencyKey)) req.Headers.Add("Idempotency-Key", idempotencyKey); if (body != null) req.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); using (var res = await Http.SendAsync(req)) { var text = await res.Content.ReadAsStringAsync(); T result = null; try { result = JsonConvert.DeserializeObject(text); } catch (JsonException) { } if (result is SendResponse sr) sr.httpStatus = (int)res.StatusCode; if (result == null && typeof(T) == typeof(JObject)) result = new JObject { ["success"] = false, ["error"] = $"HTTP {(int)res.StatusCode}" } as T; return result; } } } } /// الطريقة 1: بيانات العميل (رابط خدمة الرسائل + اسم المستخدم + كلمة السر) public class GatewayClient { private readonly string _serviceUrl; // مثال: https://sendmrsal.com/api/Agent_Client_/PostData private readonly string _baseUrl; private readonly AuthenticationHeaderValue _auth; public GatewayClient(string serviceUrl, string userName, string password) { _serviceUrl = serviceUrl.Trim(); _baseUrl = _serviceUrl.Substring(0, _serviceUrl.IndexOf("/api/", StringComparison.OrdinalIgnoreCase)); _auth = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName.Trim()}:{password.Trim()}"))); } public async Task SendText(string number, string message, string idempotencyKey = null) { try { return await Shared.Send(HttpMethod.Post, _serviceUrl, _auth, Shared.TextBody(number, message), idempotencyKey) ?? Fail("Empty response"); } catch (Exception ex) { return Fail(ex.Message); } } /// رقم الفاتورة مثلاً: لو انعاد الطلب خلال 24 ساعة ما تنرسل مرتين public async Task SendFile(string number, byte[] fileBytes, string fileName, string caption = null, string idempotencyKey = null) { try { return await Shared.Send(HttpMethod.Post, _serviceUrl, _auth, Shared.FileBody(number, fileBytes, fileName, caption), idempotencyKey) ?? Fail("Empty response"); } catch (Exception ex) { return Fail(ex.Message); } } public Task SendFile(string number, string filePath, string caption = null, string idempotencyKey = null) => SendFile(number, File.ReadAllBytes(filePath), Path.GetFileName(filePath), caption, idempotencyKey); /// حالة الرقم: connected | qr | connecting | disconnected public Task GetStatus() => Shared.Send(HttpMethod.Get, _baseUrl + "/api/status", _auth, null); /// حالة رسالة: sent | delivered | read | failed public Task GetMessage(long messageId) => Shared.Send(HttpMethod.Get, _baseUrl + "/api/messages/" + messageId, _auth, null); private static SendResponse Fail(string msg) => new SendResponse { success = false, error = "true", message = msg }; } /// الطريقة 2: مفتاح API للشركة (تدير كل عملائك) public class PartnerClient { private readonly string _api; // https://sendmrsal.com/api/v1/partner private readonly AuthenticationHeaderValue _auth; public PartnerClient(string baseUrl, string apiKey) { _api = baseUrl.Trim().TrimEnd('/') + "/api/v1/partner"; _auth = new AuthenticationHeaderValue("Bearer", apiKey.Trim()); } // customerId: رقم العميل في المنصة، أو "ext:" + رقمه في نظامك (مثال: "ext:C-100") private string C(string customerId) => _api + "/customers/" + Uri.EscapeDataString(customerId).Replace("%3A", ":"); public Task Me() => Shared.Send(HttpMethod.Get, _api + "/me", _auth, null); public Task ListCustomers() => Shared.Send(HttpMethod.Get, _api + "/customers", _auth, null); public Task Plans() => Shared.Send(HttpMethod.Get, _api + "/plans", _auth, null); /// تفعيل أو تجديد اشتراك العميل. planId من Plans()، و days اختياري (الافتراضي مدة الباقة) public Task Renew(string customerId, string planId = null, int? days = null) => Shared.Send(HttpMethod.Post, C(customerId) + "/renew", _auth, new { planId, days }); /// يرجع customer و credentials (رابط الخدمة واسم المستخدم وكلمة السر — احفظها، كلمة السر ما تطلع مرة ثانية) public Task CreateCustomer(string name, string externalId = null, string contactPhone = null, string webhookUrl = null) => Shared.Send(HttpMethod.Post, _api + "/customers", _auth, new { name, externalId, contactPhone, webhookUrl }); public Task GetCustomer(string customerId) => Shared.Send(HttpMethod.Get, C(customerId), _auth, null); public Task UpdateCustomer(string customerId, object changes) => Shared.Send(new HttpMethod("PATCH"), C(customerId), _auth, changes); public Task DeleteCustomer(string customerId) => Shared.Send(HttpMethod.Delete, C(customerId), _auth, null); public Task ResetPassword(string customerId) => Shared.Send(HttpMethod.Post, C(customerId) + "/password", _auth, new { }); /// يبدأ الربط. بعدها نادِ GetConnection كل 2-3 ثواني واعرض connection.qr (صورة data:image/png) لين status = connected public Task Connect(string customerId) => Shared.Send(HttpMethod.Post, C(customerId) + "/connect", _auth, new { }); /// ربط بكود بدل مسح الرمز: يرجع connection.pairingCode public Task ConnectWithCode(string customerId, string phone) => Shared.Send(HttpMethod.Post, C(customerId) + "/connect", _auth, new { method = "code", phone }); public Task GetConnection(string customerId) => Shared.Send(HttpMethod.Get, C(customerId) + "/connection", _auth, null); /// رابط صفحة ربط جاهزة ترسله للعميل (صالح 24 ساعة) public Task CreateLink(string customerId) => Shared.Send(HttpMethod.Post, C(customerId) + "/link", _auth, new { }); public Task Disconnect(string customerId) => Shared.Send(HttpMethod.Post, C(customerId) + "/disconnect", _auth, new { }); public Task SendText(string customerId, string number, string message, string idempotencyKey = null) => Shared.Send(HttpMethod.Post, C(customerId) + "/send", _auth, Shared.TextBody(number, message), idempotencyKey); public Task SendFile(string customerId, string number, byte[] fileBytes, string fileName, string caption = null, string idempotencyKey = null) => Shared.Send(HttpMethod.Post, C(customerId) + "/send", _auth, Shared.FileBody(number, fileBytes, fileName, caption), idempotencyKey); public Task ListMessages(string customerId, int limit = 50) => Shared.Send(HttpMethod.Get, C(customerId) + "/messages?limit=" + limit, _auth, null); public Task GetMessage(string customerId, long messageId) => Shared.Send(HttpMethod.Get, C(customerId) + "/messages/" + messageId, _auth, null); } public static class Webhooks { /// تحقق من توقيع الـ Webhook: الهيدر X-Signature = "sha256=" + HMAC-SHA256(الجسم الخام, السر) public static bool Verify(string rawBody, string signatureHeader, string secret) { if (string.IsNullOrEmpty(signatureHeader) || string.IsNullOrEmpty(secret)) return false; using (var h = new HMACSHA256(Encoding.UTF8.GetBytes(secret))) { var expected = "sha256=" + BitConverter.ToString(h.ComputeHash(Encoding.UTF8.GetBytes(rawBody))).Replace("-", "").ToLowerInvariant(); if (expected.Length != signatureHeader.Length) return false; var diff = 0; for (var i = 0; i < expected.Length; i++) diff |= expected[i] ^ signatureHeader[i]; return diff == 0; } } } }