Connecting to shopify and returning products - laravel

I'm tring to return products from my shopify store and dump the expected returned json on to the page. No products return via the code but if I go directly to the url in the form below I get the expected json displayed on the page:
https://API_KEY:PASSWORD#your-store.myshopify.com/admin/products.json
Can anyone help me return the json using this package which I'm using to connect to shopify? I'm also using Laravel 5.
I've noticed that the Input calls return nothing:
Input::get('code');
Input::all();
I added this to app.php:
'Input' => Illuminate\Support\Facades\Input::class,
I'm getting this error:
ERROR #22: The requested URL returned error: 401
in api.php line 309 at API->call(array('METHOD' => 'GET', 'URL' => '/admin/products.json?page=1')) in routes.php line 87
This is my route:
Route::get('/show_products', function() {
$shopify = App::make('ShopifyAPI');
// This creates an instance of the Shopify API wrapper and
// authenticates our app.
$shopify = App::make('ShopifyAPI', [
'API_KEY' => 'api_key',
'API_SECRET' => 'api_secret',
'SHOP_DOMAIN' => 'shop_domain.myshopify.com',
'ACCESS_TOKEN' => 'access_token'
]);
$shopify->installURL(['permissions' => array('read_products', 'write_products'), 'redirect' => 'https://dev.shopify.com/public/']);
try {
$verify = $shopify->verifyRequest(Input::all(), true);
if ($verify)
{
$code = Input::get('code');
echo "code: ".$code; // no code returned
$accessToken = $shopify->getAccessToken($code);
echo "accessToken: ".$accessToken; // no access token
}
else
{
echo "issue with data";
// Issue with data
}
}
catch (Exception $e)
{
echo '<pre> Error: ' . $e->getMessage() . '</pre>';
}
// Gets a list of products
$result = $shopify->call([
'METHOD' => 'GET',
'URL' => '/admin/products.json?page=1'
]);
$products = $result->products;
print_r($products);
exit;
});

I ran into this issue on Android. The accessing the products by the url with key/secret worked fine if I was in a browser, but failed trying to do a basic GET against that URL from the device.
I couldn't figure out why, but I ended up setting the header on the request, and that worked well.
Where you had
https://API_KEY:PASSWORD#your-store.myshopify.com/admin/products.json
Instead, request
https://your-store.myshopify.com/admin/products.json
but set the header x-shopify-access-token to PASSWORD

Related

Laravel: Can't use the autoload function

I have a question about autoloading in Laravel.
I am trying to use an API to translate a web site. I typed in the code given by the provider in the controller and I got the following error message.
require(vendor\autoload.php): failed to open stream: No such file or directory
This is the code.
require 'vendor\autoload.php'; <=★Here★
session_start();
define('URL', '');
define('KEY', '');
define('SECRET', '');
define('NAME', '');
$api_name = '';
$api_param = '';
$provider = new \League\OAuth2\Client\Provider\GenericProvider(
[
'clientId' => KEY,
'clientSecret' => SECRET,
'redirectUri' => '',
'urlAuthorize' => '',
'urlAccessToken' => URL . '/oauth2/token.php',
'urlResourceOwnerDetails' => '',
],
);
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('client_credentials');
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$params = array(
'access_token' => $accessToken->getToken(),
'key' => KEY,
'api_name' => $api_name,
'api_param' => $api_param,
'name' => NAME,
'type' => 'xml',
'xxx' => 'xxx',
);
$request = $provider->getAuthenticatedRequest(
'POST',
URL . '/api/?' . http_build_query($params),
$accessToken,
);
$response = $provider->getResponse($request);
$data = $response->getBody()->getContents();
print_r($data);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
I checked the file pointed out in the error message and actually autoload.php file was in the vendor folder. I did some research and I found some web sites saying that I should add a directory in composer.json but I wasn't so sure what I should do.
I appreciate if you could tell me what I'm doing wrong or what I should do. Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.

How can i change the image upload directory and view image url in laravel

In my script all images uploaded goes into directory "ib" but i want to change that directory to a different name eg. "imgib"
here is what i did so far. i changed the code vlues from "ib" to "imgib"
} else {
// upload path
$path = 'imgib/';
// if path not exists create it
if (!File::exists($path)) {
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
}
// move image to path
$upload = $request->file('uploads')->move($path, $imageName);
// file name
$filename = url($path) . '/' . $imageName;
// method server host
$method = 1;
}
// if image uploded
if ($upload) {
// if user auth get user id
if (Auth::user()) {$userID = Auth::user()->id;} else { $userID = null;}
// create new image data
$data = Image::create([
'user_id' => $userID,
'image_id' => $string,
'image_path' => $filename,
'image_size' => $fileSize,
'method' => $method,
]);
// if image data created
if ($data) {
// success array
$response = array(
'type' => 'success',
'msg' => 'success',
'data' => array('id' => $string),
);
// success response
return response()->json($response);
} else {
if (file_exists('imgib/' . $filename)) {$delete = File::delete('imgib/' . $filename);}
// error response
return response()->json(array(
'type' => 'error',
'errors' => 'Opps !! Error please refresh page and try again.',
));
}
so far everything looks ok and it creates "imgib" directory automatically and all uploads go into "imgib" directory.
But the issue is, image url still uses the same old directory name.
eg. site.org/ib/78huOP09vv
How to make it get the correct url eg. site.org/imgib/78huOP09vv
Thanks for the help everyone. I managed to fix the issue by editing viewimage.blade.php
Yes of course need to clear the browser cache after editing the files.

PayPalRestSDK: Mock Response Instrument_Declined response when capturing order

I've been struggling to mock the 'INSTRUMENT_DECLINED' issue, which according to Paypal is an usual error after attempting to capture an order (https://developer.paypal.com/demo/checkout/#/pattern/server).
Correctly setting the header to mock the response will help me to simulate other errors from the docs https://developer.paypal.com/docs/business/test-and-go-live/simulation-tests/#orders.
I'm using Laravel back end and React front end.
I have already gotten the expected mocked response using axios and calling in the front-end:
return axios
.post(
`https://api-m.sandbox.paypal.com/v2/checkout/orders/${orderID}/capture`,
{},
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + accessToken,
"PayPal-Mock-Response":
'{"mock_application_codes":"INSTRUMENT_DECLINED"}',
},
}
)
.then((res) => {
console.log(res);
})
However, I don't want to expose accessToken into the front end, I'd prefer to do everything in the back-end with GuzzleHtttp.
I've already had a positive response - with 'status': 'COMPLETED' without adding PayPal-Mock-Response header like so:
$client = new \GuzzleHttp\Client();
$response = $client->request(
'POST',
'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . $paypalOrderId . '/capture',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $access_token,
// 'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]),
// 'PayPal-Mock-Response' => "['mock_application_codes':'INSTRUMENT_DECLINED]",
],
],
);
$data = json_decode($response->getBody(), true);
But when adding the PayPal-Mock-Response header like shown in the commented code from above, both attemps have returned this exception:
"message": "Client error: POST https://api-m.sandbox.paypal.com/v2/checkout/orders/9HG50866FU785784C/capture
resulted in a 404 Not Found response",
"exception": "GuzzleHttp\Exception\ClientException",
"file": "C:\xampp\htdocs\react\React-Laravel\vinos-gdl\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php",
This exception, I'm sure has to do to the way I'm passing the PayPal-Mock-Response header into the Guzzle http call but I can't find the way to do it correctly.
Any help is much appreciated.
UPDATE SOLVED**
Ok the way to go is sending the header like so:
'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]),
I dunno if I had any typo but I finally got it. I also used INTERNAL_SERVER_ERROR to get a 500 response from server and built a catch for every situation:
} catch (ClientException $e) {
if ($e->hasResponse()) {
return response()->json([
'msg' => 'Client Exception',
'error' => json_decode($e->getResponse()->getBody()),
], 400);
}
return response()->json([
'msg' => 'Client Exception',
'request' => $e->getRequest(),
$e->hasResponse() ? $e->getResponse() : ""
]);
// return response()->json(['msg' => 'Server Error', 'error' => report($e)]);
} catch (BadResponseException $e) {
if ($e->hasResponse()) {
return response()->json([
'msg' => 'Uknown Exception',
'error' => json_decode($e->getResponse()->getBody()),
], 500);
}
return response()->json([
'msg' => 'Uknown Exception',
'request' => $e->getRequest(),
$e->hasResponse() ? $e->getResponse() : ""
]);
}
Thanks for the ones who commented.
"PayPal-Mock-Response":
'{"mock_application_codes":"INSTRUMENT_DECLINED"}',
...
// 'PayPal-Mock-Response' => "['mock_application_codes':'INSTRUMENT_DECLINED]",
There is a difference betwen {} (JSON object) and [] (JSON array).
What you have inside the brackets is not an array, so its syntax is invalid. It doesn't map to anything PayPal expects, hence the 404.

How to get paymentMethodNonce in Braintree API?

I'm working in laravel 5.4
My transactions are successfull when I try a 'fake_nonce' type of string provided by the braintree docs. But when I tried to get the paymentMethodNonce it always gives me error like nonce not found. And sometimes http error!!! If I try to configure it by myself!
Take a look at my controller function below
public function addOrder(Request $request){
$customer = Braintree_Customer::create([
'firstName' => $request->guest_name,
'email' => $request->guest_email,
'phone' => $request->guest_phone
]);
$customer->success;
$customer->customer->id;
$find = Braintree_Customer::find($customer->customer->id);
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
$result = Braintree_Transaction::sale([
'amount' => $request->subtotal,
'paymentMethodNonce' => $nonceFromTheClient,
'options' => [
'submitForSettlement' => True
]
]);
if ($result->success) {
$settledTransaction = $result->transaction;
} else {
print_r($result->errors);
}
Cart::destroy();
return view('guest/track', compact('result'));
}
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
Your using the wrong nonce, this nonce must come from the DropIn ui and not be generated on your code.
Please check the onPaymentMethodReceived() method provided in the JS SDK.
Please check this reference

Payments with Laravel Omnipay (mollie gateway)

I'm currently stuck trying to create a payment with Omnipay. I have the following libraries installed in my project:
https://github.com/barryvdh/laravel-omnipay
https://github.com/thephpleague/omnipay-mollie
But I'm having problems starting. I see in the example that I need these params:
$params = [
'amount' => $order->amount,
'issuer' => $issuerId,
'description' => $order->description,
'returnUrl' => URL::action('PurchaseController#return', [$order->id]),
];
But what's the $issuerId? I would like to have an integration with Mollie.
Does someone maybe has an example of using laravel Omnipay with Mollie?
UPDATE:
I'm trying to submit my form with an ajax call. In my PHP function I have the following code:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'amount' => $ticket_order['order_total'] + $ticket_order['organiser_booking_fee'],
'description' => 'Kapelhoek wijkfeesten',
'returnUrl' => URL::action('EventCheckoutController#fallback'),
];
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response); die;
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
return $response->getRedirectResponse(); die;
} else {
// payment failed: display message to customer
echo $response->getMessage(); die;
}
But now I'm getting the following console error:
XMLHttpRequest cannot load https://www.mollie.com/payscreen/select-method/PRMtm6qnWG. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://kapelhoektickets.dev' is therefore not allowed access.
How can I fix this?
But what's the $issuerId?
Issuer ID is The issuer's unique identifier, for example ideal_ABNANL2A. When creating a payment, specify this ID as the issuer parameter to forward the consumer to their banking environment directly.
You can see a list of available issuers by calling this API url:
https://api.mollie.nl/v1/issuers
as stated in https://www.mollie.com/be/docs/reference/issuers/list
To read more about the issuer visit this part of the API-documentation:
https://www.mollie.com/be/docs/reference/issuers/get

Resources