iOS Push Notifications to a topic - java

I have an Ionic app (client), with a Java 8 backend (server), and I have set up push notifications.
client
let topics: string[] = [this.personModelLoggedIn.uid];
const options: PushOptions = {
android: {
senderID: "XXXXXXXXXXXX",
sound: "true",
vibrate: "true",
topics: topics
},
ios: {
senderID: "XXXXXXXXXXXX",
alert: "true",
badge: true,
sound: "true",
topics: topics
},
windows: {}
};
For Android, I can receive notifications, send from the following:
server
private String sendAndroidPushNotification(String device_token, String topics, String title, String message)
throws Exception {
String pushMessage = null;
if (device_token != null && !device_token.equals("null")) {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\":\""
+ device_token + "\"}";
} else {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\": \"/topics/"
+ topics + "\"}";
}
// Create connection to send FCM Message request.
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(pushMessage.getBytes());
return "Android Push Notification: " + conn.getResponseCode() + " " + conn.getResponseMessage() + " - " + pushMessage;
}
Problem
I have the following code for iOS, but the client does not receive the push notifications.
/**
* import com.notnoop.apns.APNS; import com.notnoop.apns.ApnsService;
* https://github.com/notnoop/java-apns.
*/
private String sendIOSPushNotification(String device_token, String topics, String title, String message)
throws Exception {
ApnsService service = APNS.newService().withCert(PATH_TO_P12_CERT, CERT_PASSWORD).withSandboxDestination()
.build();
String payload = APNS.newPayload()
// .customFields(map)
.alertBody(title + " " + message).sound("default").build();
service.push(Utilities.encodeHex(topics.getBytes()), payload);
return "iOS Push Notification: " + title + " " + message;
}
If you look at the com.notnoop.apns api, it is supposed to push to a device token, however, I need it to rather push to a uid. I have implemented the above code to push to a uid, but it doesn't work.
Question
Id it possible for the com.notnoop.apns api to push notifications to a topic? Otherwise, is there another api that will be able to do this?
If neither is possible, should the client rather listen on the device token? But the problem here is, that the sender of the push notification does not know the receivers device token. The sender does know the receivers uid though.
Thanks

Related

How to send sms messages in Android using http requests using java code

I want to send SMS using android application. For that I had refer following sites.
ozekisms.com
Java Sms Example
How To Make HTTP POST Request To Server
And from following site I had registered and from using that API URL I had make that request.
http://websms.24x7sms.com/
http://www.24x7sms.com/downloads/24x7sms_http_api2.pdf
For that I used the following code.
protected void sendSMS(){
Log.d("in","booking sms function");
String nm1 = name.getText().toString();
String ara1 = area.getSelectedItem().toString();
String add1 = address.getText().toString();
String mob1 = mobile.getText().toString();
String message1 = "Name:"+ nm1 + "\n" + "Area:" + ara1 + "\n" + "Address:" + add1 + "\n"
+ "Mobile:" + mob1;
BufferedReader reader = null;
// Defined URL where to send data
String requesturl = "http://smsapi.24x7sms.com/api_2.0/SendSMS.aspx?APIKEY=********" +
"MobileNo=+91**********&SenderID=SMSMsg&Message=You%20have%20new%20booking%20fro%20(variable%20please%20collect%20from%20them." +
"ServiceName=TEMPLATE_BASED";
try {
URL url = new URL(requesturl);
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
huc.setRequestMethod("POST");
Log.d("after connection open",huc.getResponseMessage());
Log.d("RESPONSE FROM SERVER", huc.getResponseMessage());
}
After Running program I had get following message in logcat window.
11-06 20:14:57.830 6513-6513/com.******.*******.********* D/in: booking sms function
11-06 20:14:58.555 6513-6513/com.******.*******.********* D/after connection open: OK
11-06 20:14:58.556 6513-6513/com.******.*******.********* D/RESPONSE FROM SERVER: OK
But i never receive the message on particular mob number. Please Help me.
Thanks In ADVANCE....

Push Notification to IOS issue CodeName One

I try to push notification from java server to IOS client
and i have this error(response from codename one server)
{"error":"Failed to send push to APNS: com.notnoop.exceptions.NetworkIOException: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake"}
String GOOGLE_SERVER_KEY = "********************************************";
HttpsURLConnection connection;
String url = "https://push.codenameone.com/push/push";
String TOKEN = "******-****-*****-*****-**************";
String URL_ENCODED_LINK_TO_YOUR_P12_FILE =
"https://dl.dropboxusercontent.com/*/******************/Certificates.p12";
String URL_ENCODED_CERTIFICATE_PASSWORD = "******";
String deviceId =
"cn1-gcm-*******************************************************";
String deviceId2 =
"cn1-ios-***************************************************";
String MESSAGE_BODY = "This notification message coming from server";
try {
connection = (HttpsURLConnection)new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
String query =
"token=" + TOKEN + "&device=" + deviceId + "&device=" +
deviceId2 + "&type=1&auth=" + GOOGLE_SERVER_KEY +
"&certPassword=" + URL_ENCODED_CERTIFICATE_PASSWORD +
"&cert=" + URL_ENCODED_LINK_TO_YOUR_P12_FILE + "&body=" +
URLEncoder.encode(MESSAGE_BODY, "UTF-8") + "&production=false";
try {
OutputStream output = connection.getOutputStream();
output.write(query.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ResponseCode : " + connection.getResponseCode());
System.out.println("ResponsenMessage : " +
connection.getResponseMessage());
BufferedReader br =new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
String result = "";
System.out.println("Output .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
result += output + "\n";
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
Output from codename one Server
Response Code : 200
Response Message : OK
Output ....
{"error":"Failed to send push to APNS: com.notnoop.exceptions.NetworkIOException: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake"}
A handshake exception would generally mean the Codename One servers failed to connect due to a security issue. This probably means your P12 is incorrect.
Are you sure you used the right P12 file? Keep in mind that there are 2 push certificates (not to be confused with the 2 signing certificates) and only one of them should be used based on the value of the sandbox flag.
Did you use the certificate wizard?
I think 2195 and 2196 ports are disabled on either the server or client side which needs to be enabled for apple push notification.

getting Blank response from php server while access from other country in android

I made a andoid application in which I am getting response from php server, requesting in POST format. I am using below code for http connection:
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
String url = encodeUrl(methodType, graphURL, params);
Log.d("url - ",url);
Log.d("Method Type - ", methodType + " URL - " + url);
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setConnectTimeout(60000);
conn.setReadTimeout(30000);
conn.setRequestProperty("User-Agent", System.getProperties()
.getProperty("http.agent"));
if (!methodType.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
if (params.getByteArray(key) != null) {
dataparams.putByteArray(key, params.getByteArray(key));
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", methodType);
}
if (params.containsKey("access_token")) {
#SuppressWarnings("deprecation")
String decoded_token = URLDecoder.decode(params
.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(("--" + strBoundary + endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key : dataparams.keySet()) {
os.write(("Content-Disposition: form-data; filename=\""
+ key + "\"" + endLine).getBytes());
os
.write(("Content-Type: content/unknown" + endLine + endLine)
.getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine)
.getBytes());
}
}
os.flush();
}
String response = "";
try {
response = parseXmlSvn(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
//response = read(conn.getErrorStream());
Log.i("RESPONSE",""+response);
}
Log.i("RESPONSE", ""+response);
return response;
Everything is working fine on my demo server, I uploaded my PHP service to clients server. I am getting proper response from his server also.
But when client access app in 3G or 4G in some other country in his android devices, he is getting Blank response while the same service of same server can be accessible in iOS code easily by him. Is it some packet loss while getting response or any other problem?
I would really appreciate any help you can give me.
Thanks

PayPal IPN returns INVALID on live and VERIFIED on sandbox

I have been trying to implement the paypal IPN system in our company website. When I test my script in the IPN sandbox tool, it is validated and everything goes well, however when I move it live, the IPN returned as INVALID but the payment has been completed well.
When I check the IPN history in my account, I can see this IPN message with the HTTP Response 200:
mc_gross=0.01&invoice=40&protection_eligibility=Ineligible&item_number1=&payer_id=mypayerId&tax=0.00&payment_date=08:06:52 Sep 03, 2013 PDT&payment_status=Completed&charset=windows-1252&mc_shipping=0.00&mc_handling=0.00&first_name=myName&mc_fee=0.01&notify_version=3.7&custom=18528&payer_status=verified&business=bussiness_mail&num_cart_items=1&mc_handling1=0.00&verify_sign=AJ.HL1f2A9aoBiFQCLn.3J-QkKQGAF.RVW8er5rbGJ6SsQFWBbStuRtD&payer_email=myMail&mc_shipping1=0.00&tax1=0.00&txn_id=61052338B4613440H&payment_type=instant&last_name=MySurname&item_name1=Paquete Lite&receiver_email=mybussiness_mail&payment_fee=&quantity1=1&receiver_id=SVRXVCZYE2AYC&txn_type=cart&mc_gross_1=0.01&mc_currency=EUR&residence_country=ES&transaction_subject=18528&payment_gross=&ipn_track_id=38c492cbe6257
Paypal live credentials are OK.
URL is OK (https://www.paypal.com/cgi-bin/webscr)
My IPNHandler is a Java Servlet. The doPost Action is:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Java JSP
log.error("IPN doPost " + new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds());
// read post from PayPal system and add 'cmd'
Enumeration en = request.getParameterNames();
String str = "cmd=_notify-validate";
while (en.hasMoreElements()) {
String paramName = (String) en.nextElement();
String paramValue = request.getParameter(paramName);
paramValue = new String(paramValue.getBytes("iso-8859-1"), "utf-8");
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
boolean isSandbox = "true".equals(PropertiesManager.getProperty("signbox", "PaypalSandbox"));
// post back to PayPal system to validate
// NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
// using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
// and configured for older versions.
String url = null;
if (isSandbox){
url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
}else{
url = "https://www.paypal.com/cgi-bin/webscr";
}
log.error("La url de a la que redirigimos a Paypal es " + url);
URL u = new URL(url);
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
log.error("Tras abrir la conexión, res es = " + res);
// assign posted variables to local variables
String idUser = request.getParameter("custom");
String idCompra = request.getParameter("invoice");
String paymentStatus = request.getParameter("payment_status");
String paymentAmount = request.getParameter("mc_gross");
String fee = request.getParameter("mc_fee");
String paymentCurrency = request.getParameter("mc_currency");
String txnId = request.getParameter("txn_id");
String receiptId = request.getParameter("receipt_id");
String receiverEmail = request.getParameter("receiver_email");
String payerEmail = request.getParameter("payer_email");
String paymentType = request.getParameter("payment_type");
String txnType = request.getParameter("txn_type");
if (!"instant".equals(paymentType) || !"cart".equals(txnType)) {
log.debug("NO ES UN CART CHECKOUT. Detalles:");
log.debug("idCompra=" + idCompra);
log.debug("status=" + paymentStatus);
log.debug("amount=" + paymentAmount);
log.debug("currency=" + paymentCurrency);
log.debug("transactionId=" + txnId);
log.debug("receiptId=" + receiptId);
log.debug("receiverEmail=" + receiverEmail);
log.debug("payerEmail=" + payerEmail);
log.debug("paymentType=" + paymentType);
log.debug("txnType=" + txnType);
return;
}
**//HERE THE RESPONSE IS INVALID IN LIVE MODE**
if (res != null && res.equals("VERIFIED")) { //res = "VERIFIED" res = "INVALID"
// more code not important for this issue....
Any idea? As I said, payments are completed but the IPN is sended INVALID.
I know this is old but it might help someone else, I think you need to POST the data for validation.
According to Paypal IPN Docs:
//After receiving an IPN message from PayPal,
//you must respond to PayPal with a POST message
//that begins with "cmd=_notify-validate".
//Append to your message a duplicate of the
//notification received (the same IPN fields
//and values in the exact order you received them)
...
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setRequestMethod("POST");
...
To receive IPN message data from PayPal, your listener must follow this request-response flow:
1.Your listener listens for the HTTPS POST IPN messages that PayPal sends with each event.
2.After receiving the IPN message from PayPal, your listener returns an empty HTTP 200 response to PayPal. Otherwise, PayPal resends the IPN message.
3.Your listener sends the complete message back to PayPal using HTTPS POST.
Prefix the returned message with the cmd=_notify-validate variable, but do not change the message fields, the order of the fields, or the character encoding from the original message.
Send response messages back to PayPal:
https://ipnpb.sandbox.paypal.com/cgi-bin/webscr (for Sandbox IPNs)
https:/ipnpb.paypal.com/cgi-bin/webscr (for live IPNs)
for more info see also:
https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNImplementation/#specs

server cookie = null

I am doing authentication and receiving a null cookie. I want to store this cookie but sever is not returning me a cookie. But the response code is 200 ok.
httpConn.setRequestProperty(
"Authorization",
"Basic " + Base64OutputStream.encodeAsString(
login.getBytes(), 0, login.getBytes().length, false, false));
String tmpCookie = httpConn.getHeaderField("set-cookie");
This is my code.
String login = username + ":" + password;
String base = "http://mysever/login";
HttpConnection httpConn = null;
httpConn = (HttpConnection)Connector.open(base);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpsConnection.POST);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml,application/x-javascript,*/*;q=0.5 ");
//Add the authorized header.
httpConn.setRequestProperty("Authorization",
"Basic " + Base64OutputStream.encodeAsString(
login.getBytes(), 0, login.getBytes().length, false, false));
message = httpConn.getResponseMessage();
status = httpConn.getResponseCode();
tmpCookie = httpConn.getHeaderField("Set-Cookie");
EventLogger.logEvent(guid, status);
if (status == HttpConnection.HTTP_OK)
{
String tmpCookie = httpConn.getHeaderField("set-cookie");
authForm.append("\nConnected");
authForm.append("\n\nLogin Response:" + message +
"\nHTTP response code:" + status + "\nCookie: "
+ tmpCookie);
//getNewZipFile();
}
else if(status !=HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: " + status);
}
httpConn.close();
Have you actually made a connection? Your code shows you setting a request property and then immediately trying to find a header value, with no indication that the request has actually been sent.
If you are doing so (in which case fuller code would be welcome) you should use Wireshark or something similar to find out what the network traffic actually looks like.
How request Authorization header connected with response Cookie?
I suppose that it is in no way.
May be server doesn't return any cookies? Or may be "set-cookie" is case sensitive, and you must use "Set-Cookie" instead.

Categories

Resources