Java code for ETN Payments


#1

Hi all.

Here is the XML markup for a basic Android-Java ETN payments layout.
And some code to help drive it.
Its a bit of a mess, as I haven’t really had the time to go through and clean everything up.
In theory, just create a new activity called "pay_etn" and copy/paste this code into the relative XML and Java files. You can pretty much ignore activity_pay_etn

The rest is just linking in the right variables from other parts of your app, database, or hardcoded.
The only absolutely necessary variables are:
etnwallet, secret (secret api key), pricaftertaxallitems (sale cost), curency (ie: USD), saleid (ie: transaction id)

This script will also generate receipts.
Good luck!

XML LAYOUT:
Called: content_pay_etn
Child of: activity_pay_etn
Notes: The logo @drawable/electroneum is a simple electroneum logo placed into the Drawable folder
I pull most of my data from an MSSQL database, but you may choose to hardcode many of the values.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_dark"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.crowsoft.ezpos.pay_etn"
    tools:showIn="@layout/activity_pay_etn">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="2dp"
        android:background="@android:color/background_dark"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.075"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView14"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginTop="2dp"
                android:layout_weight="0.5"
                android:background="@android:color/background_light"
                android:paddingTop="0dp"
                android:textAlignment="center"
                android:textColor="@android:color/background_dark"
                android:textSize="24sp"
                android:textStyle="italic"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <View
                android:id="@+id/divider2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.005"
                android:background="?android:attr/listDivider"
                android:foreground="@android:color/background_dark" />

            <TextView
                android:id="@+id/textView69"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginTop="2dp"
                android:layout_weight="0.5"
                android:background="@android:color/background_light"
                android:paddingTop="0dp"
                android:textAlignment="center"
                android:textColor="@android:color/background_dark"
                android:textSize="24sp"
                android:textStyle="italic"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout7"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.075"
            android:background="@android:color/background_light"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView14">

            <TextView
                android:id="@+id/textView15"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:paddingTop="0dp"
                android:text="Cash Value Owed:"
                android:textColor="@android:color/background_dark"
                android:textSize="18sp" />

            <View
                android:id="@+id/divider6"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.005"
                android:background="?android:attr/listDivider"
                android:foreground="@android:color/background_dark" />

            <TextView
                android:id="@+id/textView32"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:text="ETN Value Owed:"
                android:textColor="@android:color/background_dark"
                android:textSize="18sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout8"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.1"
            android:background="@android:color/background_light"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayout7">

            <TextView
                android:id="@+id/payment_etn_amountowed"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:paddingTop="0dp"
                android:textColor="@android:color/background_dark"
                android:textSize="18sp" />

            <View
                android:id="@+id/divider7"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.005"
                android:background="?android:attr/listDivider"
                android:foreground="@android:color/background_dark" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.15"
                android:padding="5dp"
                app:srcCompat="@drawable/electroneum" />

            <TextView
                android:id="@+id/payment_etn_amountowedetn"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.35"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:paddingTop="0dp"
                android:textColor="@android:color/background_dark"
                android:textSize="18sp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginBottom="1dp"
            android:layout_weight="0.025"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView66"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:background="@android:color/background_light" />

            <View
                android:id="@+id/divider"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.005"
                android:background="?android:attr/listDivider"
                android:foreground="@android:color/background_dark" />

            <TextView
                android:id="@+id/textView33"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.5"
                android:background="@android:color/background_light"
                android:paddingEnd="20dp"
                android:text="* ETN Transfer fee included"
                android:textAlignment="textEnd"
                android:textColor="@android:color/background_dark"
                android:textSize="10sp" />
        </LinearLayout>

        <ImageView
            android:id="@+id/payment_etn_qrcode"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="1dp"
            android:layout_weight="0.35"
            android:background="@android:color/background_light"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayout8" />

        <TextView
            android:id="@+id/payment_etn_timeout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/background_light"
            android:text="Time out in 300s"
            android:textAlignment="center" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.3"
            android:background="@android:color/background_light"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.25"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.5"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/payment_etn_cancel"
                    android:layout_width="200dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:backgroundTint="#EE0000"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/payment_EFTPOS_confirm"
                    app:srcCompat="@android:drawable/ic_menu_close_clear_cancel" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.25"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

#2
> import android.annotation.SuppressLint;
> import android.app.AlertDialog;
> import android.content.Context;
> import android.content.DialogInterface;
> import android.content.Intent;
> import android.graphics.Bitmap;
> import android.graphics.Color;
> import android.media.MediaScannerConnection;
> import android.net.Uri;
> import android.net.http.RequestQueue;
> import android.os.AsyncTask;
> import android.os.Build;
> import android.os.Bundle;
> import android.os.CountDownTimer;
> import android.os.Environment;
> import android.os.StrictMode;
> import android.print.PrintAttributes;
> import android.print.PrintDocumentAdapter;
> import android.print.PrintManager;
> import android.support.v7.app.AppCompatActivity;
> import android.support.v7.widget.Toolbar;
> import android.util.Log;
> import android.view.View;
> import android.webkit.WebView;
> import android.webkit.WebViewClient;
> import android.widget.ImageButton;
> import android.widget.ImageView;
> import android.widget.TextView;
> import android.widget.Toast;
> import com.google.zxing.BarcodeFormat;
> import com.google.zxing.common.BitMatrix;
> import com.google.zxing.qrcode.QRCodeWriter;
> 
> import java.io.BufferedReader;
> import java.io.File;
> import java.io.FileWriter;
> import java.io.IOException;
> import java.io.InputStreamReader;
> import java.math.BigDecimal;
> import java.net.URL;
> import java.security.InvalidKeyException;
> import java.security.Key;
> import java.security.NoSuchAlgorithmException;
> import java.security.SignatureException;
> import java.sql.Connection;
> import java.sql.DriverManager;
> import java.sql.PreparedStatement;
> import java.sql.ResultSet;
> import java.sql.SQLException;
> import java.sql.Statement;
> import java.text.DecimalFormat;
> import java.text.SimpleDateFormat;
> import java.util.Date;
> import java.util.Formatter;
> import com.google.zxing.WriterException;
> import static java.lang.String.valueOf;
> import org.apache.http.HttpEntity;
> import org.apache.http.HttpResponse;
> import org.apache.http.HttpStatus;
> import org.apache.http.HttpVersion;
> import org.apache.http.client.HttpClient;
> import org.apache.http.client.methods.HttpGet;
> import org.apache.http.client.methods.HttpPost;
> import org.apache.http.entity.StringEntity;
> import org.apache.http.impl.client.DefaultHttpClient;
> import org.apache.http.params.BasicHttpParams;
> import org.apache.http.params.HttpConnectionParams;
> import org.apache.http.params.HttpParams;
> import org.apache.http.params.HttpProtocolParams;
> import org.apache.http.protocol.HTTP;
> import org.json.JSONObject;
> import javax.crypto.Mac;
> import javax.crypto.spec.SecretKeySpec;
> 
> public class pay_etn extends AppCompatActivity {
>     double amountgiveninteger;
>     double amountowedinteger;
> // converts anoying decimals to 2 decimal places
>     DecimalFormat formatx = new DecimalFormat("##.00"); 
>  // my database details
>     Connection connect = ConnectionHelper("sa", "*******", "databasenamegoeshere",  
> Preferences.getInstance().ipaddress);
>     Statement st;
>     String content;
>     String url;
>     PreparedStatement preparedStatement;
>     String line;
>     int cmcetn = 0;
>     String currency;
>     int finished;
>     WebView myWebView;
>     String htmlDocument;
>     String paymentstring;
>     String paymentid;
>     String paymentstatusmessage;
>     int paymentstatus;
>     int counttimer;
>     CountDownTimer cTimer = null;
>     int timeout;
>     String etnwallet;
>     String secret;
>     @Override
>     protected void onCreate(Bundle savedInstanceState) {
>         super.onCreate(savedInstanceState);
>         setContentView(R.layout.activity_pay_etn);
>         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
>         setSupportActionBar(toolbar);
> 
> 
>         currency = Preferences.getInstance().currency;
> // Yes, I am pulling the average ETN value from coin market cap
>         url = "https://api.coinmarketcap.com/v2/ticker/2137/?convert=" + currency;
> 
> 
>         try {
> // this is where I get my ETN wallet, secret API key and other settings from my database.
>             preparedStatement = connect.prepareStatement("select etnwallett, etnsecret from settings");
>             ResultSet rs = preparedStatement.executeQuery();
>             while (rs.next()) {
>                 content = rs.getString(1);
>                 etnwallet =   rs.getString(1);
>                 secret = rs.getString(2);
> 
>             }
>         } catch (Exception e) {
>             //
>         }
> 
> 
>         //BUTTON HANDLING
>         ImageButton cancel = findViewById(R.id.payment_etn_cancel);
>         cancel.setOnClickListener(new View.OnClickListener() {
>             @Override
>             public void onClick(View view) {
>                 finish();
>                 cTimer.cancel();
>             }
>         });
>         Preferences.getInstance().obsInt = new ObservableInteger();
>         final TextView amountowed = findViewById(R.id.payment_etn_amountowed);
>         final TextView amountowedetn = findViewById(R.id.payment_etn_amountowedetn);
> 
>         pay_etn.getetnusd test2 = new pay_etn().new getetnusd();
>         test2.execute("TEST");
> 
> 
>         Preferences.getInstance().obsInt.setOnIntegerChangeListener(new OnIntegerChangeListener() {
>             @Override
>             public void onIntegerChanged(int newValue) {
>                 if (Preferences.getInstance().obsInt.get() == 1) {
>                     test();
>                 } else if (
>                         Preferences.getInstance().obsInt.get() == 2
>                         ) {
>                     amountowedinteger = Double.valueOf(Preferences.getInstance().priceaftertaxstring);
>                     amountgiveninteger = 0.0;
>                     amountowed.setText(currency + "$ " + Preferences.getInstance().priceaftertaxstring);> 
>                     Log.w("TAG", "onIntegerChanged: BEGINNING SEND POST" );
> 
>                            timeout = 300;
>                             final TextView timeoutview = findViewById(R.id.payment_etn_timeout);
>                               cTimer = new CountDownTimer(300000, 2000) {
>                          public void onTick(long millisUntilFinished) {
>                             timeout = timeout -2;
>                             timeoutview.setText("Time out in " + timeout + "s");
>                             new SendPostRequest().execute();
>                             if (paymentstatus ==1){
>                                 cTimer.cancel();
> 
>                                 AlertDialog.Builder builder = new AlertDialog.Builder(pay_etn.this);
>                                 builder.setIcon(R.drawable.electroneumnew);
>                                 builder.setTitle("CompanyName: ETN");
>                                 builder.setMessage("Electroneum Payment Received!")
>                                         .setCancelable(false)
>                                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
>                                             public void onClick(DialogInterface dialog, int id) {
>                                                 paymentconfirmed();
>                                             }
>                                         });
>                                 AlertDialog alert = builder.create();
>                                 alert.show();
> 
> 
> 
> 
> 
>                             }
>                         }
> 
>                         public void onFinish() {
>                             if (paymentstatus ==0)
>                             {
>                                 AlertDialog.Builder builder = new AlertDialog.Builder(pay_etn.this);
>                                 builder.setIcon(getResources().getDrawable(android.R.drawable.ic_dialog_alert));
>                                 builder.setTitle("CompanyName: ETN");
>                                 builder.setMessage("Error: Electroneum Payment Timed-Out: (300 seconds)")
>                                         .setCancelable(false)
>                                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
>                                             public void onClick(DialogInterface dialog, int id) {
>                                                 finish();
>                                                 cTimer.cancel();
>                                             }
>                                         });
>                                 AlertDialog alert = builder.create();
>                                 alert.show();
>                             }
>                         }
>                     };
>                     cTimer.start();
>                 }
>             }
>         });
> 
>     }
> 
> 
> 
> 
> 
>     public void paymentconfirmed()
>     {
>        // Toast.makeText(pay_etn.this, "ETN Payment Confirmed", Toast.LENGTH_SHORT).show();
>         Preferences.getInstance().salecomplete = true;
>         Preferences.getInstance().paymenttype = "Crypto: ETN";
> 
> 
>         final AlertDialog.Builder receipt;
>         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
>             receipt = new AlertDialog.Builder(pay_etn.this, android.R.style.Theme_Material_Light_Dialog_Alert);
>         } else {
>             receipt = new AlertDialog.Builder(pay_etn.this);
>         }
>         receipt.setTitle("Receipt")
>                 .setMessage("Would you like to print a receipt?")
>                 .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
>                     public void onClick(DialogInterface dialog, int which) {
>                         print();
> 
>                     }
>                 })
>                 .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
>                     public void onClick(DialogInterface dialog, int which) {
>                         finish();
>                         cTimer.cancel();
>                     }
>                 })
>                 .setNeutralButton("E-mail", new DialogInterface.OnClickListener() {
>                     public void onClick(DialogInterface dialog, int which) {
>                         Context context = getApplicationContext();
>                         getTempFile(context, htmlDocument);
>                         finish();
>                         cTimer.cancel();
>                     }
>                 })
>                 .setIcon(android.R.drawable.ic_dialog_alert)
>                 .show();
> 
> 
>         receipt.create();
>     }
> 
>     public void test() {
>         // this is a small sample use of the QRCodeEncoder class from zxing
>         QRCodeWriter writer = new QRCodeWriter();
>         try {
> 
> 
>             int length = String.valueOf(Preferences.getInstance().saleid).length();
>             paymentid = ("0000000000" + String.valueOf(Preferences.getInstance().saleid)).substring(length);
>             amountowedinteger = Double.valueOf(Preferences.getInstance().priceaftertaxstring);
>             double etnowed = amountowedinteger / Double.valueOf(Preferences.getInstance().etnusdvalue);
>             String etnowedstring = formatx.format(etnowed);
>              content = etnwallet + "/" + paymentid + "/" + etnowedstring;
>             paymentstring = etnwallet + "/" + paymentid + "/" + etnowedstring;
>         Log.w("TAG", "" + content);
> 
>             BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
>             int width = bitMatrix.getWidth();
>             int height = bitMatrix.getHeight();
>             Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
>             for (int x = 0; x < width; x++) {
>                 for (int y = 0; y < height; y++) {
>                     bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
>                 }
>             }
> 
>             ((ImageView) findViewById(R.id.payment_etn_qrcode)).setImageBitmap(bmp);
>             Preferences.getInstance().obsInt.set(2);
> 
>         } catch (WriterException e) {
>             e.printStackTrace();
>             Preferences.getInstance().obsInt.set(0);
>         }
>     }
> 
> 
>     @SuppressLint("NewApi")
>     private Connection ConnectionHelper(String user, String password,
>                                         String database, String server) {
>         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
>                 .permitAll().build();
>         StrictMode.setThreadPolicy(policy);
>         Connection connection = null;
>         String ConnectionURL = null;
> 
>         try {
>             Class.forName("net.sourceforge.jtds.jdbc.Driver");
>             ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"
>                     + "databaseName=" + database + ";user=" + user
>                     + ";password=" + password + ";";
>             //     Log.w("TAG", "XXXXXXXXXXXXXXXXXXXXConnectionHelper: " + ConnectionURL);
>             DriverManager.setLoginTimeout(5);
>             connection = DriverManager.getConnection(ConnectionURL);
> 
>         } catch (SQLException se) {
>             return null;
> 
>         } catch (ClassNotFoundException e) {
>             Log.e("ERROR2", e.getMessage());
> 
>         } catch (Exception e) {
>             Log.e("ERROR3", e.getMessage());
> 
>         }
>         return connection;
>     }
> 
>     class getetnusd extends AsyncTask<String, String, String> {
>         @Override
>         protected String doInBackground(String... params) {
>             RequestBTCUSD(url);
>             while (cmcetn == 0) {
>             }
>             return null;
>         }
> 
>         @Override
>         protected void onPostExecute(String result) {
>             super.onPostExecute(result);
>             Preferences.getInstance().obsInt.set(1);
> 
>         }
> 
> 
>         void RequestBTCUSD(String url) {
> 
>             int timeoutSocket = 5000;
>             int timeoutConnection = 5000;
> 
> 
>             HttpParams httpParameters = new BasicHttpParams();
>             HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
>             HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
>             HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
>             HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
>             HttpClient client = new DefaultHttpClient(httpParameters);
>             HttpGet httpget = new HttpGet(url);
> 
>             try {
>                 HttpResponse getResponse = client.execute(httpget);
>                 final int statusCode = getResponse.getStatusLine().getStatusCode();
>                 if (statusCode != HttpStatus.SC_OK) {
>                     cmcetn = 1;
>                     return;
>                 }
> 
>                 line = "";
>                 StringBuilder total = new StringBuilder();
>                 HttpEntity getResponseEntity = getResponse.getEntity();
>                 BufferedReader reader = new BufferedReader(new InputStreamReader(getResponseEntity.getContent()));
> 
>                 while ((line = reader.readLine()) != null) {
>                     total.append(line);
>                 }
>                 line = total.toString();
> 
>                 //set some default variables for splitting texts
>                 String[] striptext;
>                 String[] striptext2;
>                 String striptext3;
>                 BigDecimal BTCpriceConvert;
>                 String BTCprice;
> 
>                 striptext = line.split(",");
>                 striptext2 = striptext[14].split(":");
>                 striptext3 = striptext2[2]; //.replaceAll("[/:!@#$%^&*()<>+?\"{}\\[\\]=`~;]", "");
>                 //  Log.w("TAG", "XXXXXXXXXXXXXXXXXXXXXXXXXX   RequestBTCUSD: "  + striptext3);
>                 Double cmc = Double.valueOf(striptext3);
>                 BTCpriceConvert = new BigDecimal(cmc);
>                 Log.w("TAG", "XXXXXXXXXXXXXXXXXXXXXXXXXX   RequestBTCUSD: " + BTCpriceConvert);
>                 BTCprice = valueOf(BTCpriceConvert);
>                 //  BTCprice = striptext3;
>                 line = BTCprice;
>                 int ETNWITHDRAWALFEE = 5;
>                 Preferences.getInstance().etnusdvalue = BTCprice + ETNWITHDRAWALFEE;
> 
> 
>                 cmcetn = 1;
>             } catch (Exception e) {
>                 cmcetn = 1;
>             }
>             cmcetn = 1;
>         }
>     }
> 
> 
>     private void print() {
>         runOnUiThread(new Runnable() {
>             WebView webView = new WebView(pay_etn.this);
> 
>             @Override
>             public void run() {
> 
> 
>                 webView.setWebViewClient(new WebViewClient() {
> 
>                     public boolean shouldOverrideUrlLoading(WebView view,
>                                                             String url) {
>                         return false;
>                     }
> 
>                     @Override
>                     public void onPageFinished(WebView view, String url) {
>                         PrintManager printManager = (PrintManager) pay_etn.this
>                                 .getSystemService(Context.PRINT_SERVICE);
> 
>                         PrintDocumentAdapter printAdapter =
>                                 webView.createPrintDocumentAdapter("MyDocument");
> 
>                         String jobName = getString(R.string.app_name) + " Print Test";
> 
>                         printManager.print(jobName, printAdapter,
>                                 new PrintAttributes.Builder().build());
>                         myWebView = null;
>                         finished = 1;
>                     }
>                 });
> 
> 
>                 try {
> 
>                     preparedStatement = connect.prepareStatement("select * from saleshistory WHERE saleid = " + Preferences.getInstance().saleid);
>                     ResultSet rs = preparedStatement.executeQuery();
> 
>                     int pass = 0;
> 
>                     String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
> 
>                     if (Preferences.getInstance().customername == null) {
>                         Preferences.getInstance().customername = "";
>                     }
> 
>                     htmlDocument =
>                             "<html><body><h1>" + Preferences.getInstance().companyname + "</h1>Tax Number:" + Preferences.getInstance().TaxNumber + "<br><p><b>RECEIPT for sale #: " + Preferences.getInstance().saleid + "</b><br>Customer = " + Preferences.getInstance().customername + "<br>Dated: " + date + "<br> Seller: " + Preferences.getInstance().loginusername + "<table border=1>";
>                     Log.w("TAG", "made it 2");
>                     while (rs.next()) {
> 
>                         String customer = rs.getString(4);
>                         String stockitemname = rs.getString(6);
>                         String Amount = rs.getString(5);
>                         final String priceperitem = rs.getString(7);
>                         final String pricebefore = rs.getString(8);
>                         final String priceafter = rs.getString(9);
>                         htmlDocument = htmlDocument + "<br><tr><th width=240>" + stockitemname + "</th><th width=80> x " + Amount + " </th><th width=100>$" + priceafter + "</th></tr>";
>                         pass = pass + 1;
>                     }
>                     Log.w("TAG", "made it 3");
> 
>                     htmlDocument = htmlDocument + "</table><br> Payment Type: " + Preferences.getInstance().paymenttype + "<br><B>TOTAL BEFORE TAX: <br>$" + formatx.format(Preferences.getInstance().pricebeforetaxallitems) + "<br>TOTAL AFTER TAX: <br>$" + formatx.format(Preferences.getInstance().priceaftertaxallitems)
>                             + "</b></p></body></html>";
> 
>                     webView.loadDataWithBaseURL(null, htmlDocument,
>                             "text/HTML", "UTF-8", null);
>                     Log.w("TAG", "made it 4");
>                     myWebView = webView;
> 
>                 } catch (Exception e) {
>                     Log.w("TAG", "print: " + e);
>                 }
>                 //   finish();
>             }
>         });
>      }
> 
> 
>     @Override
>     protected void onResume() {
>         super.onResume();
>         if (finished == 1) {
>             finish();
>             cTimer.cancel();
>         }
>     }
> 
> 
>     void getTempFile(Context context, String url) {
> 
>         String filename = Preferences.getInstance().companyname + "_receipt_" + Preferences.getInstance().saleid + ".html";
>         File testFile = new File(pay_etn.this.getExternalFilesDir(null), filename);
>         try {
> 
> 
>             int pass = 0;
>             preparedStatement = connect.prepareStatement("select * from saleshistory WHERE saleid = " + Preferences.getInstance().saleid);
>             ResultSet rs = preparedStatement.executeQuery();
>             while (rs.next()) {
> 
>                 String customer = rs.getString(4);
>                 String stockitemname = rs.getString(6);
>                 String Amount = rs.getString(5);
>                 final String priceperitem = rs.getString(7);
>                 final String pricebefore = rs.getString(8);
>                 final String priceafter = rs.getString(9);
>                 htmlDocument = htmlDocument + "<br><tr><th width=240>" + stockitemname + "</th><th width=80> x " + Amount + " </th><th width=100>$" + priceafter + "</th></tr>";
>                 pass = pass + 1;
>             }
> 
> 
>             if (Preferences.getInstance().customername == null) {
>                 Preferences.getInstance().customername = "";
>             }
> 
>             String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
> 
>             htmlDocument =
>                     "<html><body><h1>" + Preferences.getInstance().companyname + "</h1>Tax Number:" + Preferences.getInstance().TaxNumber + "<br><p><b>RECEIPT for sale #: " + Preferences.getInstance().saleid + "</b><br>Customer = " + Preferences.getInstance().customername + "<br>Dated: " + date + "<br> Seller: " + Preferences.getInstance().loginusername + "<table border=1>";
>             Log.w("TAG", "made it 2");
> 
>             Log.w("TAG", "made it 3");
> 
>             htmlDocument = htmlDocument + "</table><br> Payment Type: " + Preferences.getInstance().paymenttype + "<br><B>TOTAL BEFORE TAX: <br>$" + formatx.format(Preferences.getInstance().pricebeforetaxallitems) + "<br>TOTAL AFTER TAX: <br>$" + formatx.format(Preferences.getInstance().priceaftertaxallitems)
>                     + "</b></p></body></html>";
> 
> 
>             boolean sucess = testFile.createNewFile();
> 
>             FileWriter writer = new FileWriter(testFile);
>             //// Adds a line to the file
>             // BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true /*append*/));
>             writer.write(htmlDocument);
>             writer.close();
>             // Refresh the data so it can seen when the device is plugged in a
>             // computer. You may have to unplug and replug the device to see the
>             // latest changes. This is not necessary if the user should not modify
> 
>             // the files.
>             MediaScannerConnection.scanFile(this,
>                     new String[]{testFile.toString()},
>                     null,
>                     null);
> 
> 
>             String pathname = testFile.toString();
> 
>             File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), pathname);
>             Uri path = Uri.fromFile(filelocation);
> 
>             String email = "";
> 
>             try {
>                 preparedStatement = connect.prepareStatement("SELECT email FROM customers where id = " + Preferences.getInstance().customerid);
>                 ResultSet rsx = preparedStatement.executeQuery();
>                 while (rsx.next()) {
>                     email = rsx.getString(1);
>                 }
> 
>             } catch (SQLException se) {
>                 Log.e("ERROR1", se.getMessage());
>             }
> 
> 
>             String mailId = email;
>             Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
>                     Uri.fromParts("mailto", mailId, null));
> 
>             emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Receipt From: " + Preferences.getInstance().companyname);
    >             emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + pathname));
>    
>                  emailIntent.putExtra(Intent.EXTRA_HTML_TEXT, htmlDocument);
>             startActivity(Intent.createChooser(emailIntent, "Send email..."));
>
> 
>         } catch (IOException e) {
>             Log.e("ReadWriteFile", "Unable to write to the TestFile.txt file." + e);
>         } catch (Exception e) {
> 
>         }
> 
>     }
>   
>     public static String hashMac(String text, String secretKey)
>             throws SignatureException {
> 
>         try {
>             Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
>             Mac mac = Mac.getInstance(sk.getAlgorithm());
>             mac.init(sk);
>             final byte[] hmac = mac.doFinal(text.getBytes());
>             return toHexString(hmac);
>         } catch (NoSuchAlgorithmException e1) {
>             // throw an exception or pick a different encryption method
>             throw new SignatureException(
>                     "error building signature, no such algorithm in device "
>                             + HASH_ALGORITHM);
>         } catch (InvalidKeyException e) {
>             throw new SignatureException(
>                     "error building signature, invalid key " + HASH_ALGORITHM);
>         }
>     }
> 
> 
>     private static final String HASH_ALGORITHM = "HmacSHA256";
> 
>     public static String toHexString(byte[] bytes) {
>         StringBuilder sb = new StringBuilder(bytes.length * 2);
> 
>         Formatter formatter = new Formatter(sb);
>         for (byte b : bytes) {
>             formatter.format("%02x", b);
>         }
> 
>         return sb.toString();
>     }
> 
> 
>     public class SendPostRequest extends AsyncTask<String, Void, String> {
> 
>         protected void onPreExecute() {
>         }
> 
>         HttpClient httpClient = new DefaultHttpClient();
>         HttpResponse response;
>         protected String doInBackground(String... arg0) {
>             try {
>                 URL url = new URL("https://poll.electroneum.com/vendor/check-payment"); // here is your URL path
>                 JSONObject json = new JSONObject();
>                 json.put("payment_id", paymentid);
>                 json.put("vendor_address", etnwallet);
>                 String signature = hashMac(json.toString(), secret);
>                 HttpPost request = new HttpPost("https://poll.electroneum.com/vendor/check-payment");
>                 StringEntity params = new StringEntity(json.toString());
>                 request.addHeader("content-type", "application/json");
>                 request.addHeader("Accept", "application/json");
>                 request.addHeader("ETN-SIGNATURE", signature);
>                 request.setEntity(params);
>                response = httpClient.execute(request);
> 
>                 BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
>                 StringBuilder builder = new StringBuilder();
>                 String str = "";
> 
>                 while ((str = rd.readLine()) != null) {
>                     builder.append(str);
>                 }
> 
>                 String text = builder.toString();
>                 Log.w("TAG", "doInBackground: " +text );
> 
>                 String split[] = text.split(",");
>                 String statussplit[] = split[0].split(": ");
>                 paymentstatus = Integer.valueOf(statussplit[1]);
>                 Log.w("TAG", "doInBackground: STATUS =  " + paymentstatus );
>                 String split2[] = split[1].split(": ");
>                 paymentstatusmessage = split2[1].replaceAll("[-\\[\\]^/,'*:.!><~@#$%+=?|\"\\\\()]+", "");
>                 Log.w("TAG", "doInBackground: Message =  " + paymentstatusmessage );
> 
> 
>             } catch (Exception e) {
>                 return new String("Exception: " + e.getMessage());
>             } finally {
>                 httpClient.getConnectionManager().shutdown();
>             }
> 
>             return response.toString();
>         }
>        @Override
>         protected void onPostExecute(String result) {
>         }
>      } }

#3

JAVA CODE TO RUN EVERYTHING:
Notes:
called: pay_etn.java

  • Preferences.getInstance().Currency = a string, its a 3 letter code (AUS, USA, NZD) and it drives the conversion of ETN into local currency.
  • Preferences.getInstance().priceaftertaxallitems = a double, = the total price of your sale after tax
  • Preferences.getInstance().paymenttype = a string, The current type of payment (ie: “ETN” or “Crypto”)
  • Preferences.getInstance().ipaddress = a string, self explanatory, the IP address of any MSSQL server
  • Preferences.getInstance().companyname = a string, name of your company.
  • Preferences.getInstance().TaxNumber = a string, your tax registration number, for receipts
  • Preferences.getInstance().saleid = a string, 10 digits long. Used to generate ETN payment ID.
  • Preferences.getInstance().customername = a string, the customers name for receipts
  • Preferences.getInstance().loginusername = the sellers name, for receipts.

Oh ! There’s an observable change integer.
Preferences.getinstance().obsint
That I’m using to auto trigger certain events
You might want to Google how to create this.


#4

This is awesome! Thanks for the hours you put in!


#5

Awesome work @SteveElliott keep up the goodwork :blush: :+1:


#6

Awesome team, keep it up