· 4 years ago · Feb 25, 2021, 11:38 PM
1 <?php
2
3 public function pulseAuthToken() {
4 $base_url = "http://pulse.test";
5 $username = 'pulseAPI';
6 $password = 'admin123';
7 $client_secret = 'admin123';
8 $client_id = '890b281d-f6d5-403f-b6ab-306e8c367638';
9
10
11 $authData = {
12 'grant_type' => 'password',
13 'username' => $username,
14 'password' => $password,
15 'client_id' => $client_id,
16 'client_secret' => $client_secret,
17 }
18
19
20 $ch = curl_init($base_url . '/oauth/token');
21 curl_setopt_array($ch, array(
22 CURLOPT_POST => TRUE,
23 CURLOPT_RETURNTRANSFER => TRUE,
24 CURLOPT_HTTPHEADER => array(
25 'Content-Type: application/x-www-form-urlencoded'
26 ),
27 CURLOPT_POSTFIELDS => $authData
28 ));
29
30 $response = curl_exec($ch);
31
32 // Check for errors
33 if ($response === 401 || $reponse == 404) {
34 die(curl_error($ch));
35 };
36
37 curl_close($ch);
38
39 // Decode the response
40 return $response['access_token'];
41 }
42
43 public function createGasUsage($cost, $icp, $kwh) {
44 $base_url = "http://pulse.test";
45
46 $postData = array(
47 "_links": {
48 "type": {"href": $base_url . "/rest/type/usage_data/gas"}
49 },
50 "field_cost": [{"value": $cost}],
51 "field_icp": [{"target_id": $icp}],
52 "field_kwh": [{"value": $kwh}],
53 "field_estimate": [{"value": $estimate}],
54 "field_account": [{"target_id": $account}],
55 "field_day": [{"value": $day}],
56 "field_month": [{"value": $month}],
57 "field_year": [{"value": $year}],
58 );
59
60 $authToken = pulseAuthToken();
61
62 // Setup cURL
63 $ch = curl_init($base_url . '/entity/usage_data?_format=hal_json');
64 curl_setopt_array($ch, array(
65 CURLOPT_POST => TRUE,
66 CURLOPT_RETURNTRANSFER => TRUE,
67 CURLOPT_HTTPHEADER => array(
68 'Authorization: Bearer '.$authToken,
69 'Content-Type: application/hal_json'
70 ),
71 CURLOPT_POSTFIELDS => json_encode($postData)
72 ));
73
74 // Send the request
75 $response = curl_exec($ch);
76
77 // Check for errors
78 if($response === FALSE){
79 die(curl_error($ch));
80 };
81
82 // Decode the response
83 $responseData = json_decode($response, TRUE);
84
85 // Close the cURL handler
86 curl_close($ch);
87
88 // Print the date from the response
89 echo $responseData['Successful'];
90 }
91