json_decode variables to email - json

I am using btcpayserver with bitpay php api. Trying to implement ipn in payments and send variables to email.
the ipn generates a log file like this:
Raw IPN: {
"id": "KrYtvetS9oQ9s7CDErk,
"url": "https://btcpayserv.net/invoice?id=KrYtvetS9oQ9s7",
"posData": null,
"status": "paid",
"btcPrice": "0.00162327",
"price": 11.99,
"currency": "EUR",
"invoiceTime": 1569570609000,
"expirationTime": 1569571509000,
"currentTime": 1569570697070,
"btcPaid": "0.00162327",
"btcDue": "0.00000000",
"rate": 7386.36657706093,
"exceptionStatus": false,
"buyerFields": {
"buyerEmail": "buyeremail#test.com"
},
"transactionCurrency":
the ipn get data like this in php: $ipn = json_decode($raw_post_data);
php
$ipn = json_decode($raw_post_data);
$invoice = $client->getInvoice($ipn->id);
$invoiceId = $invoice->getId();
$invoiceUrl = $invoice->getUrl();
$invoiceStatus = $invoice->getStatus();
$invoiceExceptionStatus = $invoice->getExceptionStatus();
$invoicePrice = $invoice->getPrice();
$invoiceBtcPrice = $invoice->getbtcPrice();
i could send some fields like this via php mail:
$message = 'Date:' . $date . ', ID: ' . $invoiceId . ', Status: ' . $invoiceStatus . ', Url: ' . $invoiceUrl . ', BTC Price: ' . $invoiceBtcPrice . ', Price: ' . $invoicePrice;
but i will like to send this variable of the RAW IPN: "buyerEmail": "buyeremail#test.com"
can not make it.

Related

Perl LWP::UserAgent parse response JSON

I am using the LWP::UserAgent module to issue a GET request to one of our APIs.
#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
use Data::Dumper;
my $ua = LWP::UserAgent->new;
my $request = $ua->get("http://example.com/foo", Authorization => "Bearer abc123", Accept => "application/json" );
print Dumper $request->content;
The request is successful. Dumper returns the following JSON.
$VAR1 = '{
"apiVersion": "v1",
"data": {
"ca-bundle.crt": "-----BEGIN CERTIFICATE-----abc123-----END CERTIFICATE-----\\n"
},
"kind": "ConfigMap",
"metadata": {
"creationTimestamp": "2021-07-16T17:13:01Z",
"labels": {
"auth.openshift.io/managed-certificate-type": "ca-bundle"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:data": {
".": {},
"f:ca-bundle.crt": {}
},
"f:metadata": {
"f:labels": {
".": {},
"f:auth.openshift.io/managed-certificate-type": {}
}
}
},
"manager": "cluster-kube-apiserver-operator",
"operation": "Update",
"time": "2021-09-14T17:07:39Z"
}
],
"name": "kube-control-plane-signer-ca",
"namespace": "openshift-kube-apiserver-operator",
"resourceVersion": "65461225",
"selfLink": "/api/v1/namespaces/openshift-kube-apiserver-operator/configmaps/kube-control-plane-signer-ca",
"uid": "f9aea067-1234-5678-9101-9d4073f5ae53"
}
}';
Let's say I want to print the value of the apiVersion key, which should print v1.
print "API Version = $request->content->{'apiVersion'} \n";
The following is being printed. I am not sure how to print the value v1. Since HTTP::Response is included in the output, I suspect I might have to use the HTTP::Response module?
API Version = HTTP::Response=HASH(0x2dffe80)->content->{'apiVersion'}
Perl doesn't expand subroutine calls in a double-quoted string.
print "API Version = $request->content->{'apiVersion'} \n";
In this line of code, content() is a subroutine call. So Perl sees this as:
print "API Version = $request" . "->content->{'apiVersion'} \n";
And if you try to print most Perl objects, you'll get the hash reference along with the name of the class - hence HTTP::Response=HASH(0x2dffe80).
You might think that you just need to break up your print() statement like this:
print 'API Version = ', $request->content->{'apiVersion'}, "\n";
But that's not going to work either. $request->content doesn't return a Perl data structure, it returns a JSON-encoded string. You need to decode it into a data structure before you can access the individual elements.
use JSON;
print 'API Version = ', decode_json($request->content)->{'apiVersion'}, "\n";
But it might be cleaner to do the decoding outside of the print() statement.
use JSON;
my $data = decode_json($request->content);
In which case you can go back to something more like your original code:
print "API Version = $data->{'apiVersion'} \n";
The JSON content must be decoded first. There are several modules for that, like JSON:
use JSON;
# ...
my $href = decode_json $request->content;
And then use it like a normal hash reference: $href->{apiVersion}

Jira Api: Why is description being merged with summary, when creating a new issue?

I'm creating a Powershell script for monitoring disk space and creating issues on Jira, with how much disk space is left.
I can't seem to figure out how to separate my summary and my description. They are "merged" together, and are both being passed into the summary when the issue is created.
I'm guessing that the formatting of my JSON body might just be off, but I can't seem to figure out what I've done wrong.
The body i'm sending is looking like this:
$body =
'{
"fields":
{
"project":
{
"key": "' + $projectKey + '"
},
"issuetype":
{
"name": "' + $issueType + '"
},
"summary": "' + $summary + '",
"description": "' + $description + '",
"priority":
{
"id": "' + $priority + '"
}
}
}';
summary and description looks like this:
$description = "{0}% space is available on the {1} drive. {2} of {3} GB of space is available." -f [math]::truncate($diskSpace), $drive, [math]::truncate($currentDrive.FreeSpace / 1gb), [math]::truncate($currentDrive.Size / 1gb);
$summary = "There is plenty of space left on the {0} drive" -f , $drive;
The issue wasn't the JSON, but the way I called my function, which was responsible for creating the Jira.
I changed it from this:
CreateJira($summary, $description)
To This:
CreateJira $summary, $description

How can i fix my json output?

I have an issue to decode the json that i receive from CURL,
i used json_last_error to see what may be the reason and it looks like my json is malformed.
// Make the REST call, returning the result
$response = curl_exec($this->curl); // result is as per screenshot below
$resp_json = json_decode($response, true);
echo "<pre>";
print_r($resp_json); // display nothing
echo "</pre>";
Click here to see the json output and the issue
from jsonlint, response is like...
{
"RESPONSE_DATA": [{
"property_address": "6\/192 Kingsgrove Road",
"price": 0.0,
"contact_name": "Nicholas Smith",
"property_facing_direction": "unknown",
"agent_name": "",
"client_id": 46984,
"property_suburb": "Kingsgrove",
"agent_phone": "",
"contact_phone": "0407 787 288",
"ordered_datetime": "2017-12-05 04:15:03",
"agent_email": "",
"property_state": "NSW",
"job_id": 2324,
"im_job_id": "40432-o",
"product_ids": 3000000,
"confirmed_datetime": "",
"photographer_comment": "Photography Premium Daylight 3 photos $145.00\
nAdd Per Premium Photo 2 at $20 .00 each\ n Total $185 .00 ","
contact_company ":"
Raine & Horne Commerical - Marrickville ","
agent_id ":"
","
preferred_datetime ":"
2017 - 12 - 07 11: 00: 00 ","
property_postcode ":0000,"
status_code ":"
N "}],"
RESPONSE_MESSAGE ":"
OK ","
RESPONSE_CODE ":200}
There are 4 issues broking the json:
Unexpected newline
\n in photographer_comment
\ n in photographer_comment
property_postcode ":0000
That you can hardcode to replace it by:
$json = trim(preg_replace('/\s+/', ' ', $json));
$json = str_replace("\\n", "", $json);
$json = str_replace("\\ n", "", $json);
$json = str_replace(":0000", ":\"0000\"", $json);
It's quick and dirty, and not covering other cases; you can try regex if you want to use a more general way. But I think it would be more reasonable to fix it at the data provider side.
Besides above, some keys' name are not good due to the tailing empty space, such as: "preferred_datetime "

Invalid payload - Slack API JSON

I am using a Groovy script to send a POST using the Slack API, at present I am getting invalid_payload returned and I think this is most likely due to the formatting of my JSON. I know the Slack API expects it JSON with double quotes but I can't seem to be able to pass a variable into the JSON object:
SUCCESS_MESSAGE = '{"attachments": [{"color": "#2A9B3A", "author_name": ${DEV_NAME}, "title": "Build Status", "title_link": ${BUILD_URL}, "text": "Successful Build" }]}'
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "${SUCCESS_MESSAGE}", "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text
How should I correctly format my SUCCESS_MESSAGE var so I don't get the error?
You need to quote your DEV_NAME and BUILD_URL variable expansions so the JSON string is valid.
Your whole string needs to be enclosed in " instead of ' so the variables are actually expanded
And you need to escape the " inside your string so they appear in your JSON string.
SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`
Alternatively you can generate the JSON in much nicer programmatic way. Which would be helpful if your notifications got a bit more complicated:
def notification = [
attachments: [
[
color: "#2A9B3A",
author_name: DEV_NAME,
title: "Build Status",
title_link: BUILD_URL,
text: "Successful Build"
]
]
]
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", JsonOutput.toJson(notification), "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text

NGINX log filter $upstream_response_time JSON ELK "-" parsefailure

I have my NGINX logs formated as JSON:
log_format le_json '{ "#timestamp": "$time_iso8601", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"body_bytes_sent": "$body_bytes_sent", '
'"status": $status, '
'"request": "$request", '
'"request_method": "$request_method", '
'"response_time": $upstream_response_time, '
'"http_referrer": "$http_referer", '
'"http_user_agent": "$http_user_agent" }';
My log gets picked up by filebeat and sent to Logstash that have the following config:
input {
beats {
port => 5044
codec => "json"
}
}
filter {
geoip {
database => "C:/GeoLiteCity.dat"
source => "[remote_addr]"
}
}
output {
elasticsearch {
template => "C:/ELK/logstash-2.2.2/templates/elasticsearch-template.json"
template_overwrite => true
hosts => ["127.0.0.1"]
index => "%{[#metadata][beat]}-%{+YYYY.MM.dd}"
document_type => "%{[#metadata][type]}"
}
}
The problem i'm having is $upstream_response_time. When there is no response time NGINX puts an '-' on this post. As you can see i don't put "" around $upstream_response_time because i want it as a number so i can perform calculations with this in Kibana and display. When '-' is sent i get a jsonparsefailure in Logstash because it is not a number.
I would like to set all the '-' to 0. What would be the best way to do this?
I've had no success with trying to filter it in nginx-config. I think it needs to be done prior to getting shipped to Logstash because that's where the parsefailure occurs.
Any ideas?
Try this:
map $upstream_response_time $temprt {
default $upstream_response_time;
"" 0;
}
$upstream_response_time either a number or unset. Nginx logs unset variables as dash (-), but map treats them as empty strings.
A fleshed out example from #AlexeyTen using null instead of 0 to differentiate from real values since I wasn't 100% sure how to use mapped variables:
map $upstream_response_time $temprt {
default $upstream_response_time;
"" null;
}
log_format le_json '{ "#timestamp": "$time_iso8601", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"body_bytes_sent": "$body_bytes_sent", '
'"status": $status, '
'"request": "$request", '
'"request_method": "$request_method", '
'"response_time": $temprt, '
'"http_referrer": "$http_referer", '
'"http_user_agent": "$http_user_agent" }';