Since few days I'm trying to implement the iOS in-app purchase verification on the beforeSave of a purchase (on sandbox), but it always fail.
I tried the receipt with postman, and it works.
So, it's the Parse.Cloud.httpRequest the problem.
I tried also to put the receipt directly in the Cloud Code and it's always the same error (21002). https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
Here is my code :
Parse.Cloud.httpRequest({
method: 'POST',
url:'https://sandbox.itunes.apple.com/verifyReceipt',
body:{'receipt-data':receipt},
success: function (httpResponse) {
console.log(httpResponse.text);
if (httpResponse.status == 0) {
// success
} else {
// error
}
},
error: function (httpResponse) {
// error
}
});
Is there someone that did it?
If this a auto-renewal subscription?
If so, you missed the password field:
password Only used for receipts that contain auto-renewable
subscriptions. Your app’s shared secret (a hexadecimal string).
in the jsonBody:
var jsonBody = {
"receipt-data" : reference,
"password" : "xxxxx"
};
Also you should JSON encode the POST BODY (node example in the following)
itunes_client.post("", {}, JSON.stringify(jsonBody),
Related
I seem to be stuck on this. Trying to validate the receipt (server side) on an in-app purchase on IOS (haven't tried with android, yet.)
I'm using the official in_app_purchase pub package.
This is the setup to initialize the purchase:
Future<bool> initiatePurchase() async {
...
(verify store is available)
..
print ("==> Store available, initiating purchase");
final PurchaseParam purchaseParam =
PurchaseParam(productDetails: _productDetails![0]);
await InAppPurchase.instance.buyNonConsumable(purchaseParam: purchaseParam);
return true;
}
Here's my verify purchase call:
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
PurchaseVerifRest purchaseRest = PurchaseVerifRest();
Map<String,dynamic> rsp = await purchaseRest.verifyPurchase(
{
"source": purchaseDetails.verificationData.source,
"vfdata": purchaseDetails.verificationData.serverVerificationData
});
// bundle up the source and verificationData in a map and send to rest
// call
return rsp['status'] == 200;
}
On the server side, the code looks like this (NodeJS/express app)
// (in router.post() call - 'purchaseData' is the map sent in the above code,
// the 'vfdata' member is the 'serverVerificationData'
//. in the 'purchaseDetails' object)
if (purchaseData.source == ('app_store')) {
const IOS_SHARED_SECRET = process.env...;
let postData = {
'receipt-data': purchaseData['vfdata'],
'password': IOS_SHARED_SECRET
};
try {
let verif_rsp = await execPost(postData);
retStatus = verif_rsp.statusCode;
msg = verif_rsp.data;
} catch (e) {
retStatus = e.statusCode;
}
}
What I get back, invariably is
210003 - Receipt could not be authenticated
... even though the purchase seems to go through, whether I validate or not.
Details/questions:
Testing with a sandbox account.
This is for a 'non-consumable' product purchase.
I'm assuming that purchaseDetails.verificationData.serverVerificationData is the payload containing the receipt to send to Apple for verification. Is this not correct? Is there another step I need to do to get the receipt data?
I've read in other posts that the verification step is only for recurring subscriptions and not for other types of products. Is this correct? I don't see anything in Apple's docs to indicate this.
Any thoughts appreciated.
I am trying to implement SSO in a mobile app.
I am using react-native-inappbrowser-reborn to handle the SSO auth flow in an in-app browser. I can successfully authenticate inside the in-app browser. That is to say, I receive a session cookie and I can view the web version of the app from inside of the in-app browser. However, when I redirect back to the mobile application, none of my fetch requests include the session cookie! I have fetch configured with {credentials: 'include'}. CookieManager.getAll() returns an empty object.
I am experiencing this problem on iOS (v15.2), and I have yet to test on Android.
According to the documentation I should be able to share the cookie set in the in the in-app browser with my react-native app.
I am using the following code based off of the react-native-inappbrowser-reborn documentation
async function authenticate() {
const url = 'http://localhost:3000/sso/login?redirect_uri=myapp://home';
const deepLink = 'myapp://home';
try {
if (await InAppBrowser.isAvailable()) {
InAppBrowser.openAuth(url, deepLink, {
// iOS Properties
ephemeralWebSession: false,
// Android Properties
showTitle: false,
enableUrlBarHiding: true,
enableDefaultShare: false,
}).then(async (response) => {
if (response.type === 'success' && response.url) {
console.log('should see a new cookie set!');
console.log(await CookieManager.getAll()); // Sadly, nothing in here
const user = await fetch('http://localhost:3000/user', {
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
/* This is an authenticated endpoint which returns a 401,
because for some reason the session cookie doesn't go along with the request */
}
});
} else {
throw new Error('login unsuccessful');
}
} catch (error) {
throw new Error();
}
}
Any bit of insight here would be immensely appreciated!
I'm trying to Integrate Apple Pay in my application. Following the online docs and some SO help, I've managed to show the Apple Pay payment dialog and all the call backs are configured.
the response returned from the Apple Pay is something like this
{
"version": "RSA_v1",
"signature": "somestring",
"data": "DP...A=",
"header": {
"wrappedKey": "MF...5g==",
"publicKeyHash": "kd...l4=",
"transactionId": "a5...3e"
}
}
But my requirement is to get ephemeralPublicKey under header object. According to Apple Pay Payment Token Format Reference
the returned object is correct as its RSA_v1 version which will not have ephemeralPublicKey but wrappedKey. Now my question is how do i get EC_v1 version of the returned token object.
May be I'm missing something here in the docs but please someone point me to the right direction. Any help is appreciated.
Here is the way to get this returned response from the Apple Pay Gateway server. You can't see this response in the console directly. You can see this response only if you will log it on the server by using an ajax request. See mine below sample URL and my source code.
Full Documentation for beginners
https://gist.github.com/jagdeepsingh/c538e21f3839f65732a5932e35809d60
session.onpaymentauthorized = (event) => {
$("#paymentMethodVal").val("apple-pay");
$form = $("#reservation-form");
console.log($form.serialize());
callRequest({
url: '/reserve/init-apple-pay',
method: 'POST',
data: {
token: event.payment.token,
reservationData: $form.serialize()
},
beforeRequest: function(e) {},
afterRequest: function(response) {
response = JSON.parse(response);
if(response.status){
toastr.success(response.message);
session.completePayment(ApplePaySession.STATUS_SUCCESS);
}else{
toastr.error(response.message.split(/\r\n|\r|\n/g).join('<br/>'));
session.completePayment(ApplePaySession.STATUS_FAILURE);
}
}
});
};
token: event.payment.token, line is your answer this will send data directly to server and you can log data over there.
{
"version": "RSA_v1",
"signature": "somestring",
"data": "DP...A=",
"header": {
"wrappedKey": "MF...5g==",
"publicKeyHash": "kd...l4=",
"transactionId": "a5...3e"
}
}
I've read here that it's possible to send an IPN directly to a Google cloud function. I have my Google Cloud functions running on Firebase on an index.js file.
I've set up my Paypal buttons to send the IPN to a page on my webapp.
Here is an example of one of the functions I'm running off Google Cloud Functions/Firebase:
// UPDATE ROOMS INS/OUTS
exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
const beforeData = change.before.val();
const afterData = change.after.val();
const roomPushKey = afterData.inRoom;
const insbefore = beforeData.ins;
const insafter = afterData.ins;
if ((insbefore === null || insbefore === undefined) && (insafter === null || insafter === undefined) || insbefore === insafter) {
return 0;
} else {
const updates = {};
Object.keys(insafter).forEach(key => {
updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
});
return admin.database().ref().update(updates); // do the update}
}
return 0;
});
Now question:
1) I want to add another function to process IPN from Paypal as soon as I have a transaction. How would I go about this?
I'll mark the answer as correct if solves this first question.
2) how would that Google cloud function even look like?
I'll create another question if you can solve this one.
Note I am using Firebase (no other databases nor PHP).
IPN is simply a server that tries to reach a given endpoint.
First, you have to make sure that your firebase plan supports 3rd party requests (it's unavailable in the free plan).
After that, you need to make an http endpoint, like so:
exports.ipn = functions.http.onRequest((req, res) => {
// req and res are instances of req and res of Express.js
// You can validate the request and update your database accordingly.
});
It will be available in https://www.YOUR-FIREBASE-DOMAIN.com/ipn
Based on #Eliya Cohen answer:
on your firebase functions create a function such as:
exports.ipn = functions.https.onRequest((req, res) => {
var reqBody = req.body;
console.log(reqBody);
// do something else with the req.body i.e: updating a firebase node with some of that info
res.sendStatus(200);
});
When you deploy your functions go to your firebase console project and check your functions. You should have something like this:
Copy that url, go to paypal, edit the button that's triggering the purchase, scroll down to Step 3 and at the bottom type:
notify_url= paste that url here
Save changes.
You can now test your button and check the req.body on your firebase cloud functions Log tab.
Thanks to the answers here, and especially to this gist: https://gist.github.com/dsternlicht/fdef0c57f2f2561f2c6c477f81fa348e,
.. finally worked out a solution to verify the IPN request in a cloud func:
let CONFIRM_URL_SANDBOX = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
exports.ipn = functions.https.onRequest((req, res) => {
let body = req.body;
logr.debug('body: ' + StringUtil.toStr(body));
let postreq = 'cmd=_notify-validate';
// Iterate the original request payload object
// and prepend its keys and values to the post string
Object.keys(body).map((key) => {
postreq = `${postreq}&${key}=${body[key]}`;
return key;
});
let request = require('request');
let options = {
method: 'POST',
uri : CONFIRM_URL_SANDBOX,
headers: {
'Content-Length': postreq.length,
},
encoding: 'utf-8',
body: postreq
};
res.sendStatus(200);
return new Promise((resolve, reject) => {
// Make a post request to PayPal
return request(options, (error, response, resBody) => {
if (error || response.statusCode !== 200) {
reject(new Error(error));
return;
}
let bodyResult = resBody.substring(0, 8);
logr.debug('bodyResult: ' + bodyResult);
// Validate the response from PayPal and resolve / reject the promise.
if (resBody.substring(0, 8) === 'VERIFIED') {
return resolve(true);
} else if (resBody.substring(0, 7) === 'INVALID') {
return reject(new Error('IPN Message is invalid.'));
} else {
return reject(new Error('Unexpected response body.'));
}
});
});
});
Also thanks to:
https://developer.paypal.com/docs/classic/ipn/ht-ipn/#do-it
IPN listener request-response flow: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNImplementation/
To receive IPN message data from PayPal, your listener must follow this request-response flow:
Your listener listens for the HTTPS POST IPN messages that PayPal sends with each event.
After receiving the IPN message from PayPal, your listener returns an empty HTTP 200 response to PayPal. Otherwise, PayPal resends the IPN message.
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.
Extremely late to the party but for anyone still looking for this, PayPal have made a sample in their JS folder on their IPN samples Github repo.
You can find this at:
https://github.com/paypal/ipn-code-samples/blob/master/javascript/googlecloudfunctions.js
I am trying to implement push to my app.
I've followed this guide:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-ios-get-started-push/
However, I am using API's instead of the Data-scripts, so in one of my API methods I am doing this:
var push = request.service.push;
push.apns.send(null, {
alert: "Alert",
payload: {
inAppMessage: "Hey, a new item arrived"
}
}, {
success: function(resp) {
console.log(resp)
},
error: function(err) {
console.error(err)
}
});
My log is showing this (So I land in the success-method [Also I know that I should never land in error for iOS due to apples push server not responding with error]):
{ isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
'content-type': 'application/xml; charset=utf-8',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Mon, 20 Oct 2014 11:31:21 GMT' },
md5: undefined }
My app is registered correctly like this, I see the callback message and no error:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)deviceToken
{
[client.push registerNativeWithDeviceToken:deviceToken tags:#[#"uniqueTag"] completion:^(NSError *error)
{
NSLog(#"registerNativeWithDeviceToken callback");
if (error != nil)
{
NSLog(#"Error registering for notifications: %#", error);
}
}];
}
But no push message land in my iphone! Nothing is happening.
Im trying to check for errors in my Notification Hub but I see no log there.
What am I missing? I really don't get it where my actual device id is stored server side anyway. I must be missing something.
Thank you!
The best way to debug what is occurring is to follow the Notification Hub debugging steps here: http://msdn.microsoft.com/en-us/library/azure/dn530751.aspx
I would begin by using Service Bus Explorer to double-check the registration has the device token and tags you expect. After verifying that, please test sending an alert directly via the Notification Hub portal. If you still have issues, please send me an email at toddreif#microsoft.com.
Use your debug menu in Azure as #Todd Reifsteck said, and please test the tag name both "myTag" and myTag while debugging.