How use "segment" in OneSignal with when POST to API? - php

Im trying to POST a push to OneSignal service. I can make it work including "include_player_ids".. but can't make it work with "segments"
Im trying this:
$data= array("app_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"contents" => array("en" => "Check this!") ,
"filters" => array("segment"=> "test"),
"big_picture" => "http://www.xxxxx.com/img/logo2.png"
);
Response:
stdClass Object ( [errors] => Array ( [0] => Please include a case-sensitive header of Authorization: Basic with a valid REST API key. ) [reference] => Array ( [0] => https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids ) )
Also trying this:
$data= array("app_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"contents" => array("en" => "Check this!") ,
"segments" => "all",
"big_picture" => "http://xxxxxx.com/img/logo2.png"
);
Response:
stdClass Object ( [errors] => Array ( [0] => You must include which players, segments, or tags you wish to send this notification to. ) )

I got it, you have to add segments like this:
'included_segments' => array('test')
And the head of the CURL to post must contain the api rest key
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic API-REST-KEY'));

Related

Twitter OAuth 2.0 responding with "Value passed for the token was invalid."

EDIT: See solution. Problem was in how the Twitter library was instantiated.
I'm trying to get Twitter authorization using OAuth2. I'm able to get it to work in a simple test script, but when I try to use it in my WordPress plugin it doesn't work.
I'm using The PHP League's OAuth2 Client with a library I wrote to connect it to Twitter; the test script is in the README.
The test script stores the OAuth2 state in $_SESSION; the actual app stores it in a WordPress transient. I've confirmed the integrity of the data through the pipeline:
Data from Twitter library after generating auth URL:
Array
(
[url] => https://twitter.com/i/oauth2/authorize?redirect_uri=https%3A%2F%2Fsmol.blog%2Fwp-json%2Fsmolblog%2Fv2%2Fconnect%2Fcallback%2Ftwitter&code_challenge=EV7BCVYmkvCnIlVLH6cVzrvjNloQlleAkkYwLLgg41w&code_challenge_method=S256&state=fd5824ef415aa325f1f68d3504bb16b3&scope=tweet.read%20users.read%20offline.access&response_type=code&approval_prompt=auto&client_id=MjVXMnRGVUN5Ym5lcVllcTVKZkk6MTpjaQ
[state] => fd5824ef415aa325f1f68d3504bb16b3
[verifier] => u7Zbf1gVEFZLyTgr_2Hk~i5P2pt8VgicyhZgdeO0pAyIZqhSoYqglHaIxsNRjHz0AHpwhlU1~Q
)
Data pulled from WordPress transient during the callback (stored slightly differently):
Array
(
[id] => fd5824ef415aa325f1f68d3504bb16b3
[userId] => 1
[info] => Array
(
[verifier] => u7Zbf1gVEFZLyTgr_2Hk~i5P2pt8VgicyhZgdeO0pAyIZqhSoYqglHaIxsNRjHz0AHpwhlU1~Q
)
)
Request object to Twitter's token endpoint:
GuzzleHttp\\Psr7\\Request Object
(
[method:GuzzleHttp\\Psr7\\Request:private] => POST
[requestTarget:GuzzleHttp\\Psr7\\Request:private] =>
[uri:GuzzleHttp\\Psr7\\Request:private] => GuzzleHttp\\Psr7\\Uri Object
(
[scheme:GuzzleHttp\\Psr7\\Uri:private] => https
[userInfo:GuzzleHttp\\Psr7\\Uri:private] =>
[host:GuzzleHttp\\Psr7\\Uri:private] => api.twitter.com
[port:GuzzleHttp\\Psr7\\Uri:private] =>
[path:GuzzleHttp\\Psr7\\Uri:private] => /2/oauth2/token
[query:GuzzleHttp\\Psr7\\Uri:private] =>
[fragment:GuzzleHttp\\Psr7\\Uri:private] =>
[composedComponents:GuzzleHttp\\Psr7\\Uri:private] =>
)
[headers:GuzzleHttp\\Psr7\\Request:private] => Array
(
[Host] => Array
(
[0] => api.twitter.com
)
[content-type] => Array
(
[0] => application/x-www-form-urlencoded
)
[Authorization] => Array
(
[0] => Basic [base64-encoded app id and secret redacted]
)
)
[headerNames:GuzzleHttp\\Psr7\\Request:private] => Array
(
[content-type] => content-type
[host] => Host
[authorization] => Authorization
)
[protocol:GuzzleHttp\\Psr7\\Request:private] => 1.1
[stream:GuzzleHttp\\Psr7\\Request:private] => GuzzleHttp\\Psr7\\Stream Object
(
[stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #101
[size:GuzzleHttp\\Psr7\\Stream:private] =>
[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp
[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array
(
)
)
)
Body of said request:
client_id=MjVXMnRGVUN5Ym5lcVllcTVKZkk6MTpjaQ&client_secret=[redacted]&grant_type=authorization_code&code=aTVUMDkybzdsVmExOEQ5MjdrVjVOQVZ3YTVDbUdmTXRDMktZSzBaSGFqVk5LOjE2NjUzNjc1MjIyNjg6MToxOmFjOjE&code_verifier=u7Zbf1gVEFZLyTgr_2Hk~i5P2pt8VgicyhZgdeO0pAyIZqhSoYqglHaIxsNRjHz0AHpwhlU1~Q
The error:
PHP Fatal error: Uncaught League\\OAuth2\\Client\\Provider\\Exception\\IdentityProviderException: Value passed for the token was invalid. in /var/www/html/wp-content/plugins/smolblog-wp/vendor/smolblog/oauth2-twitter/src/Twitter.php:169
I know I'm missing something stupid here. But I can't for the life of me figure out what. There's a lot more code in the actual app than there is in the test script, but I've verified the data at multiple points in the stack, including right before it's sent to Twitter. What else do I need to be testing, or is there something that I'm forgetting?
Found the error. In the test script, the redirectUri was passed into the constructor of the OAuth2 client; In the app, it was passed into the getAuthorizationUrl function. This worked for the initial call to Twitter, but (apparently) that data is also needed for the getAccessToken call. So here's the fix.
Old and busted:
new Twitter([
'clientId' => $app->env->twitterAppId ?? '',
'clientSecret' => $app->env->twitterAppSecret ?? '',
])
New hotness:
new Twitter([
'clientId' => $app->env->twitterAppId ?? '',
'clientSecret' => $app->env->twitterAppSecret ?? '',
'redirectUri' => "{$app->env->apiBase}connect/callback/twitter",
])

Coinmarketcap API call with PHP and choose data set with slug

I tried to do my first API calls which worked finally with help from this great users here in this community. Thanks again. I want to choose data[1] or the currency with symbol. So i could use a $variable from my CMS. Maybe someone can show me a way how i can change this call to symbol. Here is my API call.
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
$price = $json->data[1]->quote->USD->price; echo $price;
You get the data block IDs with array_column(), then you get the symbol's data block ID with array_search():
$data_ids = array_column($json->data, 'symbol');
$symbol_data_id = array_search('ETH', $data_ids);
$price = $json->data[$symbol_data_id]->quote->USD->price;
Or as an oneliner:
$price = $json->data[array_search('ETH', array_column($json->data, 'symbol'))]->quote->USD->price;
LATER UPDATE: OK, let me elaborate on this. Step by step:
You need a proper URL to acces the API. For this you need the API documentation. Your original question mentioned
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
while for your comment question you need something like
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?symbol=ETH";
A proper URL will give you a JSON response structured according to its purpose. You have this part ironed out, so I'll not insist on this. From your question text:
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: 1b58ff56-58b2-4fd0-b184-f9c3dd4ff106',
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, [
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1, // ask for raw response instead of bool
]);
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
Then you have to decide how to use the response. For me, the fastest way is to look at its structure (var_dump($json) or print_r($json)). Which will give something like this (the original question):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:37:59.447Z
[error_code] => 0
[error_message] =>
[elapsed] => 22
[credit_count] => 1
[notice] =>
[total_count] => 7060
)
[data] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Bitcoin
[...]
)
[1] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[slug] => ethereum
[...]
[quote] => stdClass Object
(
[USD] => stdClass Object
(
[price] => 4445.0743486785
[volume_24h] => 14137477206.072
[volume_change_24h] => -9.6622
[percent_change_1h] => 0.2898806
[percent_change_24h] => -1.29677209
[percent_change_7d] => 3.13286959
[percent_change_30d] => 23.49191199
[percent_change_60d] => 28.79913805
[percent_change_90d] => 48.37310902
[market_cap] => 525560956659.07
[market_cap_dominance] => 19.5198
[fully_diluted_market_cap] => 525560956659.07
[last_updated] => 2021-11-06T18:37:03.000Z
)
)
)
[2] => stdClass Object [...]
or this (the question in the comment):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:03:05.201Z
[error_code] => 0
[error_message] =>
[elapsed] => 12
[credit_count] => 1
[notice] =>
)
[data] => stdClass Object
(
[ETH] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[category] => coin
[description] => Ethereum (ETH) is a cryptocurrency . Users are able to generate ETH through the process of mining. Ethereum has a current supply of 118,233,336.749. The last known price of Ethereum is 4,424.33123326 USD and is down -1.39 over the last 24 hours. It is currently trading on 4537 active market(s) with $14,138,162,060.93 traded over the last 24 hours. More information can be found at https://www.ethereum.org/.
[...]
[platform] =>
[date_added] => 2015-08-07T00:00:00.000Z
[twitter_username] => ethereum
[is_hidden] => 0
)
)
)
So data is a property of the $json object.
In the first case, data is an array and its structure suggests using array functions to retrieve specific data.
In the second case, data and ETH are objects, while description is a property of ETH. Which allows me to get the description using object syntax
$description = $json->data->ETH->description;

How to get value of email form JWT

Im usign dialogflow to create a booking table assistant.
To get info by user, he need to sign in with google so when finish the conversation i would take uderId value of user.
For take that I use jose-php library so:
header( 'Access-Control-Allow-Headers: *' );
header( 'Access-Control-Allow-Origin: *' );
header( "Access-Control-Allow-Credentials: true" );
header( 'Content-Type: application/json' );
include('../phpseclib/Net/SSH2.php');
include('../JOSE/JWT.php');
include('../JOSE/URLSafeBase64.php');
$jwt_string = 'userIdtoken';
$jwt = JOSE_JWT::decode($jwt_string);
echo $jwt['JOSE_JWT']['Claims']['email'];
the problem is that I recive error printing email value!
How I could get it?
$jwt value result so:
JOSE_JWT Object
(
[header] => Array
(
[alg] => RS256
[kid] => cf022a49e9786148ad0e379cc854844e36c3edc1
[typ] => JWT
)
[claims] => Array
(
[iss] => https://accounts.google.com
[nbf] => 1551435957967
[aud] => 284549458086-fdoluk70pqkcuh8vj4tj1dou15v444tiua.apps.googleusercontent.com
[sub] => 1092379345381822971290339
[email] => dasdasddas#gmail.com
[email_verified] => 1
[name] => frank rossi
[picture] => https://lh4.googleusercontent.com/-79eVyjn_YU8/AAAAAAAAAAI/AAAAAAAAPBs/uvq_fruLiB0/s96-c/photo.jpg
[given_name] => Federico
[family_name] => Idsfdsfdsf
[iat] => 1545351958267
[exp] => 155143534961867
[jti] => 428254345532cddf49dec17d24ace2e6f45f8af4b14b2
)
[signature] => 'somthing'
[raw] => 'somthing'
)
It seems to me like the problem is a typo. You wrote $jwt['JOSE_JWT']['Claims']['email'];, but the key is claims, not Claims.
Also, $jwt seems to be an object of class JOSE_JWT, not an array. So using it with subscript operator is not possible just like that. You should instead access its properties:
$jwt->claims['email']

Cannot create campaign Mailchimp API 3.0 - PHP

I'm trying to integrate the MailChimp API 3.0 with PHP into a custom built CMS. When I try to create a single campaign with the following code I have an error message.
CODE:
$apikey = <--api-key-->;
$list_id = <--list-id-->;
use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp($apikey);
$result = $MailChimp->post("campaigns", [
'type' => 'regular',
'recipients' => ['list_id' => '$list_id'],
'settings' => ['subject_line' => 'test subject',
'reply_to' => 'test#test.com',
'from_name' => 'test name'],
]);
echo "<pre>";
print_r($result);
print_r($MailChimp->getLastRequest());
echo "</pre>";
ERROR MESSAGE:
Array
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Invalid Resource
[status] => 400
[detail] => The resource submitted could not be validated. For field-specific details, see the 'errors' array.
[instance] =>
[errors] => Array
(
[0] => Array
(
[field] =>
[message] => Schema describes object, NULL found instead
)
)
)
USING print_r($MailChimp->getLastRequest());
Array
(
[method] => post
[path] => campaigns
[url] => https://us8.api.mailchimp.com/3.0/campaigns
[body] =>
[timeout] => 10
[headers] => POST /3.0/campaigns HTTP/1.0
User-Agent: DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)
Host: us8.api.mailchimp.com
Accept-Encoding: deflate, gzip
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Authorization: apikey <--api-key-->
Content-Length: 0
)
I have checked the documentation, searched through SO, but haven't found anything. If anyone has a working code that creates a simple campaign I can start working with, I would appreciate it. What am I missing?
This is the code I used to get it done, also check for the encoding, it can cause problems
$result = $MailChimp->post("campaigns", [
"type" =>"regular",
"recipients"=> [
"list_id"=> "$list_id"
]
,
"settings"=> [
"subject_line"=> "test subject",
"from_name"=> "test name",
"reply_to"=> "test#test.com"
]
]);

Outbound efax developer api request using EHttpClient Yii not working

I'm using EHttpClient extension yii.
My Code:
$file = file_get_contents($path, true);
Yii::import('ext.EHttpClient.*');
$client = new EHttpClient('https://secure.efaxdeveloper.com/EFax_WebFax.serv', array(
'maxredirects' => 3,
'timeout' => 30,
'Content-Type' => 'application/x-www-form-urlencoded',
'adapter' => 'EHttpClientAdapterCurl'));
$client->setParameterPost(array('id'=>urlencode("2313125942"), 'xml'=>urlencode($file)));
SiteHelper::printShow($client);
$response = $client->request("POST");
var_dump($response->isSuccessful());
SiteHelper::printShow($response);
My xml data:
<?xml version="1.0"?>
<OutboundRequest>
<AccessControl>
<UserName>b23s2323</UserName>
<Password>b23s2323</Password>
</AccessControl>
<Transmission>
<TransmissionControl>
<Resolution>STANDARD</Resolution>
</TransmissionControl>
<DispositionControl>
<DispositionLevel>BOTH</DispositionLevel>
<DispositionEmails>
<DispositionEmail>
<DispositionAddress>johnmorris201615#gmail.com</DispositionAddress>
</DispositionEmail>
</DispositionEmails>
</DispositionControl>
<Recipients>
<Recipient>
<RecipientFax>8189790412</RecipientFax>
</Recipient>
</Recipients>
<Files>
<File>
<FileContents>Base64 pdf here</FileContents>
<FileType>pdf</FileType>
</File>
</Files>
</Transmission>
</OutboundRequest>
The information of my request:
EHttpClient Object
(
[config:protected] => Array
(
[maxredirects] => 3
[strictredirects] =>
[useragent] => EHttpClient
[timeout] => 30
[adapter] => EHttpClientAdapterCurl
[httpversion] => 1.1
[keepalive] =>
[storeresponse] => 1
[strict] => 1
[output_stream] =>
[encodecookies] => 1
[rfc3986_strict] =>
[content-type] => application/x-www-form-urlencoded
)
[adapter:protected] =>
[uri:protected] => EUriHttp Object
(
[_username:protected] =>
[_password:protected] =>
[_host:protected] => secure.efaxdeveloper.com
[_port:protected] => 443
[_path:protected] => /EFax_WebFax.serv
[_query:protected] =>
[_fragment:protected] =>
[_regex:protected] => Array
(
[alphanum] => [^\W_]
[escaped] => (?:%[\da-fA-F]{2})
[mark] => [-_.!~*'()\[\]]
[reserved] => [;\/?:#&=+$,]
[unreserved] => (?:[^\W_]|[-_.!~*'()\[\]])
[segment] => (?:(?:(?:[^\W_]|[-_.!~*'()\[\]])|(?:%[\da-fA-F]{2})|[:#&=+$,;])*)
[path] => (?:\/(?:(?:(?:[^\W_]|[-_.!~*'()\[\]])|(?:%[\da-fA-F]{2})|[:#&=+$,;])*)?)+
[uric] => (?:[;\/?:#&=+$,]|(?:[^\W_]|[-_.!~*'()\[\]])|(?:%[\da-fA-F]{2}))
)
[_scheme:protected] => https
)
[headers:protected] => Array
(
)
[method:protected] => GET
[paramsGet:protected] => Array
(
)
[paramsPost:protected] => Array
(
[id] => 2313125942
[xml] => The%encoded%url%xml%data
)
[cookiejar:protected] =>
[last_request:protected] =>
[last_response:protected] =>
[redirectCounter:protected] => 0
[_unmaskStatus:protected] =>
[_queryBracketsEscaped:protected] => 1
)
I already read the documentation from https://secure.efaxdeveloper.com/downloads.jsp Outbound already set all the required fields on xml data and request post. But I always get this error from efax developer API:
Post Unsuccessful!
Your request has failed due to invalid data.
Please refer to our documentation prior to resubmitting.
Error Level: User
Error Message: XML data argument was not passed.
Please contact us at 888-278-8666 if you continue to encounter errors.
Error Message : XML data argument was not passed What is wrong with my xml data?
(*Note on my request the xml post parameter is set the encoded file contents of my xml).
I used PHP efax instead.
PHP eFax is a PHP class that wraps the eFax® Developer API. Use PHP
eFax to automate the task of sending and receiving faxes
electronically from your PHP-powered web server.
Don't use urlencode. Just set the content type to application/x-www-form-urlencoded.

Categories