Pass data from curl to view on codeigniter - php

I have a json data from the curl, then I want to send it to a view in codeigniter but when I display it appears an error "illegal string offset".
json data:
{
"ProgramId": "29aee327-cd89-48c0-b79f-69a0e2b03709",
"ProgramName": "Microsoft CSP",
"CountryFullName": "Indonesia",
"CurrencyCode": "IDR",
"ProductGroups": [
{
"GroupName": "Microsoft 365",
"Products": [
{
"ProductId": "3451a3b0-8cda-44a7-bad7-c30be81c4aaa",
"ProductName": "Microsoft 365 F1",
"ProductGroup": "Microsoft 365",
"ProductSku": "3451A3B0-8CDA-44A7-BAD7-C30BE81C4AAA",
"Price": 0,
"MinQty": 1,
"MaxQty": 10000000,
"Qty": 0,
"UnitPrice": 132300,
"ProductUnit": "Licenses",
"RetailPrice": 147000,
"CommitmentValue": null,
"TieredProductSku": null,
"ProductType": "NON-SPECIFIC",
"ProductDescription": "Designed to meet the needs of firstline workers in your organization. Offers best-in-class productivity across devices while providing IT with security and control.",
"ProductShortDescription": null,
"ProductRestrictions": null,
"IsTrialProduct": false,
"BillingCycleDuration": 1
}
],
"IsExpanded": true,
"Order": -10
}
then I retrieve the data from a controller to be sent to the display, here I use the file_get_contents function
public function index()
{
$this->template->add_includes('js', 'assets/js/holder.js');
$init = "";
$this->template->add_init($init);
// GET data
$source = base_url().'api/products/'.$this->tenantId;
$content = file_get_contents($source);
$result = json_decode($content, true);
//print_r($result); exit;
$data['products']=$result;
$this->template->load('templates/Template', 'Demo',$data);
}

Related

Parsing Request, PHP/Laravel

This API is used by an access control device to report personnel pass-through records, After me (A third-party platform) called the API to a face recognition terminal or face recognition access control terminal.
Calling direction:
A face recognition terminal or face recognition access control terminal calls the API to a third-party platform.
Request description:
Request method: POST
Request URL: /LAPI/V1.0/System/Event/Notification/PersonVerification
Content-Type: text/plain
Request example:
{
"Reference": "204.2.1.20:5118/LAPI/V1.0/System/Event/Subscription/0",
"Seq": 5,
"DeviceCode": "210235C3R13202000093",
"Timestamp": 1564735558,
"NotificationType": 1,
"FaceInfoNum": 1,
"FaceInfoList": [
{
"ID": 5,
"Timestamp": 1564707615,
"CapSrc": 1,
"FeatureNum": 0,
"FeatureList": [
{
"FeatureVersion": "",
"Feature": ""
},
{
"FeatureVersion": "",
"Feature": ""
}
],
“Temperature”: 36.5,
“MaskFlag”: 1,
"PanoImage": {
"Name": "1564707615_1_86.jpg",
"Size": 101780,
"Data": "…"
},
"FaceImage": {
"Name": "1564707615_2_86.jpg",
"Size": 35528,
"Data": "…"
},
"FaceArea": {
"LeftTopX": 4981,
"LeftTopY": 3744,
"RightBottomX": 8250,
"RightBottomY": 5583
}
}
],
"CardInfoNum": 0,
"CardInfoList": [ ],
"GateInfoNum": 0,
"GateInfoList": [ ],
"LibMatInfoNum": 1,
"LibMatInfoList": [
{
"ID": 5,
"LibID": 3,
"LibType": 4,
"MatchStatus": 2,
"MatchPersonID": 0,
"MatchFaceID": 0,
"MatchPersonInfo": {
"PersonName": "",
"Gender": 0,
"CardID": "",
"IdentityNo": ""
}
}
]
}
I am using Laravel, I got [] when tried $request->all(), below when I dump( $request->getContent() );
dump
Seems like I need to remove "" from beginning and end of request in order to json_decode(), but no matter what string function I used - preg_replace, substring, etc - nothing changed, when I tried $content[0] I got { and NOT ", $content[-1] I got \n, $content[-2] I got }
Can anybody point out where I erred ?
Looks like this is the Content-Type header problem. But it should be a proper solution:
$find = ['/"""/', '/\\\n/', '/“/', '/”/'];
$replace = ['', '', '"', '"'];
$output = preg_replace($find, $replace, $your_input);
// now the $output is ready to be decoded
$decoded = json_decode($output);
$v = var_dump($decoded);
See this Repl for real implementation: Json Parse

Stripe, users can not download their invoice

I am working with Stripe Payment Gateway and everything is working so far, except the option, that my users can download their invoice on my website. It is possible to download an invoice inside the stripe dashboard but that is not what I need. After my users made a payment, they should be able to download their invoices to my system.
Currently I am working with stripe webhooks. A user makes a payment and the data is saved inside my database. This is how my code looks like:
\Stripe\Stripe::setApiKey("$stripe_secret_key_test");
// Retrieve the request's body and parse it as JSON:
$input = #file_get_contents('php://input');
$event_json = json_decode($input);
// Update database with new billing entry
if ($event_json->type == 'invoice.payment_succeeded') {
$invoice_id = $event_json->data->object->id;
$customer = $event_json->data->object->customer;
$date = $event_json->data->object->date;
$price = $event_json->data->object->amount_paid;
$user = $event_json->data->object->lines->data[0]->metadata->userid;
$stripe_sub_id = $event_json->data->object->lines->data[0]->id;
$plan_id = $event_json->data->object->lines->data[0]->plan->id;
$stamp_created = $event_json->data->object->lines->data[0]->plan->created;
$comments = $event_json->data->object->lines->data[0]->plan->nickname;
$period_start = $event_json->data->object->lines->data[0]->period->start;
$period_end = $event_json->data->object->lines->data[0]->period->end;
$content=array("invoice"=>$invoice_id,
"user"=>$user,
"stripe_cust_id"=>$customer,
"stripe_sub_id"=>$stripe_sub_id,
"idea_id"=>0,
"billing_date"=>$date,
"plan"=>$plan_id,
"price"=>$price,
"stamp_created"=>$stamp_created,
"period_start"=>$period_start,
"period_end"=>$period_end,
"status"=>'paid',
"printed"=>0);
insertGWInfo('billing',$content);
$content=array("user"=>$user,
"trans_time"=>date("Y-m-d H:i:s"),
"ip"=>$_SERVER['REMOTE_ADDR'],
"trans_type"=>1,
"cash_amount"=>$price,
"comments"=>"Subscription for ".$comments."",
"idea_id"=>0);
insertGWInfo('user_accounting',$content);
}
Now I´ve created a table where I fetch those entries from my database and display them to my customer. I would like to have a button now with "Download Invoice" where my customers can download the subscription invoice which appears monthly.
Any idea how I can do this? I have the invoice_id but where do I get the URL to download an invoice? I wasn´t able to find anything inside the stripe docs. Any help would be really appreciated.
EDIT:
Here is the JSON outcome for invoice.payment_suceeded:
"{
"created": 1326853478,
"livemode": false,
"id": "evt_00000000000000",
"type": "invoice.payment_succeeded",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2018-02-28",
"data": {
"object": {
"id": "in_00000000000000",
"object": "invoice",
"amount_due": 1000,
"amount_paid": 1000,
"amount_remaining": 0,
"application_fee": null,
"attempt_count": 1,
"attempted": true,
"billing": "charge_automatically",
"charge": "_00000000000000",
"closed": true,
"currency": "eur",
"customer": "cus_00000000000000",
"date": 1526455801,
"description": null,
"discount": null,
"due_date": null,
"ending_balance": 0,
"forgiven": false,
"lines": {
"data": [
{
"id": "sub_Cs4DUPJKcAJ7cg",
"object": "line_item",
"amount": 1000,
"currency": "eur",
"description": "1 standard-inv × Standard Investor (at €10.00 / month)",
"discountable": true,
"livemode": false,
"metadata": {
},
"period": {
"end": 1531726201,
"start": 1529134201
},
"plan": {
"id": "3",
"object": "plan",
"aggregate_usage": null,
"amount": 1000,
"billing_scheme": "per_unit",
"created": 1526375755,
"currency": "eur",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": "Standard Plan for Investors",
"product": "prod_CrihTVfgRHgImD",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"proration": false,
"quantity": 1,
"subscription": null,
"subscription_item": "si_Cs4DrvYN2FlCbS",
"type": "subscription"
}
],
"has_more": false,
"object": "list",
"url": "/v1/invoices/in_1CSK5FDsOByhb3e8m8Z1BooY/lines"
},
"livemode": false,
"metadata": {
},
"next_payment_attempt": null,
"number": "774C629-0001",
"paid": true,
"period_end": 1526455801,
"period_start": 1526455801,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"subscription": "sub_00000000000000",
"subtotal": 1000,
"tax": null,
"tax_percent": null,
"total": 1000,
"webhooks_delivered_at": 1526455810
}
}
}"
Stripe DOES support this now. The PDF link is available by listing the invoices via the API and accessing the invoice_pdf attribute of an invoice.
Here's how you can get an array of invoices with their PDF links:
const invoicesResponse = await stripe.invoices.list({ customer: customerStripeId });
const invoices = invoicesResponse.map(invoice => ({
invoiceId: invoice['id'],
pdf: invoice['invoice_pdf'],
}));
return invoices;
Here's the API docs:
https://stripe.com/docs/api/invoices/object#invoice_object-invoice_pdf Thanks #avelis for the suggestion.
Stripe does not support downloading the invoice as a PDF at the moment via the API and it is only available in the dashboard instead.
For now, the best solution is to build your own invoice receipt/pdf instead. You can retrieve the Invoice object via the API which tells you what the invoice is for: period, amount, when it was paid, what's in that invoice, etc. And you can then generate your own receipt for your customers on your end.
it is posible :) works like a charm with the Python API.
import stripe
import requests
stripe_keys = {'secret_key': 'XXXxxxx','publishable_key': 'XXXxxxx'}
stripe.api_key = stripe_keys['secret_key']
stripe_subscription_id = 'XXXXXXX'
invoices = stripe.Invoice.list(subscription=stripe_subscription_id)
for inv in invoices:
pdf = inv.invoice_pdf
invoice_file = requests.get(pdf)
open('C://User//XXXXX//Desktop//invoice.pdf', 'wb').write(invoice_file.content)
There is a much easier way now. Following are the steps I follow to use Stripe's default method to download the invoice pdf.
Find the customer for which I want to download the invoice in pdf format
const findCustomerByEmail = async (email) => {
try {
const customer = await stripe.customers.list({
email,
limit: 1,
});
if (customer.data.length !== 0) {
return customer.data[0].id;
}
} catch (e) {
return (e);
}
};
Now that I have the customer, I then find all the invoices of the user:
exports.getInvoices = async (req, res, next) => {
const cusStripeId = await findCustomerByEmail(req.user.email);
const invoices = await stripe.invoices.list({
limit: 3000,
customer: cusStripeId,
});
res.status(httpStatus.OK).json(invoices);
};
Now I have a list of the invoices for this user. I can traverse through all the invoices.
invoices.data[0].invoice_pdf
invoices object is an array, and the data[0].invoice_pdf has a link that will download pdf. As an alternative we can also see the invoice as an html page without the need to download it, as follows.
invoices.data[0].hosted_invoice_url

Show JSON data from Request Body POST [duplicate]

As a test, this JSON data is being POSTed to my website:
{
"order": {
"id": null,
"created_at": null,
"status": "new",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 2263,
"currency_iso": "USD"
},
"custom": "123456789",
"button": {
"type": "buy_now",
"name": "Test Item",
"description": null,
"id": null
},
"transaction": {
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
}
}
}
Since it is being sent server-to-server I cannot visibly see the data. I have tried sending the $_POST array to a text file, but it comes up blank. What I think I need to do is:
$data = json_decode($jsonData);
But how do I set the variable $jsonData?
You can try to use wrappers for reading raw POST query.
$data = file_get_contents("php://input");
Have you tried this, store the sting obtained to a variable and then decoding it?
$postedJsonData= '{"order":{"id":null,"created_at":null,"status":"new","total_btc":
{"cents":100000000,"currency_iso":"BTC"},"total_native":
{"cents":2263,"currency_iso":"USD"},"custom":"123456789","button":
{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":
{"hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
var_dump(json_decode($postedJsonData, true));
The true parameter would return an associative array
$data = json_decode($jsonData, True);

How do I turn a POSTed JSON value into PHP?

As a test, this JSON data is being POSTed to my website:
{
"order": {
"id": null,
"created_at": null,
"status": "new",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 2263,
"currency_iso": "USD"
},
"custom": "123456789",
"button": {
"type": "buy_now",
"name": "Test Item",
"description": null,
"id": null
},
"transaction": {
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
}
}
}
Since it is being sent server-to-server I cannot visibly see the data. I have tried sending the $_POST array to a text file, but it comes up blank. What I think I need to do is:
$data = json_decode($jsonData);
But how do I set the variable $jsonData?
You can try to use wrappers for reading raw POST query.
$data = file_get_contents("php://input");
Have you tried this, store the sting obtained to a variable and then decoding it?
$postedJsonData= '{"order":{"id":null,"created_at":null,"status":"new","total_btc":
{"cents":100000000,"currency_iso":"BTC"},"total_native":
{"cents":2263,"currency_iso":"USD"},"custom":"123456789","button":
{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":
{"hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}';
var_dump(json_decode($postedJsonData, true));
The true parameter would return an associative array
$data = json_decode($jsonData, True);

How do i get the total number of comments from this JSON array using php?

Im tring to show a list of articles on my site with a authour, date and comments field below the article so that users can see the number of comments for an article before even opening it.
The coments are from facebook and im using the graph api which returns the following JSON code per article, how do i get the total number of comments from this? Thanks
I have tried json_decode but the arrays am getting are all with count zero.
{
"http://www.withinzambia.com/technology-and-it/your-modem-isnt-that-fast.html": {
"comments": {
"data": [
{
"id": "10151004341202332_23086817",
"from": {
"name": "Cindi Mutale",
"id": "1045450015732187"
},
"message": "Glad someone finally pointed this out.",
"can_remove": false,
"created_time": "2012-07-02T19:46:58+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "10151002332_23094740",
"from": {
"name": "Chanda Mike",
"id": "1000034452054679"
},
"message": "my modem is 7mbps, so that's not 7MB per second?",
"can_remove": false,
"created_time": "2012-07-03T13:51:24+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "10151004341202332_23094782",
"from": {
"name": "Precious Chulu",
"id": "100242343243281187"
},
"message": "The max for the modem in the picture is 7mbps, which is actually about 900kb when you divide by 8, so you will never download at more than 1mb per second with these modems even when MTN or Airtel upgrades the network.",
"can_remove": false,
"created_time": "2012-07-03T13:57:56+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"next": "https://graph.facebook.com/10151004341202332/comments?value=1&redirect=1&limit=25&offset=25&__after_id=10151004341202332_23094782"
}
}
}
}
<?php
...
$count = 0;
$array = json_decode($input, true);
foreach($array AS $website) {
$count += count($website['comments']['data']);
}
...
?>
$count is answer.
Bonus :)
$jsonArr = ' ..your JSON array.. ';
$decodedArr = json_decode($jsonArr);
$num_comments = count($decodedArr->{'http://www.withinzambia.com/technology-and-it/your-modem-isnt-that-fast.html'}->comments->data);
echo $num_comments;
tested and works.
be aware that if you load your JSON into a string, like i did here, single quotes will need to be escaped.

Categories