I am using Laravel 8 and Laravel Cashier for my subscriptions
When I tried to cancel the subscription, it returns
Call to a member function stripe() on null
when cancelling the subscription
Even the Auth::check() returns true
Here is my cancelSubscription method
public function cancelSubscription(Request $request){
$user = $request->user();
try{
// if(Auth::check()){
$user->subscription('My-Subscription-Name')->cancel();
// }
if($request->ajax()) {
return response([
'success' => true,
'data' => "Successfully subscribed"
], 200);
}
}catch (\Throwable $ex) {
Log::critical($ex);
if($request->ajax()) {
return response([
'success' => false,
'data' => "Server Error"
], 422);
}
}
}
Here is the code in api.php for the cancel subscription method
Route::post('/cancel-sub',[SubscriptionController::class, 'cancelSubscription'])->middleware('auth:api');
I've also tried this
public function cancelSubscription(Request $request){
$user = UserSubscription::where('stripe_id', $request->subId)->first(); //returns subscription id
try{
// if(Auth::check()){
$user->subscription('My-Subscription-Name')->cancel();
// }
if($request->ajax()) {
return response([
'success' => true,
'data' => "Successfully subscribed"
], 200);
}
}catch (\Throwable $ex) {
Log::critical($ex);
if($request->ajax()) {
return response([
'success' => false,
'data' => "Server Error"
], 422);
}
}
}
I've also tried
$user = $request->user();
$subscriptions = $user->subscriptions()->active()->first();
$subscriptions->cancel();
but it still doesn't work. Any answers will be appreciated.
I also did dd(auth()->user()->subscription('My-Subscription-Name')) and it returns true and here is the result
Laravel\Cashier\Subscription {#1293
#guarded: []
#with: array:1 [
0 => "items"
]
#casts: array:1 [
"quantity" => "integer"
]
#dates: array:4 [
0 => "created_at"
1 => "ends_at"
2 => "trial_ends_at"
3 => "updated_at"
]
#billingCycleAnchor: null
#connection: "mysql"
#table: "subscriptions"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:12 [
"id" => 32
"user_tbl_id" => 4697
"name" => "My-Subscription-Name"
"stripe_id" => "sub_xxx"
"stripe_status" => "active"
"stripe_price" => "price_xxx"
"quantity" => 1
"trial_ends_at" => null
"ends_at" => null
"expires_at" => "2022-10-13 20:38:54"
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#original: array:12 [
"id" => 32
"user_tbl_id" => 4697
"name" => "Choi-Nomi"
"stripe_id" => "sub_xxx"
"stripe_status" => "active"
"stripe_price" => "price_xxx"
"quantity" => 1
"trial_ends_at" => null
"ends_at" => null
"expires_at" => "2022-10-13 20:38:54"
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#changes: []
#classCastCache: []
#attributeCastCache: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [
"items" => Illuminate\Database\Eloquent\Collection {#1303
#items: array:1 [
0 => Laravel\Cashier\SubscriptionItem {#1301
#guarded: []
#casts: array:1 [
"quantity" => "integer"
]
#connection: "mysql"
#table: "subscription_items"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:9 [
"id" => 33
"subscription_id" => 32
"stripe_id" => "si_xxx"
"stripe_product" => "prod_xxx"
"stripe_price" => "price_xxx"
"quantity" => 1
"user_subscription_id" => null
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#original: array:9 [
"id" => 33
"subscription_id" => 32
"stripe_id" => "si_xxx"
"stripe_product" => "prod_xxx"
"stripe_price" => "price_xxx"
"quantity" => 1
"user_subscription_id" => null
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#changes: []
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#paymentBehavior: "allow_incomplete"
#prorationBehavior: "create_prorations"
}
]
#escapeWhenCastingToString: false
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#couponId: null
#promotionCodeId: null
#allowPromotionCodes: false
#paymentBehavior: "allow_incomplete"
#prorationBehavior: "create_prorations"
}
I did have a look at my old project and what I did was add another method on User Model, to also delete the subscription related entries on the database
public function cancelStripeSubscription( $name = 'My Subscription Name') {
$sub = $this->subscription($name);
if ( $sub ) {
DB::table('subscriptions')->where('id', $sub->id)->delete();
DB::table('subscription_items')->where('subscription_id', $sub->id)->delete();
if ( $sub->stripe_status != 'canceled' )
$sub->cancelNow();
}
}
so you can simply call auth()->user()->cancelStripeSubscription();
In you code however, you should first check if they have active subscription or subscribe to specific product by checking subscription status
something like this;
public function cancelSubscription(Request $request){
try{
if ( auth()->user()->subscribed('default') )
/*
or if ( $user->subscribedToProduct('prod_premium', 'default'))
or if ( $user->subscribedToPrice('price_basic_monthly', 'default'))
or
$sub = auth()->user()->subscription('My-Subscription-Name')
if ( $sub && $sub->stripe_status == 'canceled' )
*/
{
auth()->user()->subscription('My-Subscription-Name')->cancel();
} else {
return response([ 'error' => true, 'message' => 'You have no active subscription' ], 404);
}
.
.
}
.
.
}
Furthermore, verify if that subscripton your trying to cancel really is a subscription object and check if user is even have a subscription
public function cancelSubscription(Request $request){
return [
'request' => $request->all(),
'user' => auth()->user(),
'subscription' => auth()->user()->subscription('My-Subscription-Name'),
'subscriptions' => auth()->user()->subscriptions()
]
.
.
}
Related
I am having great difficulty in making a payment preference in requecission of the paid market.
$pagamento = $mp->setPreferencia
"items" => [
[
"picture_url" => "https://i.imgur.com/FlFgLr5.jpeg",
"title" => "Saldo #smsgobr",
"description" => "Saldo para o bot #smsgobr no Telegram",
"quantity" => 1,
"currency_id" => "BRL",
"unit_price" => (float)$valor
],
"external_reference" => $hash,
"expiration_date_to" => date ('c', strtotime('+1 day'))
],
[
"payment_methods" => array (
"excluded_payment_types" => array (
"id" => "ticket",
"id" => "bank_transfer",
"id" => "atm",
"id" => "debit_card",
"id" => "account_money"
]);
thank you very much in advance
I am fetching data from database using stored procedure but getting below error
htmlspecialchars() expects parameter 1 to be string, array
Below is the controllers
public function index()
{
$id=2;
// $single_blog['user'] = UserRole::where('id',$id)->get();
$single_blog['user'] = DB::select("CALL FetchUserRoleWithId(".$id.")");
return view('home',$single_blog);
}
In view simple use only as
{{$user}}
If i use get() method then properly print $user data in blade file.
But using stored procedure getting below error
"htmlspecialchars() expects parameter 1 to be string, array"
Using stored procedure getting below data
array:1 [▼
"user" => array:1 [▼
0 => {#1237 ▼
+"id": 2
+"name": "SO"
+"status": "1"
+"created_by": null
}
]
]
Using get() method getting below data
array:1 [▼
"user" => Illuminate\Database\Eloquent\Collection {#1257 ▼
#items: array:1 [▼
0 => App\Models\UserRole {#1258 ▼
#fillable: array:4 [▶]
#connection: "mysql"
#table: "user_roles"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:8 [▼
"id" => 2
"name" => "SO"
"status" => "1"
"created_by" => null
"updated_by" => null
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#original: array:8 [▶]
#changes: []
#casts: array:1 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
#forceDeleting: false
}
]
#escapeWhenCastingToString: false
}
]
Anyone have idea how to display this data in blade file.
I'm trying to create a node via drupal API but I have this error:
Got error 'PHP message: PHP Fatal error: Uncaught GuzzleHttp\\Exception\\ClientException: Client error: `POST https://site.it/entity/node?_format=hal_json` resulted in a `422 Unprocessable Entity` response:\n{"message":"Could not determine entity type bundle: \\u0022type\\u0022 field is missing."}
this is my function:
public function createFaq($notes, $telegram_id){
$url = "/entity/node?_format=hal_json";
$opt = [
'headers' => self::$baseHeader,
'body' => json_encode([
[
'type' => [ ['target_id' => 'faq'] ],
'title' => 'title',
'utente' => [ [ 'target_id' => '123462' ] ],
'field_domanda' => [ [ 'value' => $notes['domanda'] ] ],
'field_presenza' => [ [ 'value' => $notes['presenza'] == "Si"? true : false ] ],
]
])
];
$response = $this->client->request('POST', $url , $opt);
$r = json_decode( $response->getBody());
return $r;
}
But i't really strange because this other function is working
public static function createUser($title){
$url= "/entity/node?_format=hal_json";
$opt = [
'headers' => self::$baseHeader,
'body' => json_encode([
'title' => [ [ 'value' => $title ] ],
'type' => [ [ 'target_id' => 'article' ] ],
])
];
$response = $this->client->request('POST', $url , $opt);
$r = json_decode( $response->getBody());
return $r;
}
Can someone understood my error?
This is because the json data are enclosed in square brackets twice, just remove one pair :
$opt = [
'headers' => self::$baseHeader,
'body' => json_encode([
//[
'type' => [ ['target_id' => 'faq'] ],
'title' => 'title',
'utente' => [ [ 'target_id' => '123462' ] ],
'field_domanda' => [ [ 'value' => $notes['domanda'] ] ],
'field_presenza' => [ [ 'value' => $notes['presenza'] == "Si"? true : false ] ],
//]
])
];
I'm using Laravel for about one month and i wanted to try the guzzle module, to get last fm user infos
I've tried this request in my controller :
$client = new \GuzzleHttp\Client(['base_uri' => 'http://ws.audioscrobbler.com/']);
//$client = new \GuzzleHttp\Client();
$response = $client->get('2.0/?method=user.getinfo&user=rj&api_key=xxxxxxxxxx&format=json');
dd($response);
but i've just got this kind of things
Response {#190 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:11 [▼
"date" => array:1 [▶]
"server" => array:1 [▼
0 => "Apache/2.2.22 (Unix)"
]
"x-web-node" => array:1 [▼
0 => "www223"
]
"access-control-allow-origin" => array:1 [▼
0 => "*"
]
"access-control-allow-methods" => array:1 [▼
0 => "POST, GET, OPTIONS"
]
"access-control-max-age" => array:1 [▼
0 => "86400"
]
"cache-control" => array:1 [▼
0 => "max-age=60"
]
"expires" => array:1 [▶]
"content-length" => array:1 [▼
0 => "642"
]
"connection" => array:1 [▶]
"content-type" => array:1 [▶]
]
-headerLines: array:11 [▶]
-protocol: "1.0"
-stream: Stream {#181 ▼
-stream: :stream {#237 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
Could someone help me with an example or something :) ?
For body's contents:
echo $response->getBody();
Well I am very very new to Laravel. So I am learning the basics from Laracast actually. I have a table called songs , a model Song.php as below:
<?php namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Song extends Eloquent{
}
And a Controller SongsController.php :
use App\Song;
use DB;
class SongsController extends Controller
{
function index() {
$songs = Song::get();
$songs2 = DB::table('songs')->get();dd($songs2);
//$mysong2 = Song::whereSlug('as-long-as-you-love-me')->first();
}
}
So I expect $songs and $songs2 are same and produce same result. but dd($songs) produce result something like below:
Collection {#146 ▼
#items: array:1 [▼
0 => Song {#147 ▼
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:6 [▼
"id" => "1"
"title" => "As Long as you Love me"
"slug" => "as-long-as-you-love-me"
"lyrics" => null
"created_at" => "2015-06-21 00:00:00"
"updated_at" => "2015-06-21 00:00:00"
]
#original: array:6 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]
}
and $songs2 produces ( which I think the actual,but not sure):
array:1 [▼
0 => {#145 ▼
+"id": "1"
+"title": "As Long as you Love me"
+"slug": "as-long-as-you-love-me"
+"lyrics": null
+"created_at": "2015-06-21 00:00:00"
+"updated_at": "2015-06-21 00:00:00"
}
]
So I want to know which one should I use ? And is there any mistake I am doing ?
there is no mistake.
for $songs you are using eloquent with function get(), which will always return an object of type
Illuminate\Database\Eloquent\Collection
but for $songs2 you are using query builder with function get(), which will always return an array of
stdClass objects.
thats why you see different results.
both are correct and you can use both, but if you have created a model for your song, then use eloquent instead of query builder.