Add image to expo push notifications - react-native

I want to send an expo push notification that would look like this :
That is to say add to the right of the notifications an image.
This is my code to generate notifications at the moment :
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-Encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify({
to: tokens,
sound: 'default',
badge: 1,
title: "Actualité !",
body: `${title} - ${commerce.name}`,
}),
});
I can only add a title and a body but not an image...
How could I manage to do this ?

This fixed my problem. Maybe this will help yours too.
Here is the array:
(
'to' => $req->device_token,
'notification' => [
'body' => $req->text,
'title' => $req->title,
'text' => $req->text,
'sound' => 'default',
'image' => $req->image
],
'data' => [
'item_type' => $req->type,
'item_type_id' => $req->id,
'click_action' => 'FLUTTER_NOTIFICATION_CLICK'
],
'priority' => 'high',
)

Related

Status failed error get after enter card input in network international ngenius payment in react native?

First we create sandbox account from https://www.network.ae/en/contents/listing/online-solutions#book-1
then we create access Token see code
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/vnd.ni-identity.v1+json");
myHeaders.append("Authorization", `Basic ${}API_KEY`);
myHeaders.append("Cookie", "\_abck=5C342393A623B53581D9AE558C857BF2\~-1\~YAAQfXYsMa+W3wWFAQAACGk7MwlNL93fTExvJYX4pRpd6PZpRFbRT0BgePfZ2tn15MkLCVst80XVExP/xPZkPh0LUZq4QO4k+KN0bm+Tz0NlX26lWmSlI6mq0kePXMH9MJt7yQy7Rx9ZIsR2Amcb44zP+hnySdCx2uq3vwgl4ZVMQ2soqosGNHQuESjb/JJAirysYwiyN7/Mw/qg5NzXzf2ncRTbB/3CcVp/yiZPOwAsxD8x+8oZA3VAxLgvbuv0Tn9ccNN9oPATqzDtoXD1LnQorof6S/S6btPx4BZTgFeqvmxX3q5SNSlsDgySTzI5qkp81wrjTm5ficp1U0k5fcimfaR0V8Xq21luPY9VdveWYd5B87UOIcalA2CQz2S7yFSo14uqKarLVFbh00Vd1Zw=\~-1\~-1\~-1; bm_sz=AF5FEAEE5BC3A58968E80BB8D640735E\~YAAQfXYsMbCW3wWFAQAACGk7MxLpffLMR5ZpUagjSJqRS4G5rjc8MolC2xNhZUaUKTKGMj5Fvi0eLn3cbULd/jtI4QO0h8Cl4c3bFROSPs9jpPu1UFDm9R1gGBB6T7rIFPU+sxiw2wQ7gGvrlik680yFDoUraO3MoRl8cfpOu73nyKryhpb1ebghFcrF2aYM9B4f3c8ER1Fk1VTXN5TGij9bLAT7BDjVOtLjQVG5AL/wKZ57t21EFnCqlnXioDXla8Jylj6T7EQzE/5yKno2Z9Z6jMTx1rU6Jcy5nUq6SG50aVYOUYwA/w1k6WSj\~3749186\~4343095");
var raw = "";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token", requestOptions)
.then(response => response.json())
.then(result => {
setAccessToken(result.access_token)
})
.catch((e)=>console.log(e)
Then we create an order
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
myHeaders.append("Content-Type", "application/vnd.ni-payment.v2+json");
myHeaders.append("Accept", "application/vnd.ni-payment.v2+json");
myHeaders.append("Cookie", "_abck=5C342393A623B53581D9AE558C857BF2~-1~YAAQJfhWuMbikwmFAQAAm3R2KgkBO6swEeKoHNG6113OL/hvGd9LQQEo5ieCnty0rrZ7UcaRqt7InR2UUWFze7723wDPiy+SCmtMNKKL4zCJi7fwqJed1SMa2PWjCe5qWiFf/Fa0NtMY3a7TedM+6XI3cMMieW4GMHrQwGTz0BrFsZ3gC6jCUgYUTFO55uMpD3627GjbcZmsluCPLWKVLdGlsPX/wIknh1Tl/+YSO58Bnv97KpZnb0ZLZck2PYFnzGOPTiJ2JQe6vakvSFh68UxMIZYVxekwS2LTZjJGtZqLMt45A/lLbpxq95qzzCMWdxrwE0JgMgWfgu9l1k+Scq69UpgOo331AEJ+AASZF1MZ4CRJ7MEs1WpjlTbDroZVS0Uh~-1~-1~-1");
var raw = JSON.stringify({
"action": "PURCHASE",
"amount": {
"currencyCode": "AED",
"value": 2000
},
"emailAddress": "govindsingh#gmail.com",
"merchantOrderReference":"my-order",
"billingAddress":{
"firstName":"Govind",
"lastName":"Singh",
"address1":"abc",
"city":"Dubai",
"state":"Dubai",
"countryCode":"AED"
},
"merchantAttributes":{
"skipConfirmationPage":true,
"skip3DS":true
}
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch(`https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/${Outlet_id}/orders`, requestOptions)
.then(response => response.json())
.then(result => {
setOrder(result.access_token)
})
.catch((e)=>console.log(e)
then we call make card payment function by https://www.npmjs.com/package/#network-international/react-native-ngenius
const res = await initiateCardPayment(order);
console.log("res"+ res)
Alert.alert(
'Success',
'Payment was successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
} catch (err) {
console.log(err);
alert(
'Error',
'Payment was not successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
}
then we get an error -
[status:failed]
Thanks in Advance
Please give me any solution

Error: Request failed with status code 400 in react-native with axios

axios({
method: 'POST',
url: `http://${base_url}/token`,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: {
"Username": "admin#diginepal.com",
"Password": "password#123456",
"grant_type": "password"
}
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
I'm getting err: request failed with status code 400. What am I doing wrong here?
data: qs.stringify({
"Username": "admin#diginepal.com",
"Password": "password#123456",
"grant_type": "password"
})
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
using qs and changing the headers solved my problem.
Good that you managed to solve, for future reference, if you have a 400 Bad Request error, i found really useful to print the error.response.data for more meaningful error messages.
axios.post('/').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.response.data);
});

POST request body with filters in react native

I want to add filters in my request so that I only get my datas when the filter is true.
Unfortunatly, my code doesn't run and I don't know why
mySuperFunction() {
fetch('myhttps', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: {
bool: {
filter: [{ term: { mySuperTerm: true } }],
},
},
size: 1000,
}),
})
.then(response => response.json())
.then(json => {
if (json.found) {
console.log(JSON.stringify(json, null, 4));
}
else {
console.log('error');}
})
What I want to extract is all datas when my filter = true:
"data": {
"name": "eddy",
"city": "london",
"mySuperTerm": true,
}
Do you mean you get no error back at all? Nothing happening?
Wrap Accept in single quotes.
Sorry, it seems to be a bug from react native
See this github issue

React Native video file upload

I am currently uploading videos and images using base64 encoding but it was highly recommended to use an alternative to this. I am using RNFetchBlob to read the encoded file and then attach it to SuperAgent for uploading. I have seen some examples of using FormData to attach the file but cannot find a complete working example. If someone could provide a code example on how to achieve this I would greatly appreciate it.
RNFetchBlob.fs.readFile(filePath, 'base64')
.then((base64data) => {
let base64Image = `data:video/mp4;base64,${base64data}`;
let uploadRequest = superagent.post(uploadURL)
uploadRequest.attach('file',base64Image)
Object.keys(params).forEach((key) => {
uploadRequest.field(key,params[key])
})
uploadRequest.on('progress', function(e) {
this.props.setVideoUploadProgress(e.percent)
}.bind(this))
uploadRequest.end((err,resp) => {
})
})
I am using react-native-image-picker to allow users to select or record a video, which gives me a URI of the video file path. Then I use RNFetchBlob to upload it to the server.
RNFetchBlob.fetch('POST', 'Upload API endpoint', {
...this.getHeader(),
'Content-Type': 'multipart/form-data'
// Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
// Or simply wrap the file path with RNFetchBlob.wrap().
}, [
// element with property `filename` will be transformed into `file` in form data
{ name: 'file', filename: 'video.mp4', data: RNFetchBlob.wrap(this.state.videoUri) },
// custom content type
]).uploadProgress({ interval: 250 }, (written, total) => {
let uploaded = (written / total) * 100
this.setState({
uploadProgress: uploaded.toFixed(1)
})
})
.then((response) => {
if (response.ok) {
this.setState({
uploading: false,
uploadSuccess: true,
uploadFailed: false,
})
}
}).catch((err) => {
this.setState({
uploading: false,
uploadSuccess: false,
uploadFailed: true,
})
})
Basically you have to give the path of your image, audio or video to fetch blob. The following code worked for me:
RNFetchBlob.fetch(
'POST',
`${BASE_URL}vehicle/vehicleRegistration`,
{
Authorization: 'Bearer ' + authToken,
'Content-Type': 'multipart/form-data,octet-stream',
},
[
{
name: 'photo',
filename: 'vid.mp4',
data: RNFetchBlob.wrap(vehicleImage.uri),
},
{
name: 'email',
data: user.email,
},
{
name: 'userId',
data: user.id,
},
{
name: 'vehicleType',
data: values.vehicleType,
},
{
name: 'make',
data: values.make,
},
{
name: 'buildYear',
data: values.buildYear,
},
{
name: 'model',
data: values.model,
},
{
name: 'nickName',
data: values.nickName,
},
{
name: 'engineSize',
data: values.engineSize,
},
],
)
.uploadProgress((written, total) => {
console.log('uploaded', written / total);
})
.then(response => response.json())
.then(RetrivedData => {
console.log('---retrieved data------', RetrivedData);
Toast.show({
text1: 'Success',
text2: 'Vehicle Added to Garage!',
type: 'success',
});
})
.catch(err => {
console.log('----Error in adding a comment----', err);
Toast.show({
text1: 'Request Failed',
text2: err?.response?.data?.message,
type: 'error',
});
});

getting text from react native fetch call

I'm not able to parse the data from the fetch call
Below is the method
onLoginPress=()=>{
console.log("username="+this.state.username);
console.log("password="+this.state.password);
this.sendLoginRequest(this.state.username,this.state.password)
.then((response) => {
console.log("RESPONSEEEEEEEEEEEEEEEE");
console.log(response.text())
console.log( Promise.resolve(response));
response.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
The response i get it is a promise and i'm not able to get the token out of it.
Below is the log for response.text()
{
_45: 0, _81: 1,
_65: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
_54: null }
For console.log( Promise.resolve(response)) the output is
{
_45: 0,
_81: 1,
_65: { type: 'default',
status: 200,
ok: true,
statusText: undefined,
headers: { map: { connection: [ 'Keep-Alive' ],
'content-length': [ '34' ],
'content-type': [ 'application/json; charset=utf-8' ],
'set-cookie': [ 'persistent_shopping_cart=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/' ],
'cache-control': [ 'no-store, no-cache, must-revalidate' ],
expires: [ 'Thu, 19 Nov 1981 08:52:00 GMT' ],
pragma: [ 'no-cache' ],
server: [ 'Apache/2.4.23 (Ubuntu)' ],
'keep-alive': [ 'timeout=5, max=100' ],
[ 'Tue, 20 Jun 2017 06:58:16 GMT' ] } },
url:'http://integration/customer/token',
_bodyInit: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
_bodyText: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
bodyUsed: true
},
_54: null }
responseJson returns undefined.
How to get the token(3h8112qe2qobox3675ghmq9dtcbjvddc) out of the data.
Thanks!
It appears that your API is returning text. So you need to call the text() method and return it to chain with a then:
onLoginPress=()=>{
this.sendLoginRequest(this.state.username,this.state.password)
.then((response) => {
return response.text();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
If your API returns JSON, you would do exactly the same by swapping the text() call by a json() call. See the React Native fetch doc.