cordova facebookConnectPlugin and publish_actions permission - android

I have to update our app from using the v1 graph api and sdk methods to v2.X.
I have downloaded the latest facebookConnect plugin found here
I need to get the user to login to allow our app to post to the users timeline. Before i have to request publish_scope permission, but this has now changed to publish_actions.
I have tried this code, but apparently you cannot request publish_actions straight away so you have to break it up, and request public_profile first, then publish_actions. I get this message when trying to do public_profile and publish_actions at the same time
Cannot pass a publis or manage permission (publish_actions) to a
request for read authorization
So my code looks like this, but i dont think i am doing it right? Do i need the second login call? Should i be using another method? Also if the user says "Not now" to the publish_actions permission, there doesnt seem to be a way to handle it, because the success method is called?
Here is some code
$(this).find('#imgFacebook').on("tap", function (e) {
e.preventDefault();
var onError = function(msg, e) {
console.log(msg + JSON.stringify(e));
logout();
};
var requestPublishPermissions = function(f) {
console.log('requesting publish permission...');
facebookConnectPlugin.login(['publish_actions'], function(e) {
console.log('Permission granted: ' + JSON.stringify(e));
if (e.authResponse) {
// user has logged in and allowed permissions!! YAY
} else {
alert('There was an error logging you in to facebook, or you did not authorize the app to post on your wall');
}
}, function(e) {
onError('Permission denied: ', e);
});
};
var login = function() {
console.log('logging in...');
facebookConnectPlugin.login(['public_profile'], function(e) {
console.log('logged in successfully: ' + JSON.stringify(e));
requestPublishPermissions(e);
}, function(e) {
if (e.errorMessage != 'User cancelled dialog') {
alert('There was an error logging you in to facebook: ' + JSON.stringify(e));
}
onError('login error: ', e);
});
};
var logout = function(success) {
// check that knowone is logged in
facebookConnectPlugin.getLoginStatus(function(e) {
console.log('status is: ' + JSON.stringify(e));
if (e.authResponse && e.status == 'connected') {
console.log('logging out...');
facebookConnectPlugin.logout(function() {
console.log('logout successful...');
if (success) success();
}, function(e) {
console.log('error logging out: ' + JSON.stringify(e));
if (success) success();
});
} else {
// know one logged in
if (success) success();
}
}, function(e) {
if (success) success();
})
};
logout(login);
});
Because i do not want to save the users details on the application, i make sure that logout is called first, and then log the user is.
Anyone got any pointers?

Related

Expo InAppPurchases connectAsync returns undefined

I'm having issues trying to get the InAppPurchases to work in my React Native app using Expo. https://docs.expo.io/versions/latest/sdk/in-app-purchases
This is a bare workflow app that I ejected from a standard Expo app.
I made sure to follow the install instructions here carefully: https://docs.expo.io/bare/installing-unimodules/
I did test if unimodules was properly installed:
import { Constants } from "react-native-unimodules";
useEffect(() => {
alert("installed: " + JSON.stringify(Constants.systemFonts));
}, []);
The code above worked.
I'm using react-native-unimodules version 0.11.0.
Here's my code:
useEffect(() => {
(async function init() {
try {
const connect_res = await connectAsync();
alert("connect: " + JSON.stringify(connect_res));
} catch (err) {
alert("general error for connect async: " + err);
}
})();
}, []);
This is in the App.js entrypoint file. It always returns undefined for the connect_res so I assume this is the reason why I couldn't get any of the code to work.
Just below connectAsync() I have the following. This one also doesn't return anything:
setPurchaseListener(({ responseCode, results, errorCode }) => {
if (responseCode === IAPResponseCode.OK) {
results.forEach((purchase) => {
if (!purchase.acknowledged) {
alert("purchase successful!");
finishTransactionAsync(purchase, true);
}
});
}
if (responseCode === IAPResponseCode.USER_CANCELED) {
alert("user cancelld!");
} else if (responseCode === IAPResponseCode.DEFERRED) {
alert("user does not have permission to buy");
} else {
alert("something went wrong: " + errorCode);
}
});
Then on my payment screen I have the following:
import { getProductsAsync, purchaseItemAsync } from "expo-in-app-purchases";
This is the code for the payment button:
const makePayment = async () => {
alert("now making payment...");
try {
const items = Platform.select({
ios: ["abc"],
android: ["my-sub-id", "sku-my-sub-id"],
});
alert("items: " + JSON.stringify(items));
const products = await getProductsAsync(items);
alert("products: " + JSON.stringify(products));
if (products.results.length > 0) {
alert("found products!");
await purchaseItemAsync("my-sub-id");
alert("done making payment!");
} else {
alert("no products..");
}
} catch (err) {
alert("error occured while trying to purchase: " + err);
}
};
In this case, getProductsAsync() does return something resembling the format the results should be. But it doesn't return any of the subscriptions I created (I copied the product ID value listed in that column and I supplied it to both getProductsAsync and purchaseItemAsync. I also supplied the url version which basically just has a prefix of sku-:
I also enabled licensing testing for the email I'm using in Google Play:
Do note that I'm uploading the .aab file to Google Play on the internal testing track then I install it using this URL format: https://play.google.com/apps/test/com.myname.appname/versionNumber
But when I open that link, it seems like google play is detecting it as an old version even though its the latest one. The changes I've made shows up though so I'm pretty sure that's the correct install URL.
What else could I be missing?
For anyone having the same problem. all you have to do is add this on your android/app/src/main/AndroidManifest.xml file:
<uses-permission android:name="com.android.vending.BILLING" />
It wasn't mentioned in the docs at the time of this post, and it doesn't get automatically added when you install a module. Might help save you the headache if you assume the same is true for all Expo modules.

Desperately need help for Firebase - Push Notifications

I’m trying to develop Firebase - Push Notifications with Framework7. I have installed the plugin by checking $ cordova plugin list
cordova-plugin-fcm 2.1.2 “FCMPlugin”
I have registered the app on the Firebase Console and have no idea whether this code is correct or not (it’s inside the app.js)
onDeviceReady: function() {
// JScript for the main app, once PGap has loaded.
//checkDeviceSize(); (WILL RE-CODE IN A CSS FRIENDLY FORMAT)
document.addEventListener(“offline”, onOffline, false);
document.addEventListener(“online”, onOnline, false);
setTimeout(function() {
navigator.splashscreen.hide();
}, 1000);
var pushtoken;
initFCM();
getToken();
},
then, at the bottom of file app.js, I put the function
function initFCM() {
console.log("initializing...");
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.onTokenRefresh(function(token){
pushtoken = token;
app.dialog.alert('onTokenRefresh:', token);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
FCMPlugin.onNotification(function(data){
if(data.wasTapped){
app.dialog.alert(JSON.stringify(data));
}else{
app.dialog.alert(JSON.stringify(data));
}
}, function(msg){
app.dialog.alert('onNotification callback successfully registered: ' + msg);
}, function(err){
app.dialog.alert('Error registering onNotification callback: ' + err);
});
}
}
function getToken() {
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.getToken(function(token){
pushtoken = token;
app.dialog.alert('getToken:', token);
if (!token) setTimeout(getToken, 1000);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
}
}
Would be very grateful if you can show how to manage this code inside app.js
Many thanks

Facebook Plugin not working in ionic 1

I am developing an app from ionic-1. I also implemented facebook login plugin. I've followed this steps. I have no errors, but when I click on the facebook button, it doesn't work, no errors displaying. I use alert in every error catch but no alert will be displayed.
NOTE: I am running in an real android device because they said that native plugin will not work in browser.
Please help me because Im working with my thesis. Thanks to all of you!
Here's my code:
.controller('CreateAccountCtrl', ['$scope','$http','$state','$q','UserService','$stateParams', '$ionicLoading','$timeout','$ionicPopup',function($scope, $http,$state,$q, UserService,$stateParams,$ionicLoading,$timeout,$ionicPopup){
$scope.$on('$ionicView.beforeEnter', function(e){
$ionicLoading.show({
animation: 'fade-in', showBackdrop: true
});
});
$scope.$on('$ionicView.afterEnter', function(e){
$ionicLoading.hide();
$scope.formData = {};
$scope.showAlert = function(ttl,msg){
var alertPopup = $ionicPopup.alert({
title: ttl,
template: msg
});
};
});
// facebook
// This is the success callbak from the login method
var fbLoginSuccess = function(response){
if(!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo){
// store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture: "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.home');
}, function(fail){
alert(fail);
// Fail get profile info
console.log('Profile Info Fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
alert(error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function(authResponse){
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function(response){
alert(response);
console.log(response);
info.resolve(response);
},
function(response){
console.log(response);
alert(response);
info.reject(response);
}
);
return info.promise;
};
// This method is executed when the user press the "Login with faceboook" button
$scope.facebookSignIn = function(){
alert(1);
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
alert(success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo){
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.home');
}, function(fail){
console.log('Profile info fail', fail);
alert(fail);
});
}else{
$state.go('app.home');
}
}else{
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
alert(success.status);
$ionicLoading.show({
template: 'Logging in...'
});
facebookConnectPlugin.login(['email','public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
}]);
And in my html
<a class="facebook-sign-in button button-block button-facebook" ng-click="facebookSignIn()">
<i class="icon ion-social-facebook"></i>
Sign in using facebook
</a>
APP_NAME="must be facebook application name that's created on facebook developer not your app name"
APP_ID=facebook app id.
Install with facebook v4
$ cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="123456789" --variable APP_NAME="myApplication"
$rootScope.loginFacebook = function() {
$cordovaFacebook.login(["public_profile", "email", "user_birthday", "user_photos"]).then(function(success){
console.info(success.status);
if (success.status === 'connected') {
var checkrequest = {
'AuthSession[device_token]': $localStorage.device_token
}
appname.check(checkrequest).then(function(response) {
console.log(response);
if (response.key == "NOAUTH") {
$state.go('main.allowPush')
}
})
} else if (success.status === 'not_authorized') {
console.info('the user is logged in to Facebook but has not
authenticated your app')
} else {
console.info('the user is nott logged in to Facebook')
}
}, function(error) {
console.info(error);
});
}

Appcelerator/ Titanium: Cannot send push notification to Android

I want to be able to send push notifications using Titanium and Arrow Push on Android.
I have followed the instructions here:
Configuring Push Services
Subscribing to push notifications
Modules.CloudPush
My simple code looks as follows:
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
// Works fine
CloudPush.retrieveDeviceToken({
success: function () {
deviceToken = e.deviceToken;
alert('deviceToken: ' + deviceToken);
subscribeToChannel();
},
error: function () {
alert('Failed to register for push notifications! ' + e.error);
}
});
// Never runs!!!
CloudPush.addEventListener('callback', function (evt) {
Ti.API.info('New notification!');
alert("Notification received: " + evt.payload);
});
// Works fine
function subscribeToChannel () {
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'general',
type: Ti.Platform.name
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
Most of the above code is similar to the docs. The subscription aspect of the code seems to works perfectly fine, as the user's device also appears in the devices section of the Appcelerator Dashboard.
However when it comes to sending a notification, from the Appcelerator Dashboard, the word "Failure" appears next to my Android device.
The full error message when highlighting the "?" icon is as follows:
Exception Type: GCM; Error Code: 3103; Error Message:
RegistrationId(s) is null or empty; Catched Exception: argument cannot
be null
I looked this error up on http://docs.appcelerator.com/arrowdb/latest/#!/guide/troubleshooting and all it says is:
The GCM client provided a null or empty registration ID. This error is
uncommon if you are using the Modules.CloudPush module.
Which isn't helpful.
What am I doing wrong? Is this a bug on Accelerator side.
Turns out my code was fine. The credentials I was using however was incorrect. Please see my other related question here:
Appcelerator/ Titanium: Getting Android credentials to push notifications
The docs are in need of updating.
I'm hardly an expert with push, but I compared what you have to what I have in one of my apps.
Pretty sure you need to send the deviceToken into the subscribeToChannel function.
Try changing this -
function subscribeToChannel () {
to this -
function subscribeToChannel (deviceToken) {
then add the token to the call here -
subscribeToChannel (deviceToken);
Let me know if that works for you.
-Jon
On subscribeToChannel() function, you should use type : 'gcm' instead of type: Ti.Platform.name
This is a commonJS module that I created for my Android push:
function ACSPush(_callback) {
var debug_mode = true;
var Cloud = require('ti.cloud');
var CloudPush = require('ti.cloudpush');
CloudPush.enabled = true;
var deviceToken;
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
if(debug_mode)
Ti.API.info('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
if(Ti.App.Properties.getString("deviceToken") != deviceToken.toString()){
defaultSubscribe();
};
},
error : function deviceTokenError(e) {
if(debug_mode)
Ti.API.info('deviceTokenError.. :( ' + e.error);
}
});
function defaultSubscribe() {
Cloud.PushNotifications.subscribeToken({
channel : 'MyChannel',
device_token : deviceToken,
type : 'gcm'
}, function(e) {
if(e.success) {
if(debug_mode)
Ti.API.info("Success registerForPushNotifications");
Ti.App.Properties.setString("deviceToken", deviceToken.toString());
} else {
if(debug_mode)
Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
};
});
};
CloudPush.addEventListener('callback', function(evt) {
var payload = JSON.parse(evt.payload);
if(debug_mode){
Ti.API.info("Received a push notification\nPayload:\n" + JSON.stringify(evt.payload));
Ti.API.info("payload: " + payload);
};
_callback(payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Focused App (app was already running)');
});
};
module.exports = ACSPush;
Obviously, you must first configure Android Push Service http://docs.appcelerator.com/platform/latest/#!/guide/Configuring_push_services-section-src-37551713_Configuringpushservices-ConfiguringpushservicesforAndroiddevices

Cordova / Android - Can't login with Facebook

I am trying to log my users with Facebook, but can't figure out how to do it.
This is the code I have so far :
facebookConnectPlugin.getLoginStatus(
function(status) {
if (status.status != "connected") {
facebookConnectPlugin.login(
['public_profile', 'email'],
function(success) {
console.log("Success", success);
},
function(error) {
console.log("Error", error);
}
);
}
else {
console.log("logging status : ", status.status);
}
},
function(error) {
console.log("Getting logging status failed : ", error);
}
);
On my Android device, I do not have the Facebook app installed, and I am not logged into Facebook on any browser.
I would expect the facebookConnectPlugin.login() method to popup the login form, but instead this is what it returns :
Which basically means : "You did not enter. You are not connected to Facebook. Enter Facebook and try again".
I looked into this Meteor plugin to see how they were doing it, but they respect the exact same logic.
I am not sure what to do from here. Any suggestion is most welcome !
you can try code for get Login Status read more here
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getLoginStatus(
function (status) {
alert("current status: " + JSON.stringify(status));
}
);
};
you can try code for get User Profile.
facebookConnectPlugin.login( ["public_profile","email"],
function (response) {
if(response.authResponse.userID!=''){
facebookConnectPlugin.api(response.authResponse.userID+"/?fields=id,email,first_name", ["public_profile"],
function (response) {
console.log('SUCCESS:'+response);
alert('first_name : '+response.first_name+',email:'+response.email+',id:'+response.id);
},
function (response) {
console.log('ERROR:'+response);
});
}
},
function (response) {
console.log('ERROR:'+response);
});
let me know if its not working...

Categories

Resources