API להפקת חשבוניות וקבלות - דוגמאות קוד בשפות שונות (חלק 2)
דוגמאות לקוד התחברות ל API של חשבונית ירוקה בשפות תכנות PHP, Java, C#, Node.js, Ruby, Python
המדריך הבא מציג הנחיות לממשק ה- API הישן. לממשק ה- API החדש שלנו, לחצו כאן.
ניתן לפנות ל API של מערכת חשבונית ירוקה, בכל שפת תכנות, תוך שמירה על סוג הפרוטוקול הנדרש (POST / GET), אובייקטים מסוג JSON וחתימה עם אלגוריתם SHA-256. מרבית שפות התכנות הפופולריות מכילות פונקציות מובנות שמבצעות את הנדרש באופן פשוט וברור.
דוגמא לבקשה ב php
$apiKey = "{public-api-key}"; $apiSecret = "{private-api-key}"; $params = array( "timestamp" => time(), //Current timestamp "callback_url" => "{your-callback-url}", "doc_type" => 320, "description" => "תיאור מסמך", "client" => array( "send_email" => true, "name" => "לקוח חדש", "tax_id" => "123456789", "email" => "user@email.com", "address" => "רח' דיזנגוף 300", "city" => "תל אביב", "zip" => "1234567" ), "income" => array( array( "price" => "500.00", "description" => "תיאור שורת הכנסה" ) ), "payment" => array( array( "type" => 2, //Cheque "date" => "2012-01-01", //YYYY-MM-DD "amount" => "500.00", "bank" => "מזרחי טפחות", "branch" => "761", "account" => "123456", "number" => "10928" ) ) ); //Compute hashed signature with SHA-256 algorithm and the secret key $params_encoded = json_encode($params); $signature = base64_encode(hash_hmac('sha256', $params_encoded, $apiSecret, true)); $data = array( "apiKey" => $apiKey, "params" => $params, "sig" => $signature ); //Initializing curl $ch = curl_init(); //Configuring curl options $options = array( CURLOPT_URL => "https://www.greeninvoice.co.il/api/documents/add", CURLOPT_POST => true, CURLOPT_POSTFIELDS => "data=" . urlencode(json_encode($data)), CURLOPT_SSL_VERIFYPEER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array("Content-Type: application/x-www-form-urlencoded; charset=utf-8") ); //Setting curl options curl_setopt_array($ch, $options); //Getting results $result = curl_exec($ch); // Getting jSON result string curl_close($ch); //Parse result to JSON $response = json_decode($result); //If Ok if ($response->error_code == 0) { //Process response here }
דוגמא לבקשה ב java
Maven Dependency: הוספת JSON.simple לקובץ pom.xml.
com.googlecode.json-simple json-simple 1.1.1
שליחת נתונים למערכת ה API של חשבונית ירוקה:
import org.apache.commons.net.util; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class GreenInvoiceApiExample { public static void main(String[] args) { String apiKey = "{public-api-key}"; String apiSecret = "{private-api-key}"; JSONObject params = new JSONObject(); params.put("timestamp", System.currentTimeMillis() / 1000; params.put("callback_url", "{your-callback-url}"); params.put("doc_type", 320); params.put("description", "תיאור מסמך"); //Add client object JSONObject client = new JSONObject(); client.put("send_email", true); client.put("name", "לקוח חדש"); client.put("tax_id", "123456789"); client.put("email", "user@email.com"); client.put("address", "רח' דיזנגוף 300"); client.put("city", "תל אביב"); params.put("client", client); //Add income rows JSONArray income = new JSONArray(); JSONObject incomeRow = new JSONObject(); incomeRow.put("price", "500.00"); incomeRow.put("description", "תיאור שורת הכנסה"); income.add(incomeRow); params.put("income", income); //Add payment rows JSONArray payment = new JSONArray(); JSONObject paymentRow = new JSONObject(); paymentRow.put("type", 2); paymentRow.put("date", "2012-01-01"); paymentRow.put("amount", "500.00"); paymentRow.put("bank", "מזרחי טפחות"); paymentRow.put("branch", "761"); paymentRow.put("account", "123456"); paymentRow.put("number", "10928"); payment.add(paymentRow); params.put("payment", payment); PostMethod post = new PostMethod("https://www.greeninvoice.co.il/api/documents/add"); try { //Compute hashed signature with SHA-256 algorithm and the secret key Mac mac = Mac.getInstance("HMACSHA256"); mac.init(new SecretKeySpec(apiSecret.getBytes(), "HMACSHA256")); String signature = new String(new Base64(256, null, false) .encode(mac.doFinal(params.toJSONString().getBytes("UTF-8")))); JSONObject data = new JSONObject(); data.put("apiKey", apiKey); data.put("params", params); data.put("sig", signature); //Create HTTP request to GreenInvoice API HttpClient httpClient = new HttpClient(); post.setParameter("data", data.toJSONString()); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); httpClient.executeMethod(post); //Parse response String responseBody = post.getResponseBodyAsString(); Object obj = JSONValue.parse(responseBody); JSONObject response = (JSONObject) obj; long errorCode = (Long) response.get("error_code"); if (errorCode.equals(0)) { //Ok } } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { post.releaseConnection(); } } }
דוגמא לבקשה ב python
# # Written by Nir Ailon # import os import httplib import urllib import json import time import base64 import hmac import hashlib HTTPTIMEOUT = 60 APIKEY_PUBLIC = bytes("{public key}") APIKEY_PRIVATE = bytes("{private key}") GREENINVOICE_URL = "www.greeninvoice.co.il" GREENINVOICE_PATH = "/api/documents/add" testInvoice = { "timestamp": time.time(), "callback_url": "https://my-callback-url.com", "doc_type": 320, "description": "desc", "client": { "name": "clent-name", "tax_id": "123456789", "email": "user@email.com", "address": "aaaa300", "city": "bbbbb", "zip": "1234567" }, "income": [ { "price": "500.00", "description": "desc" } ], "payment": [ { "type": 2, "date": "2012-01-01", "amount": "500.00", "bank": "poalim", "branch": "761", "account": "123456", "number": "10928" } ] } test_encoded = json.dumps(testInvoice, separators=(',',':'), ensure_ascii=False) test_hash = hmac.new(APIKEY_PRIVATE, msg=test_encoded, digestmod=hashlib.sha256).digest() test_signature = base64.b64encode(test_hash) test_params = json.dumps({ "apiKey" : APIKEY_PUBLIC, "params" : testInvoice, "sig" : test_signature}, separators=(',',':'), ensure_ascii=False) url_params = urllib.urlencode({"data" : test_params}) conn = httplib.HTTPSConnection(GREENINVOICE_URL, timeout=HTTPTIMEOUT) conn.request("POST", GREENINVOICE_PATH, body=url_params, headers={"Content-type": "application/x-www-form-urlencoded"}) response = json.loads(conn.getresponse().read()) conn.close()
דוגמא לבקשה ב #C
ראשית יש להוריד ספריה לטיפול ב JSON, בדוגמה כאן נשתמש ב Json.NET
using System; using System.Text; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Net; using System.Net.Security; using System.IO; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace SampleNamespace { public class SampleClass { public static void Main() { string ApiKey = "{public-api-key}"; string ApiSecret = "{private-api-key}"; long t = (long)(DateTime.Now.ToUniversalTime()-new DateTime(1970,1,1)).TotalSeconds; JObject Params = new JObject(); Params.Add("timestamp", t); Params.Add("callback_url", "{your-callback-url}"); Params.Add("doc_type", 320); Params.Add("description", "just a + description"); //Add client object JObject Client = new JObject(); Client.Add("send_email", true); Client.Add("name", "client name"); Client.Add("tax_id", "123456789"); Client.Add("email", "user@email.com"); Client.Add("address", "client address"); Client.Add("city", "city name"); Params.Add("client", Client); //Add income rows JArray Income = new JArray(); JObject IncomeRow = new JObject(); IncomeRow.Add("price", "500.00"); IncomeRow.Add("description", "test test"); Income.Add(IncomeRow); Params.Add("income", Income); //Add payment rows JArray Payment = new JArray(); JObject PaymentRow = new JObject(); PaymentRow.Add("type", 2); PaymentRow.Add("date", "2012-01-01"); PaymentRow.Add("amount", "500.00"); PaymentRow.Add("bank", "bank"); PaymentRow.Add("branch", "761"); PaymentRow.Add("account", "123456"); PaymentRow.Add("number", "10928"); Payment.Add(PaymentRow); Params.Add("payment", Payment); //Prepare signed data System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); Formatting f = Formatting.None; ServicePointManager.ServerCertificateValidationCallback = ValidateCertificate; byte[] key = encoding.GetBytes(ApiSecret); HMACSHA256 myhmacsha256 = new HMACSHA256(key); byte[] hashValue = myhmacsha256.ComputeHash(encoding.GetBytes(Params.ToString(f))); string Signature = Convert.ToBase64String(hashValue); myhmacsha256.Clear(); JObject Data = new JObject(); Data.Add("apiKey", ApiKey); Data.Add("params", Params); Data.Add("sig", Signature); //Send request to API string ApiUrl = "https://www.greeninvoice.co.il/api/documents/add"; WebRequest request = WebRequest.Create(ApiUrl); request.Method = "POST"; string encodedData = System.Web.HttpUtility.UrlEncode(Data.ToString(f), encoding); string postData = "data=" + encodedData; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader (dataStream); string responseBody = reader.ReadToEnd(); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); JObject Response = JObject.Parse(responseBody); int ErrorCode = (int) Response["error_code"]; if (ErrorCode == 0) { //Ok } } // End of Main function (program statup) private static bool ValidateCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors ){ //This is where you should validate the remote certificate return true; } } // End of SampleClass } // End of SampleNamespace
דוגמא לבקשה ב Node.js
// request - https://github.com/mikeal/request var request = require('request'); // node.js crypto var crypto = require('crypto'); // my keys var privateKey = '{private-api-key}'; var publicKey = '{public-api-key}'; // an SHA256 hmac, with the private key + UTF8 var signer = crypto.createHmac('sha256', new Buffer(privateKey, 'utf8')); //request objects var client = { 'send_email': false, 'name': 'שם', 'address': 'כתובת' }; var income = [ { 'price': 100.00, 'description': 'מוצר שנמכר' }, { 'price': 220.00, 'description': 'עוד מוצר שנמכר' } ]; var payment = [ { 'type': 1, 'amount': 320.00 } ]; var params = { 'timestamp': new Date().getTime(), 'callback_url': 'http://www.callback-url.com', 'doc_type': 320, 'description': 'בדיקה', 'client': client, 'income': income, 'payment': payment }; // generate a signature for the 'data' object var jsonData = decodeURIComponent(encodeURIComponent(JSON.stringify(params))); var messageSignature = signer.update(jsonData).digest('base64'); // message object to POST var data = { 'apiKey': publicKey, 'params': params, 'sig': messageSignature }; request( { 'method': 'POST', 'url': 'https://www.greeninvoice.co.il/api/documents/add', 'headers': {'Content-Type': 'application/json', 'charset': 'utf-8'}, 'form': {'data': JSON.stringify(data)} }, function (error, response, body) { console.log(body); } );
דוגמא לקוד ב Ruby
apiKey = "{public-api-key}" apiSecret = "{private-api-key}" params = { "timestamp" => DateTime.now.strftime('%s'), "callback_url" => "" "doc_type" => 320, "description" => "Online purchase", "client" => { "send_email" => true, "name" => "clientname", "email" => "user@email.com", "address" => "clientaddress", "city" => "city", "zip" => "1234567" }, "income" => [ { "price" => 1, "description" => "desc" } ], "payment" => [ { "type" => 3, "date" => "2012-01-01", "amount" => 1, "number" => "8971", "deal_type" => 1, "card_type" => 2 } ] } params_encoded = params.to_json params = JSON.parse(params_encoded) sig = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), apiSecret, params_encoded)).strip() data = { "apiKey" => apiKey, "params" => params, "sig" => sig } data = {data: data.to_json} uri = URI.parse 'https://www.greeninvoice.co.il/api/documents/add' http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri, initheader = {'Content-Type' =>'application/x-www-form-urlencoded; charset=utf-8'}) request.set_form_data(data) response = http.request(request)