Created
March 19, 2024 23:06
-
-
Save luishendrix92/4243d1088addbd22b799e2f4a7c8a0e6 to your computer and use it in GitHub Desktop.
Dart - Use the HTTP API for Pusher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:http/http.dart' as http; | |
import 'package:crypto/crypto.dart'; | |
import 'dart:convert'; | |
class Pusher { | |
// Replace -us3 with -YOUR_REGION | |
static String baseUrl = "https://api-us3.pusher.com/apps"; | |
final String appId; | |
final String appKey; | |
final String secret; | |
const Pusher({ | |
required this.appId, | |
required this.appKey, | |
required this.secret, | |
}); | |
String getFullUrl(String channel, String event, String bodyStr) { | |
String timestamp = | |
(DateTime.now().millisecondsSinceEpoch / 1000).round().toString(); | |
String authVersion = "1.0"; | |
var bodyMD5 = md5.convert(utf8.encode(bodyStr)); | |
String signStr = """POST | |
/apps/${this.appId}/events | |
auth_key=${this.appKey}&auth_timestamp=${timestamp}&auth_version=$authVersion&body_md5=${bodyMD5}"""; | |
var authSignature = | |
Hmac(sha256, utf8.encode(this.secret)).convert(utf8.encode(signStr)); | |
return '$baseUrl/${this.appId}/events?body_md5=$bodyMD5&auth_version=1.0&auth_key=${this.appKey}&auth_timestamp=$timestamp&auth_signature=$authSignature'; | |
} | |
Future<int> triggerEvent(String channel, String event, Map data) async { | |
String bodyStr = json.encode({ | |
'name': event, | |
'channel': channel, | |
'data': json.encode(data), | |
}); | |
var uri = Uri.parse(getFullUrl(channel, event, bodyStr)); | |
var response = await http.post( | |
uri, | |
headers: <String, String>{ | |
'Content-Type': 'application/json', | |
}, | |
body: bodyStr, | |
); | |
return response.statusCode; | |
} | |
} | |
void main() async { | |
print("Program started!"); | |
Pusher pusher = Pusher( | |
appId: "YOUR_APP_ID", | |
appKey: "YOUR_APP_KEY", | |
secret: "YOUR_SECRET", | |
); | |
int resCode = await pusher.triggerEvent("CHANNEL", "EVENT_NAME", { | |
'message': 'Hello World', | |
}); | |
print(resCode); // 200 (hopefully) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment