Mapquest API key not recognized - mapquest

I signed up for the Mapquest API service, and I am now testing my application, using PHP.
Under Manage Keys, I created a new key, and Mapquest gave me:
Consumer Key
Consumer Secret
I clicked on Approve All Keys
I looked up the documentation for Geocoding API Post Batch, and it says that I should include the key as one of the params.
I assumed it's the Consumer Key, so I included mine. However, when I make the call, I get the following response:
The AppKey submitted with this request is invalid.
My code:
$results = mapquest_v1_geocoding_batch_get_location(array('123 Main St, Anytown, WA', '123 Main St, Anytown, WA 98052'));
pretty_print($results);
function mapquest_v1_geocoding_batch_get_location($locations)
{
//&location=Denver, CO&location=1555 Blake St, Denver, CO 80202&location=Boulder&key=KEY
$postfields = array (
'inFormat' => 'kvp',
'outFormat' => 'json',
'thumbMaps' => FALSE,
'maxResults' => 1
);
$postfields_string = http_build_query($postfields);
foreach ($locations as $location) {
$postfields_string .= '&'.http_build_query(array('location' => $location));
}
$postfields_string .= '&'.http_build_query(array('key' => PARN_MAPQUEST_TW_TO_FB_KEY));
pretty_echo($postfields_string);
$url = 'https://www.mapquestapi.com/geocoding/v1/batch';
return jhm_curl_post_call($url, $postfields);
}
function jhm_curl_post_call($url, $postfields, $setopts_array = FALSE)
{
$results = array();
if (!$setopts_array) {
$setopts_array = array();
}
if (!isset($setopts_array[CURLOPT_RETURNTRANSFER])) {
$setopts_array[CURLOPT_RETURNTRANSFER] = TRUE;
}
if (!isset($setopts_array[CURLOPT_POST])) {
$setopts_array[CURLOPT_POST] = TRUE;
}
$setopts_array[CURLOPT_URL] = $url;
$setopts_array[CURLOPT_POSTFIELDS] = http_build_query($postfields);
$ch = curl_init();
curl_setopt_array ($ch , $setopts_array);
$results['json_response'] = curl_exec($ch);
$results['response'] = json_decode($results['json_response'], TRUE);
$results['info'] = curl_getinfo($ch);
$results['curl_errno'] = curl_errno($ch);
$results['curl_error'] = curl_error($ch);
curl_close($ch);
return $results;
}
This is the $postfields_string:
inFormat=kvp&outFormat=json&thumbMaps=0&maxResults=1&location=123+Main+St%2C+Anytown%2C+WA&location=123+Main+St%2C+Anytown%2C+WA+98052&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxx
and the results of the call:
Array
(
[json_response] => The AppKey submitted with this request is invalid.
[info] => Array
(
[url] => https://www.mapquestapi.com/geocoding/v1/batch
[content_type] => text/plain
[http_code] => 403
[header_size] => 236
[request_size] => 198
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.265
[namelookup_time] => 0.062
[connect_time] => 0.109
[pretransfer_time] => 0.203
[size_upload] => 52
[size_download] => 50
[speed_download] => 188
[speed_upload] => 196
[download_content_length] => 50
[upload_content_length] => 52
[starttransfer_time] => 0.265
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 207.200.103.5
[certinfo] => Array
(
)
[primary_port] => 443
[local_ip] => 192.168.1.4
[local_port] => 50514
)
[curl_errno] => 0
[curl_error] =>
)

The key needs to be in the url parameters after mapquestapi.com rather than in the post data. Then you should be good to go.

Related

How to load post ID using the gform_form_post_get_meta filter?

Trying to load post ID (and then some ACF field) of the post, where the form is currently embedded. Using get_the_id() or global $post w/ $post->ID returns NULL.
Loading post ID works correctly when using the other Gravity Forms filters (e.g. gform_admin_pre_render), but I was told using the gform_form_post_get_meta is the better way to do ths. What is the right approach for this?
add_filter( 'gform_form_post_get_meta' , 'my_populate_cpt_as_choices' );
function my_populate_cpt_as_choices( $form ) {
$current_post_id = get_the_id();
$postargs = array(
'post_type' => 'suhlasy',
'post_status' => 'publish',
'posts_per_page' => '-1',
);
$posts = get_posts( $postargs );
$input_id = 1; // this makes sure the checkbox labels and inputs correspond
foreach ( $posts as $post ) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if ( $input_id % 10 == 0 ) {
$input_id++;
}
$post_id = $post->ID;
$id_souhlasu = 1200 + $input_id;
$title = get_the_title($post_id);
$checkbox_text = get_field('checkbox_text', $post_id);
$text_suhlasu = get_field('text_suhlasu', $post_id);
$kategoria = get_field('kategoria_suhlas', $post_id);
// getting other fields for this post to display as values or checkbox labels
$nazev_souhlasu = GF_Fields::create( array(
'type' => 'consent',
'id' => $id_souhlasu, // The Field ID must be unique on the form
'formId' => $form['id'],
'isRequired' => true,
'label' => $title,
'parameterName' => 'my_custom_parameter',
'checkboxLabel' => $checkbox_text,
'description' => '<h2>' . $current_post_id . $post_id . $kategoria . '</h2><br>' . $text_suhlasu,
'pageNumber' => 1, // Ensure this is correct
) );
$form['fields'][] = $nazev_souhlasu;
$input_id++;
}
return $form;
}

Why my postman hang forever with with GuzzleHttp\Client request?

Working with lumen-passport in lumen 8 I
got client_secret and client_id and make a request with GuzzleHttp\Client and my postman hang forever:
My postman : https://imgur.com/a/LbtUIVi
In routes/web.php :
$router->group(['prefix'=>'api/v1'], function() use($router){
$router->post('/register','AuthController#register');
$router->post('/login', 'AuthController#login');
In my control :
$client = new Client();
try {
$clientResponse = $client->post( 'http://localhost:8000/api/v1/oauth/token' /* config('service.passport.login_endpoint' ) */ , [
"form_params" => [
"client_secret" => 'DfiXey63ABDjgX7upuNaGmGvvASzhGq9kjZTV9nm', //config('service.passport.client_secret'),
"client_id" => 2, //config('service.passport.client_id'),
"grant_type" => "client_credentials",
"username" => $request->email,
"password" => $request->password
]
]);
\Log::info( varDump(-3, ' -3 login $clientResponse::') );
return $clientResponse;
} catch (BadResponseException $e) {
\Log::info( varDump(-4, ' -4 login ::') );
\Log::info( varDump($e->getMessage(), ' -4 login $e->getMessage()::') );
return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
}
In bootstrap/app.php I have :
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
//$app->configure('app');
$app->register(App\Providers\AppServiceProvider::class);
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
//$app->configure('app');
$app->register(App\Providers\AppServiceProvider::class);
// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
...
\Dusterio\LumenPassport\LumenPassport::routes($app, ['prefix' => 'api/v1/oauth']);
Under console I see :
ProjectName$ php -S localhost:8000 -t public
[Tue Jun 1 07:27:23 2021] PHP 7.4.18 Development Server (http://localhost:8000) started
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 Accepted
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45944 Accepted
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 [200]: GET /
[Tue Jun 1 07:27:29 2021] 127.0.0.1:45940 Closing
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45948 Accepted
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45944 [200]: GET /
[Tue Jun 1 07:27:31 2021] 127.0.0.1:45944 Closing
[Tue Jun 1 07:27:41 2021] 127.0.0.1:45956 Accepted
I tried to debug guzzle source and found that it hang in file /vendor/guzzlehttp/guzzle/src/Client.php,
in method:
private function transfer(RequestInterface $request, array $options): PromiseInterface
{
$request = $this->applyOptions($request, $options);
/** #var HandlerStack $handler */
$handler = $options['handler'];
\Log::info( varDump(-21, ' -21 transfer::') );
\Log::info( varDump($handler, ' $handler transfer::') );
try {
return P\Create::promiseFor($handler($request, $options)); // I suppose it hang forever here
} catch (\Exception $e) {
return P\Create::rejectionFor($e);
}
}
Checking content of $handler in log file I see :
[2021-06-01 04:54:47] local.INFO: (Object of GuzzleHttp\HandlerStack) : $handler transfer:: : Array
(
[ GuzzleHttp\HandlerStack handler] => Closure Object
(
[static] => Array
(
[default] => Closure Object
(
[static] => Array
(
[default] => GuzzleHttp\Handler\CurlMultiHandler Object
(
[factory:GuzzleHttp\Handler\CurlMultiHandler:private] => GuzzleHttp\Handler\CurlFactory Object
(
[handles:GuzzleHttp\Handler\CurlFactory:private] => Array
(
)
[maxHandles:GuzzleHttp\Handler\CurlFactory:private] => 50
)
[selectTimeout:GuzzleHttp\Handler\CurlMultiHandler:private] => 1
[active:GuzzleHttp\Handler\CurlMultiHandler:private] =>
[handles:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
[delays:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
[options:GuzzleHttp\Handler\CurlMultiHandler:private] => Array
(
)
)
[sync] => GuzzleHttp\Handler\CurlHandler Object
(
[factory:GuzzleHttp\Handler\CurlHandler:private] => GuzzleHttp\Handler\CurlFactory Object
(
[handles:GuzzleHttp\Handler\CurlFactory:private] => Array
(
)
[maxHandles:GuzzleHttp\Handler\CurlFactory:private] => 3
)
)
)
[parameter] => Array
(
[$request] => <required>
[$options] => <required>
)
)
[streaming] => GuzzleHttp\Handler\StreamHandler Object
(
[lastHeaders:GuzzleHttp\Handler\StreamHandler:private] => Array
(
)
)
)
[parameter] => Array
(
[$request] => <required>
[$options] => <required>
)
)
[ GuzzleHttp\HandlerStack stack] => Array
(
[0] => Array
(
[0] => Closure Object
(
[static] => Array
(
[bodySummarizer] =>
)
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => http_errors
)
[1] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => allow_redirects
)
[2] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => cookies
)
[3] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$handler] => <required>
)
)
[1] => prepare_body
)
)
[ GuzzleHttp\HandlerStack cached] =>
)
Any idea what is wrong? Local server misconfig ?
PHP 7.4.18 under kubuntu
"dusterio/lumen-passport": "^0.3.4",
"guzzlehttp/guzzle": "^7.3",
"laravel/lumen-framework": "^8.0",
Thanks in advance!
I don't have so experience in lumen, but I am using in environment develop this solution without Guzzle.
public function login(Request $request){
$email = $request->email;
$password = $request->password;
//Check if field is not empty
if (empty($email) or empty($password)) {
return response()->json(['status' => 'error', 'message' => 'You must fill all fields']);
}
$user = User::where('email', '=', $email)->exists();
if ($user === false) {
return response()->json(['status' => 'error', 'message' => 'User doesnt exist']);
}
//$client = new \GuzzleHttp\Client();
try{
$tokenRequest = $request->create(
env('PASSPORT_LOGIN_ENDPOINT'),
'POST'
);
$tokenRequest->request->add([
"grant_type" => "password",
"username" => $request->email,
"password" => $request->password,
"client_id" => env('PASSPORT_CLIENT_ID'),
"client_secret" => env('PASSPORT_CLIENT_SECRET'),
]);
$response = app()->handle($tokenRequest);
return $response;
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
}
}

Use CakePHP Http Client with Magento2 rest API search criteria

I'm trying to send a GET request to a local Magento2 rest API to get all the orders after a certain time. I'm following http://devdocs.magento.com/guides/v2.1/howdoi/webapi/search-criteria.html#simple-search-using-a-timestamp. I'm using CakePHP 3.4's Http Client (https://book.cakephp.org/3.0/en/core-libraries/httpclient.html) and have successfully integrated with Magento using Oauth1 and have no problems with simpler GET requests like http://www.magento.dev.com/rest/V1/stockItems/:productSku. It is a problem with passing the search criteria. The response is always a 401 Invalid Signature.
Using Postman, I can get a valid response to http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt
This is what I have so far/how I'm sending the request:
In Model/Table/OrdersTable.php:
public function importNewOrders(\App\Model\Entity\OauthIntegration $integrationDetails)
{
$this->OauthIntegrations = TableRegistry::get('OauthIntegrations');
$this->Orders = TableRegistry::get('Orders');
$timeCutOff = '2015-01-01 00:00:00';
$search = [
'searchCriteria' => [
'filterGroups' => [
0 => [
'filters' => [
0 => [
'field' => 'created_at',
'value' => $timeCutOff,
'condition_type' => 'gt'
]
]
]
]
]
];
// 'searchCriteria[filter_groups][0][filters][0][field]' => 'created_at',
// 'searchCriteria[filter_groups][0][filters][0][value]' => $timeCutOff,
// 'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'gt'
$action = '/V1/orders';
$type = "GET";
$response = $this->OauthIntegrations->sendRequest(
$integrationDetails,
$action,
$type,
'',
$search);
Log::write('debug', $response->body());
return $response;
}
and in Model\Table\OauthIntegrationsTable.php:
public function sendRequest(\App\Model\Entity\OauthIntegration $integrationDetails,
string $action, string $method = "GET", string $data = '', array $search = null)
{
$http = new Client([
'auth' => [
'type' => 'oauth',
'consumerKey' => $integrationDetails->oauth_consumer_key,
'consumerSecret' => $integrationDetails->oauth_consumer_secret,
'token' => $integrationDetails->oauth_token,
'tokenSecret' => $integrationDetails->oauth_token_secret
]
]);
$url = $integrationDetails->store_base_url . 'rest' . $action;
if ($method == 'GET'){
if (!isset($search)){
$search = [];
}
$response = $http->get($url, $search, []);
} else if ($method == 'POST'){
$response = $http->post($url, $data, [
'type' => 'json',
]);
} else if($method == 'PUT'){
$response = $http->put($url, $data, [
'type' => 'json',
]);
}
Log::write('debug', 'url: ' . $url . ' and status code: ' . $response->getStatusCode());
return $response;
}
and this is the error (I'm hoping) is the cause of the Invalid Signature response:
2017-03-28 10:07:01 Notice: Notice (8): Array to string conversion in [/var/www/cakephp/html/beacon/vendor/cakephp/cakephp/src/Http/Client/Auth/Oauth.php, line 315]
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 153
Cake\Http\Client\Auth\Oauth::_normalizedParams() - CORE/src/Http/Client/Auth/Oauth.php, line 315
Cake\Http\Client\Auth\Oauth::baseString() - CORE/src/Http/Client/Auth/Oauth.php, line 246
Cake\Http\Client\Auth\Oauth::_hmacSha1() - CORE/src/Http/Client/Auth/Oauth.php, line 143
Cake\Http\Client\Auth\Oauth::authentication() - CORE/src/Http/Client/Auth/Oauth.php, line 61
Cake\Http\Client::_addAuthentication() - CORE/src/Http/Client.php, line 501
Cake\Http\Client::_createRequest() - CORE/src/Http/Client.php, line 448
Cake\Http\Client::_doRequest() - CORE/src/Http/Client.php, line 341
Cake\Http\Client::get() - CORE/src/Http/Client.php, line 211
App\Model\Table\OauthIntegrationsTable::sendRequest() - APP/Model/Table/OauthIntegrationsTable.php, line 134
App\Model\Table\OrdersTable::importNewOrders() - APP/Model/Table/OrdersTable.php, line 672
App\Shell\MagentoShell::main() - APP/Shell/MagentoShell.php, line 36
Cake\Console\Shell::runCommand() - CORE/src/Console/Shell.php, line 472
Cake\Console\ShellDispatcher::_dispatch() - CORE/src/Console/ShellDispatcher.php, line 227
Cake\Console\ShellDispatcher::dispatch() - CORE/src/Console/ShellDispatcher.php, line 182
Cake\Console\ShellDispatcher::run() - CORE/src/Console/ShellDispatcher.php, line 128
[main] - ROOT/bin/cake.php, line 33
Code from Http\Client\Oauth.php where error occurs:
$pairs = [];
foreach ($args as $k => $val) {
if (is_array($val)) {
sort($val, SORT_STRING);
Log::write('debug', 'about to go through foreach($val as $nestedVal)');
foreach ($val as $nestedVal) {
Log::write('debug', $nestedVal);
$pairs[] = "$k=$nestedVal"; // <<< HERE
}
} else {
$pairs[] = "$k=$val";
}
}
debugging from above results in:
2017-03-28 10:07:01 Debug: about to go through foreach($val as $nestedVal)
2017-03-28 10:07:01 Debug: Array
(
[0] => Array
(
[filters] => Array
(
[0] => Array
(
[field] => created_at
[value] => 2015-01-01 00:00:00
[condition_type] => gt
)
)
)
)
In summary, is it possible to pass a multi-dimensional array to the 2nd parameter in a get request using Cake's Http Client?
// Is it possible to replace ['q' => 'widget'] with a multi-dimensional array??
$response = $http->get('http://example.com/search', ['q' => 'widget']);
If not, what would be the best way to use Cake's Http Client to send GET request to: http://www.magento.dev.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2016-07-01 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt ?
Thanks in advance!!!
Possible bug
This may be considered as a possible bug. I don't think the OAuth specs take this PHP style bracket stuff in URLs into account, and therefore sorting/encoding the parameters is limited to flat key=value sets, ie a key would be
searchCriteria[filter_groups][0][filters][0][field]
and the value would be
created_at
The CakePHP OAuth adapter however parses the requests query string into a possibly deeply nested array structure, which will then fail, as it doesn't handle that case.
I'd suggest that you report this as a possible bug. Further problems may occour as encoding seems to be ment to be applied before sorting, where in the CakePHP implementation, additonal parameter encoding is applied after sorting (that may actually be fine though, I'm not sure).
Try a custom OAuth adapter as a workaround
Until this is being fixed/enhanced, you could use a custom OAuth adapter that handles things "properly" (whatever that means in this context). Here's a quick and dirty example (works for me with the Magento API).
Create src/Http/Client/Auth/AppOAuth.php
<?php
namespace App\Http\Client\Auth;
use Cake\Http\Client\Auth\Oauth;
class AppOAuth extends Oauth
{
protected function _normalizedParams($request, $oauthValues)
{
$query = parse_url($request->url(), PHP_URL_QUERY);
parse_str($query, $queryArgs);
$post = [];
$body = $request->body();
if (is_string($body) &&
$request->getHeaderLine('content-type') === 'application/x-www-form-urlencoded'
) {
parse_str($body, $post);
}
if (is_array($body)) {
$post = $body;
}
$args = array_merge($queryArgs, $oauthValues, $post);
$query = http_build_query($args);
$args = [];
foreach (explode('&', $query) as $value) {
$pair = explode('=', $value, 2);
$args[] =
rawurlencode(rawurldecode($pair[0])) .
'=' .
rawurlencode(rawurldecode($pair[1]));
}
usort($args, 'strcmp');
return implode('&', $args);
}
}
Compare to \Cake\Http\Client\Auth\Oauth::_normalizedParams()
Use it by specifying the classname in the type option for your client instance:
'type' => 'AppOAuth',
ps
shouldn't it be filter_groups instead of filterGroups in your $search array?

Fetch protected data from object zend

I have response and I want to fetch referenceId from it, the response is
Application_Model_User Object
(
[_data:protected] => Array
(
[id] => 2
[email] => test#gmail.com
[password] => ef1dca60798e10a51e3b6201ae7c40fbe2a10887
[salt] => 87fc83906190d1e29b60c5813065af068e16459d
[name] => test
[creationDate] => 2011-07-05
[lastTimeStamp] => 2016-06-03 09:13:53
[enabled] => 1
[loginHash] =>
[employeeNumber] => 0007
[userphoneNumber] => +546546546545
[jobTitle] => Business Manager
)
[_references:protected] => Array
(
[role] => Array
(
[referenceClass] => Application_Model_Role
[referenceId] => 4
[mapperClass] => Application_Model_RoleMapper
[mapper] =>
)
[organisation] => Array
(
[referenceClass] => Application_Model_Organisation
[referenceId] => 1
[mapperClass] => Application_Model_OrganisationMapper
[mapper] =>
)
)
)
How can I fetch ?
In .phtml file in ajax after
success: function(response){
var data = jQuery.parseJSON(response);
for (var i in data)
{
var referenceId = data[i]['referenceId'];
}
}
You can use a getter. You can create a method to return the referenceId.

Get customer Email in return URL after making payment using PayPal button

How can i get customer Email in return URL after making payment using PayPal button?
Thanks.
<?php
if(isset($_GET['tx']))
{
$tx = $_GET['tx'];
$your_pdt_identity_token = //token
$request = curl_init();
// Set request options
curl_setopt_array($request, array
(
CURLOPT_URL => 'https://www.sandbox.paypal.com/cgi-bin/webscr', //sandbox!!!
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => http_build_query(array
(
'cmd' => '_notify-synch',
'tx' => $tx,
'at' => $your_pdt_identity_token,
)),
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HEADER => FALSE,
// CURLOPT_SSL_VERIFYPEER => TRUE,
// CURLOPT_CAINFO => 'cacert.pem',
));
// Execute request and get response and status code
$response = curl_exec($request);
$status = curl_getinfo($request, CURLINFO_HTTP_CODE);
// Close connection
curl_close($request);
}
if($status == 200 AND strpos($response, 'SUCCESS') === 0)
{
$singlequantity = explode("\n",$response);
$email = $singlequantity[15];
$count = null;
$email = preg_replace('"%40"', '#', $email, -1, $count);
preg_match("/payer_email=(.*)/", $email, $email);
}
else
{
echo '<script type="text/javascript">
window.location="cancel.php";
</script>';
}
?>
i know i shoved it in real hard right now , but this might be useful to other users attempting to do this.