Laravel Cashier 10 - Errors trying to show a Stripe element - php

I am using this tutorial to integrate Stripe into my Laravel site using Cashier:
https://appdividend.com/2018/12/05/laravel-stripe-payment-gateway-integration-tutorial-with-example/
This tutorial was written for Cashier 9, so it does not work out of the box with Cashier 10. However, it does work making the adjustments in this SO answer: https://stackoverflow.com/a/57812759/2002457
Except, it only works for existing Stripe customers. When I register a brand new user and try to view a plan, it gives this error: User is not a Stripe customer. See the createAsStripeCustomer method.
So, I try to do just that:
public function show(Plan $plan, Request $request)
{
if($request->user()->stripe_id === null)
{
$request->user()->createAsStripeCustomer();
}
$paymentMethods = $request->user()->paymentMethods();
$intent = $request->user()->createSetupIntent();
return view('plans.show', compact('plan', 'intent'));
}
Which yields this error: No API key provided. (HINT: set your API key using "Stripe::setApiKey(<API-KEY>)". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support#stripe.com if you have any questions.
This SO answer addresses this problem: https://stackoverflow.com/a/34508056/2002457
But the solution only works in Cashier 9, because Billable changed, so it's not clear how to set the API key.
What am I doing wrong here to create a new customer if they're not a Stripe customer already?
EDIT
- I am using the default cashier config, and I've confirmed it is pointing at the .env vars.
I put in a dd(config('cashier.key')); to confirm that config is working
I removed the old services.php config parts
The env vars are set correctly
Here's the show method:
public function show(Plan $plan, Request $request)
{
$paymentMethods = $request->user()->paymentMethods();
$intent = $request->user()->createSetupIntent();
return view('plans.show', compact('plan', 'intent'));
}
And here's the error now: User is not a Stripe customer. See the createAsStripeCustomer method.

Cashier 10 introduced some changes to the configuration including setting up the cashier.php configuration file. The upgrade guide details how, this pull request commit shows the file.
Few things to debug this:
make sure you've setup the config for cashier 10 correctly.
make sure that the config key cashier.key is available (e.g. ddd(config('cashier.key'));
double check that that your .env var's are setup correctly for stripe's API key

Related

How to setup OMISE PHP SDK to Laravel framework

I'm starting to learn Omise Payment Getway. On Omise documentation have information about PHP SDK. I'm using Laravel Framework on it. However, i'm struggling to implement the Omise PHP SDK into my Laravel site..
I have 2 question when setup the Omise PHP SDK :
The integration - after i install Omise by composer. i don't know how to use it. first, i want to display my Omise balance. here is my code on controller
use Omise\OmiseBalance;
class OmiseController extends Controller
{
public function index()
{
$balance = OmiseBalance::retrieve();
dd($balance);
}
}
but display error
Class "Omise\OmiseBalance" not found
i tried other way, but still not work..
Place the Secret and Public Key - where should i put the Secret key and Public Key on my Laravel. and how to fetch the keys?
Currently i just put this keys into my file .env
OMISE_PUBLIC_KEY=pkey_test_xxx
OMISE_SECRET_KEY=skey_test_xxx
OMISE_API_VERSION=2019-05-29
What is the correct way for me to integrate Omise PHP SDK into my Laravel Site. please help.

Missing Authorization key in headers array in laravel Shopify app using shopify cli

I had to install shopify-cli for develop shopify app with laravel. installation and test app are created successfully but when am i calling the API of shopify in Laravel app i got this error.
I am check header but no authorisation token pass. So my question how to get authenticate token get in Laravel starter app and call API of Shopify and i was follow PHP guide REST Admin API reference but without session i can not access shopify REST Admin API reference.
my code show like this...
Route::get('/rest-example', function (Request $request) {
/** #var AuthSession */
// $session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active
$session = OAuth::callback(
$request->cookie(),
$request->query(),
['App\Lib\CookieHandler', 'saveShopifyCookie'],
);
$client = new Rest($session->getShop(), $session->getAccessToken());
$result = $client->get('products', [], ['limit' => 5]);
return response($result->getDecodedBody());
})->middleware('shopify.auth:online')->name('rest-api');
I think you want to create Custom App (not embedded) for your store.
You can read here about difference. I spent the whole day searching for solutions until get the idea.
All you need to do is to create a Custom App in your store, then get Admin API access token with you can use for REST API calls.
Here is my small example how I get it.
use Shopify\Clients\Rest;
Route::get('/test', function(Request $request) {
$client = new Rest(
env('SHOPIFY_APP_HOST_NAME'),
env('SHOPIFY_APP_ADMIN_ACCESS_TOKEN') // shpat_***
);
dd($client->get('products')->getDecodedBody());
});

Laravel Cashier sends no POST request body on heroku

Ive been running into issues with Laravel Cashier when i deployed my app to heroku.
One my local environment everything is fine but on my staging server , no POST request body is ever sent to stripe.
I tried swapping api keys as i thought maybe the api version on stripe differs between the two but that doesn't work (see screenshots below)
Things i know are correct
API creds , they wont show up on stripe logs if it wasent
Composer version matches both environments (Laravel Cashier 10.5.2, Laravel 5.8.36, Stripe-php 17.7.0)
I cant seem to find anything that logs out going api requests. Ive even tried manually calling the stripe functions as low as i can get in the stack still no POST body.
Im sure some one else has ran into this. Google search on laravel cashier ALWAYS sends me back to the laravel website, like WTF.
this is my stripe method on my User model. All other code is from Cashier
public function activateSubscription() {
if ($this->hasStripeId() &&
$this->has_default_payment_method &&
$this->has_active_subscription) {
return;
}
try {
$this->newSubscription(env('STRIPE_SUBSCRIPTION_NAME'), env('STRIPE_PLAN_ID'))
->create(null, [
'name' => $this->fullname,
'email' => $this->email,
]);
$this->notify(new UserRegistered());
} catch (\Stripe\Exception\InvalidRequestException $e) {
Log::debug('Invalid Request', [
'body' => $e->getHttpBody(),
'headers' => $e->getHttpHeaders(),
'json' => $e->getJsonBody(),
'error_code' => $e->getStripeCode(),
]);
}
}
Edit
Ive removed some personal details from the POST request body
I figured it out , i had a \n at the end of my stripe secret api key on heroku environment variables.
For some reason that caused all requests to stripe to strip the POST body.
Removed that, ran a php artisan config:clear and it worked

Laravel 7 - Use REST API instead of a database

I am using a rest api to store/retrieve my data which is stored in a postgres database. The api is not laravel, its an external service!
Now i want to create a website with laravel (framework version 7.3.0) and i'm stuck on how to implement the api calls correctly.
For example: i want to have a custom user provider with which users can log-in on the website. But the validation of the provided credentials is done by the api not by laravel.
How do i do that?
Just make a Registration controller and a Login Controller by "php artisan make:controller ControllerName" and write Authentication logics there.
In previous versions of Laravel you had a command like "php artisan make:auth" that will make everything needed to do these operations. But in Laravel 7.0 you need to install a package called laravel/ui.
Run "composer required laravel/ui" to install that package
Then run "php artisan ui bootstrap --auth"
and now, you are able to run "php artisan make:auth"
This command will make whole Registration (Signup) and Login system for you.
and in orer to work with REST, you may need to know REST (Http) verbs. Learn about GET, POST, PUT, PATH, DELETE requests and how to make those request with PHP and Laravel collection methods. Learn about JSON parsing, encoding, and decoding. Then you can work with REST easily. and work without any template codes from other packages.
Thank you so much. I hope this answer give you some new information/thought. Thanks again.
Edit:
This might not be the best way. But this is what I did at that time. I tried curl and guzzle to build the request with session cookie and everything in the header to make it look like a request from a web browser. Couldn't make it work.
I used the web socket's channel id for the browser I want the changes to happen and concatenated it with the other things, then encrypted it with encrypt($string). After that, I used the encrypted string to generate a QR code.
Mobile app (which was already logged in as an authenticated used) scanned it and made a post request with that QR string and other data. Passport took care of the authentication part of this request. After decrypting the QR string I had the web socket's channel id.
Then I broadcasted in that channel with proper event and data. Caught that broadcast in the browser and reloaded that page with JavaScript.
/*... processing other data ...*/
$broadcastService = new BroadcastService();
$broadcastService->trigger($channelId, $eventName, encrypt($$data));
/*... returned response to the mobile app...*/
My BroadcastService :
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Pusher\Pusher;
use Pusher\PusherException;
class BroadcastService {
public $broadcast = null;
public function __construct() {
$config = config('broadcasting.connections.pusher');
try {
$this->broadcast = new Pusher($config['key'], $config['secret'], $config['app_id'], $config['options']);
} catch (PusherException $e) {
Log::info($e->getMessage());
}
}
public function trigger($channel, $event, $data) {
$this->broadcast->trigger($channel, $event, $data);
}
}
In my view :
<script src="{{asset('assets/js/pusher.js')}}"></script>
<script src="{{asset('assets/js/app.js')}}" ></script>
<script>
<?php
use Illuminate\Support\Facades\Cookie;
$channel = 'Channel id';
?>
Echo.channel('{{$channel}}')
.listen('.myEvent' , data => {
// processing data
window.location.reload();
});
</script>
I used Laravel Echo for this.
Again this is not the best way to do it. This is something that just worked for me for that particular feature.
There may be a lot of better ways to do it. If someone knows a better approach, please let me know.
As of my understanding, you are want to implement user creation and authentication over REST. And then retrieve data from the database. Correct me if I'm wrong.
And I'm guessing you already know how to communicate over API using token. You are just stuck with how to implement it with laravel.
You can use Laravel Passport for the authentication part. It has really good documentation.
Also, make use of this medium article. It will help you to go over the step by step process.

Stripe - No API key provided (Laravel 5.1)

I have problem with providing the Stripe API key. Everything is included, packages, all dependencies...
The error message I get: No API key provided. (HINT: set your API key using "Stripe::setApiKey()". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support#stripe.com if you have any questions.
Controller:
public function upgradeBronze() {
$bid = Session::get('builderId');
Stripe::setApiKey(env('KEY_SECRET'));
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$user = \App\User::find($bid);
$user->subscription('monthly')->create($token);
return Redirect::route('builders-packages');
} catch(\Stripe\Error\Card $e) {
return Redirect::route('builders-packages');
}
}
Error SS: http://pokit.org/get/img/5f7886d0d9a50ecf349312225c8c47ea.jpg
SOLVED
It seems that Stripe integration doesn't work fine on Laravel 5.1 version, if you follow the default documentation you probably won't succeed.
In this case the solution was to put the stripe api key into AppServiceProvider, into register() class.
Setting stripe API keys in my .env file (worked for me, Laravel 5.8):
STRIPE_KEY=your pk key here
STRIPE_SECRET=your sk key here
Set the Stripe API key from stripe.php like
public static $apiKey='sk_test_your api_key';

Categories