Segment.io HTTP API not collecting events - httprequest

The documentation and help for this particular Segment.io is limited and sparse, so I hope it's OK to ask in here.
I have just set up a Segment.io workspace and a HTTP API source
Per the docs, I sent some POST requests (with Postman) to the https://api.segment.io/v1/track and https://api.segment.io/v1/page endpoints. The requests were structured like this:
curl -X POST \
https://api.segment.io/v1/track \
-H 'Accept: */*' \
-H 'Authorization: My4w3s0m3k3y' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Type: application/json' \
-H 'Host: api.segment.io' \
-H 'Postman-Token: 474d7fbe-15af-43d2-b629-61e15945e662,2c3d5fbe-2c09-4fe6-b7ea-a04e3221201b' \
-H 'User-Agent: PostmanRuntime/7.11.0' \
-H 'accept-encoding: gzip, deflate' \
-H 'cache-control: no-cache' \
-H 'content-length: 117' \
-d '{
"userId": "abc123",
"event": "My tests",
"properties": {
"name": "test 1"
}
}'
which all returned a 200 response and the following message:
{
"success": true
}
However, when I got to my dashboard, no events have been recorded.
The debugger is also empty
What am I missing here?

It looks like your write key isn't base64 encoded. When you encode your write key, remember to add the : at the end of it, before it's encoded.
Also, for the Authorization key:value, be sure to add Basic before the encoded write key. So your Authorization key:value would look like:
Authorization: Basic {encoded write key}
An example from the segment documentation:
In practice that means taking a Segment source Write Key,'abc123', as the username, adding a colon, and then the password field is left empty. After base64 encoding 'abc123:' becomes 'YWJjMTIzOg=='; and this is passed in the authorization header like so: 'Authorization: Basic YWJjMTIzOg=='.

I have been dealing with the same issue.
I found the solution as Todd said.
You should add a header Authorization: Basic + base64 encoding write key.
So, you look for the Segment source setting and get the write key.
After that, i have used an online base64 encoding tool to encode my write key.
Finally, you should add this header (Authorization) with 'Basic' and the encoded write key.
You should be able to see the tracked event in the Debugging panel in Segment web page.
I hope this helps!

You can try this code
const { promisify } = require("util");
var Analytics = require("analytics-node");
var analytics = new Analytics("xxxxxxxxxxxxxxxxxxxxxxx", {
flushAt: 1,
});
const [identify, track] = [
analytics.identify.bind(analytics),
analytics.track.bind(analytics),
].map(promisify);
console.log("user id: ", req.body.event.app_user_id);
let app_user_id = req.body.event.app_user_id;
let period_type = req.body.event.period_type;
let expiration_at_ms = req.body.event.expiration_at_ms;
let ret = "Initial";
try {
await identify({
userId: app_user_id,
traits: {
period_type: period_type,
expiration_at_ms: expiration_at_ms,
},
});
ret = "Done : Sengment done";
} catch (err) {
console.log("err: ", err);
ret = "Error : " + err;
}
return {
rafsan: ret,
};

Try to clear your browser's cache or use a different browser. I had the same problem and worked for me.
Hope this helps.

Related

Is it possible to use curl/json with tcl and retrieve spotify API data?

I'm trying to make a simple proc in TCL that gets data from SPOTIFY API about what track I'm currently playing.
Any ideas are welcome. :D
Format:
GET https://api.spotify.com/v1/me/player/currently-playing
I need to send this:
curl -X "GET" "https://api.spotify.com/v1/me/player/currently-playing?market=ES&additional_types=episode" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer BQAai*****8n-5zXrLypj********hsgafd"
(id code for auth masked)
Reference: https://developer.spotify.com/documentation/web-api/reference/
This is a variant of Donald's solution using Tcl's built-in http support:
package require http;
package require json;
package require tls
::http::register https 443 ::tls::socket
set spotifyToken "BQAai*****8n-5zXrLypj********hsgafd"
proc spotifyGet {api args} {
global spotifyToken;
set url https://api.spotify.com/v1/$api?[http::formatQuery {*}$args]
dict set hdrs Authorization [list Bearer $spotifyToken]
dict set hdrs Accept "application/json"
set token [http::geturl $url \
-type "application/json" \
-headers $hdrs]
if {[http::status $token] eq "ok"} {
set responseBody [http::data $token]
} else {
error "Spotify call failed: [http::error $token]"
}
http::cleanup $token
return [json::json2dict $responseBody]
}
set data [spotifyGet me/player/currently-playing market ES additional_types episode]
Not so complicated, after all, but requires an additional dependency: TclTLS.
As a first cut, here's a very simple wrapper:
proc curl args {
# The options skip showing stuff you don't want in scripted form
# They also enable following redirects; you probably want to do that!
exec curl -s -S -L {*}$args
}
# Usually easiest to keep this sort of thing separate
set spotifyToken "BQAai*****8n-5zXrLypj********hsgafd"
# -G to force the use of the GET verb
set json [curl -G "https://api.spotify.com/v1/me/player/currently-playing?market=ES&additional_types=episode" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer $spotifyToken"]
We can wrap that further:
package require http; # Standard part of Tcl
package require json; # Part of tcllib
proc spotifyGet {api args} {
global spotifyToken; # Assume variable set as earlier
set url https://api.spotify.com/v1/$api?[http::formatQuery {*}$args]
set options {-H "Accept: application/json" -H "Content-Type: application/json"}
lappend options -H "Authorization: Bearer $spotifyToken"
return [json::json2dict [curl -G $url {*}$options]]
}
set data [spotifyGet me/player/currently-playing market ES additional_types episode]
puts [dict get $data item name]
If you're doing more serious JSON work, consider using the rl_json library. And you'll need to explore the data you get back to understand it. (I can't test; I don't use Spotify.)

How do you specify the sourceBranch for a Run of Pipelines via the REST API?

I've been trying to run a pipeline for a particular branch of the repository I'm using.
In the UI, there is a convenient option, but I don't understand what to try in the request.
No matter what I do I always run from master.
How do I change that? I tried filling out the repository parameters but to no avail: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run%20pipeline?view=azure-devops-rest-6.0#repositoryresourceparameters
Here is an example request:
curl --location --request POST 'https://dev.azure.com/<redacted>/<redacted>/_apis/pipelines/<redacted>/runs?api-version=6.0-preview.1' \
--header 'Authorization: Basic <redacted>' \
--header 'Content-Type: application/json' \
--header 'Cookie: VstsSession=<redacted>' \
--data-raw '{
"previewRun": true,
"resources": {
"repositories": {
"refName": "refs/heads/<redacted>"
}
},
"runParameters":
{
"namespace" : "<redacted>",
"image" : "<redacted>",
"tag" : "<redacted>",
"package" : "<redacted>",
"version" : "8.4.4"
}
}'
From your screenshot, it seems that you are using the YAML pipeline.
I have tested your example , and the root cause of this issue is that the request body(data-raw) has some issues.
You could try my sample
curl --location --request POST 'https://dev.azure.com/<redacted>/<redacted>/_apis/pipelines/<redacted>/runs?api-version=6.0-preview.1' \
--header 'Authorization: Basic <redacted>' \
--header 'Content-Type: application/json' \
--header 'Cookie: VstsSession=<redacted>' \
--data-raw '{
"stagesToSkip":[],
"resources":
{
"repositories":
{
"self":{"refName":"refs/heads/{Branchname}"}
}
},
"templateParameters":
{
"namespace":"{value}",
"image":"{value}",
"tag":"{value}",
"package":"{value}",
"version":"{value}"
},
"variables":{}
}'
Result:
For Http Request (you can test it with Postman)
1. Get pipeline api url like this
https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=7.1-preview.1
Source: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run-pipeline?view=azure-devops-rest-7.1
Fill in your organization, project and pipelineId.
(all of this can be found in the link when you open your pipeline definition in Azure DevOps)
2. Add Basic Auth headers
key: Authorization, value:"Basic [your azure Person Access Token from Azure Dev Ops with Access to Pipeline goes here]"
Should look like this
"Basic OndzNWdz43FKfjdi98hjKDJFH8kkg9854HJKHF9D8RFEHui4387lkNXE="
And set content type to application/json
like this
key: Content-Type, value: application/json
3. Put this JSON Into Raw Body
{
"templateParameters":{
"inputName":"johnsmith"
},
"resources":{
"repositories":{
"self":{
"refName":"refs/heads/feature/#JIRATask01_Blabla"
}
}
},
"variables":{
}
}
Replace refName value with branch you want to run the pipeline for.
If you have multiple repo pipeline look into this topic (but i haven't tested that solution):
Azure DevOps API to Trigger Multi Repo changing branches

Http POST works in Postman but not in Flutter

I am trying to do a POST request on my flutter application using the Http package. I tested my request first on the Api sandbox website, and then in Postman. It works well there, but once in Flutter, I always get a 400 Bad Request.
Here is my code in Flutter:
import 'package:http/http.dart';
import 'package:uuid/uuid.dart';
import 'package:wave_app/env/secrets.dart';
import 'package:wave_app/models/momo_token.dart';
String url = "https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay";
var uuid = Uuid();
String requestId = uuid.v4();
MomoToken token = await _createMomoNewTokenCollection();
String auth = "Bearer " + token.accessToken;
Map<String, String> headers = {
"Authorization": auth,
"X-Target-Environment": "sandbox",
"X-Reference-Id": requestId,
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": momoCollectionSubscriptionKey
};
String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';
Response response = await post(url, headers: headers, body: jsonBody);
int statusCode = response.statusCode;
print("STATUS CODE REQUEST TO PAY " + statusCode.toString());
print(response.reasonPhrase.toString());
print(response.body.toString());
if (statusCode == 202) {
return response.body.toString();
} else {
return null;
}
}
The api doc is here: https://momodeveloper.mtn.com/docs/services/collection/operations/requesttopay-POST?
And here is the code in curl of my Postman request (using the same variable above requestId, auth, momoCollectionSubscriptionKey)
curl --request POST \
--url https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay \
--header 'Accept: */*' \
--header 'Accept-Encoding: gzip, deflate' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSMjU2In0.eyJjbGllbnRJZCI6IjFmY2MzMjBhLTM0NWQtMTFlYS04NTBkLTJlNzI4Y2U4ODEyNSIsImV4cGlyZXMiOiIyMDIwLTAxLTExVDE1OjU3OjE4Ljc3NyIsInNlc3Npb25JZCI6ImZmYzc1OGE2LTM2MWEtNDM4ZS1hYjE5LWQ1ZGQ4ZmU4ZjEyOSJ9.DeoJyU6Hb0he_or1XeBxW-6s-xwdtmi0cUrYjQe0Z796bIGvvT-VJ214JaZItG-CBQpgv7dHbLfXNqr8D05Q7U9XiOtpr8mtYWQlY-MseGIHAyxp1qBuQkwjmBYBlDxQOYYfzG9SZ8tGFUI1_k59LMNYIhDlXXKa68Ym1sylZ8wfWjGuHaKVzMEH25ubiBwCLev5IHPchuF3toVP99U-HC8t95E3zrEt9dHgzn0hnwvpB31wcsu_b3vb-YZ1idHgosPc2GmKFsDruX14VniKBicCsnGHqZAkSPXwaOR6SIn4JZEEwhAIj3Oe2H5dwxloiX5rzaApdkwEg6KSoBXk8A' \
--header 'Cache-Control: no-cache' \
--header 'Connection: keep-alive' \
--header 'Content-Length: 194' \
--header 'Content-Type: application/json' \
--header 'Host: sandbox.momodeveloper.mtn.com' \
--header 'Ocp-Apim-Subscription-Key: 281eb****************' \
--header 'Postman-Token: ece19062-1f0b-4873-a3ed-1bd4ada8746a,528004b2-410d-4653-9909-5197a3dc95db' \
--header 'User-Agent: PostmanRuntime/7.20.1' \
--header 'X-Reference-Id: 062f8aad-f529-4d0a-804c-affb888c2b8b' \
--header 'X-Target-Environment: sandbox' \
--header 'cache-control: no-cache' \
--data '{\r\n "amount": "5",\r\n "currency": "EUR",\r\n "externalId": "123",\r\n "payer": {\r\n "partyIdType": "MSISDN",\r\n "partyId": "46733123454"\r\n },\r\n "payerMessage": "hi",\r\n "payeeNote": "hi"\r\n}'
On postman and their website, I always get a 202 Accepted response.
I am not sure, what I'm doing wrong here. Any help would be greatly appreciated!
------------ EDIT -------------------
I also tried with HttpClient, here is the code, but still got 400 Bad Request
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set("Authorization", "Bearer " + token.accessToken);
request.headers.set('content-type', 'application/json');
request.headers.set("X-Target-Environment", "sandbox");
request.headers.set("X-Reference-Id", requestId);
request.headers.set("Ocp-Apim-Subscription-Key", momoCollectionSubscriptionKey);
request.add(utf8.encode(jsonBody));
HttpClientResponse response = await request.close();
print("STATUS CODE " + response.statusCode.toString() + " " + response.reasonPhrase);
String reply = await response.transform(utf8.decoder).join();
print("REPLY " + reply);
httpClient.close();
This is definitely a problem with the server. The two headers X-Reference-Id and X-Target-Environment are being handled case sensitively by the server (i.e. it is not in compliance with the RFC).
It's Dart's io.HttpClient that forces headers to lower case, so this affects package:http and package:dio which both rely on it. There's a request to allow the client to preserve the case of headers but it's coming slowly as it's a breaking change.
In the meantime, try using this fork of the client which preserves header case. https://pub.dev/packages/alt_http/
Solved same issue by changing jsonBody from String into Map.
String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';
Only solved when changed from String -> Map;
Map jsonBody = {"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"};
and additionally, included the jsonEncode
Response response = await post(url, headers: headers, body: jsonEncode(jsonBody));
jsonEncode requires the import of Convert library
import 'dart:convert';

How i can send message to individual Line User?

I want to send message to private user not in any bot or group. How i can send ?
Thanks in advance
Line have API to send to one private user.
curl -v -X POST https://api.line.me/v2/bot/message/push \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer {channel access token}' \
-d '{
"to": "U4af4980629...",
"messages":[
{
"type":"text",
"text":"Hello, world1"
},
{
"type":"text",
"text":"Hello, world2"
}
]
}'
See the documentation: https://developers.line.biz/en/reference/messaging-api/#send-push-message

paypal authentication failure in sandbox

I encounter an issue when I try to use the Paypal sandbox API.
I've created my 2 sandbox accounts (the facilitator and the buyer), and I've created my app to get the credentials.
Then, I use the curl example provided by Paypal to get a token :
curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "my-client-id:my-secret" \
-d "grant_type=client_credentials"
I get a 200 response, with an "access_token".
Then, I use this access token to get another resource, for example :
curl -v -X GET https://api.sandbox.paypal.com/v1/invoicing/invoices?page=3&page_size=4&total_count_required=true \
-H "Content-Type: application/json" \
-H "Authorization: Bearer the-token-received-above"
Then, I get a 401 error :
{
"name":"AUTHENTICATION_FAILURE",
"message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.",
"links":[{
"href":"https://developer.paypal.com/docs/api/overview/#error",
"rel":"information_link"
}]
}
I don't understand what I'm doing wrong, since I've followed every step decribed in the Paypal doc (at least, I think I have... probably not)
Thanks for your help
curl -v -X GET "https://api.sandbox.paypal.com/v1/invoicing/invoices?page=3&page_size=4&total_count_required=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer the-token-received-above"
Actually had this exact same issue but didn't know what was wrong with my curl. For me, the issue was I forgot to put "Bearer" in the Authorization section.
For this, you are required to wrap the URL with quotation marks.
After get access_token. Please try this
try {
$params = array('access_token' => $jsonResponse->access_token);
$userInfo = OpenIdUserinfo::getUserinfo($params, $this->_api_context);
} catch (Exception $ex) {
ResultPrinter::printError("User Information", "User Info", null, $params, $ex);
exit(1);
}
ResultPrinter::printResult("User Information", "User Info", $userInfo->getUserId(), $params, $userInfo);
Don't forget to add
use PayPal\Api\OpenIdTokeninfo;
use PayPal\Api\OpenIdUserinfo;
That's worked for me.