Call a controller with json data on api plateform - api

I have build my Application with make:entity,
After I create a query who link all the table to get what I want ( a bit of all tables )
My query is working but now I want to use API Plateform to handling routes.
But I find no way to call my controller with API Plateform notation.
Annotation on Caractéristiques entity.
#[ApiResource(collectionOperations: ['requete' => [
'method' => 'get',
'path' => '/requete',
'controller' => ApiRequeteController::class,
'openapi_context' => [
'summary' => 'get requete',
'requestBody' => [
'content' => [
'application/json' => [
'schema' => [
'type' => 'object',
'properties' =>
[
'montant' => ['type' => 'int'],
'loc' => ['type' => 'string'],
'stat' => ['type' => 'string'],
'type' => ['type' => 'string'],
'sect' => ['type' => 'string'],
],
],
'example' => [
'montant' => 1000000,
'loc' => "test",
'stat' => "test",
'type' => "test",
'sect' => "test",
],
],
],
],
],
],
])]
I have found this way but not working.
give me:
syntax error, unexpected '=>' (T_DOUBLE_ARROW)
on
'method' => 'get',
Any way to do this ?

With POST and another writing
* collectionOperations= {"requete" = {
* "method" = "POST",
* "path" = "/requete",
* "controller" = App\Controller\ApiRequeteController::class,
* "openapi_context" = {
* "summary" = "get requete",
* "requestBody" = {
* "content" = {
* "application/json" = {
* "schema" = {
* "type" = "object",
* "properties" =
* {
* "montant" = {"type" = "int"},
* "loc" = {"type" = "string"},
* "stat" = {"type" = "string"},
* "type" = {"type" = "string"},
* "sect" = {"type" = "string"},
* },
* },
* "example" = {
* "montant" = 1000000,
* "loc" = "test",
* "stat" = "test",
* "type" = "test",
* "sect" = "test",
* },
* },
* },
* },
* }
* }
* }
* )
*/

Related

preference settings api mercadopago

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

Call to a member function stripe() on null when cancelling the subscription

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()
]
.
.
}

Drupal create node by post Api call fail with message "Could not determine entity type bundle: \\u0022type\\u0022 field is missing."}

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 ] ],
//]
])
];

Error Exception Array to string conversion

I want to have a response in postman for my API... but when I send a raw in body of postman
I faced to array to string conversion error
Error Exception (E_NOTICE)
Array to string conversion
this is my raw
{
"account_type": "real",
"address": "12131",
"card_bank": "",
"city": {
"id": 436,
"name": "مشهد",
"state_id": 11,
"state_name": "خراسان رضوی"
},
"code_melli": "",
"email": "",
"family": "اسداله پور",
"id": 171,
"mobile": "0911111111",
"name": "مهدی",
"phone": "",
"role": "usual",
"card": [
{
"count": 1,
"id": 2,
"id_product": 267,
"productM": null,
"seller": null,
"id_seller": 0,
"totalPrice": "97500"
},
{
"count": 1,
"id": 3,
"id_product": 696,
"productM": null,
"seller": null,
"id_seller": 0,
"totalPrice": "115000"
}
],
"state": {
"id": 11,
"name": "خراسان رضوی"
}
}
and this is my web service
about this route
public function ChangeInformation(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required',
'family' => 'required',
'mobile' => 'required',
],
[
'name.required' => 'لطفا نام خود را وارد کنید',
'family.required' => 'لطفا نام خانوادگی خود را وارد کنید',
'mobile.required' => 'لطفا موبایل خود را وارد کنید',
]);
if ($validator->fails()) {
self::$result_json['error'] = 1;
self::$result_json['error_code'] = 1;
self::$result_json['msg'] = $validator->messages()->first();
}
else{
$user = DB::table('user_app')
->where('id', $request->get('token'))
->first();
$input = $request->except('img');
/*if ($request->hasFile('img')) {
$file_param = $request->file('img');
$fileName = $file_param->getClientOriginalName();
$fileName = substr($fileName, 0, strrpos($fileName, '.'));
$fileName = str_replace(' ', '', $fileName);
$Random_Number = rand(0, 9999);
$name_file_new = $fileName . '-' . $Random_Number . '.' . $file_param->getClientOriginalExtension();
//$thumb_img = Image::make($file->getRealPath())->resize(100, 100);
$destinationPath = 'uploads/avatars/';
$file_param->move($destinationPath, $name_file_new);
$path_file = 'uploads/avatars/' . $name_file_new;
$input['img'] = $path_file;
}
else {
self::$result_json['error'] = 1;
self::$result_json['error_code'] = 1;
self::$result_json['msg'] = 'تصویر نادرست است .';
}*/
DB::table('user_app')
->where('id',$user->id)
->update($input);
$city = DB::table('cities')
->where('id', $input['shahr'])
->first();
$state = DB::table('state')
->where('id', $input['ostan'])
->first();
$user_data = DB::table('user_app')
->where('id',$user->id)
->select('account_type', 'address','email','card_bank', 'shahr as city',
'family', 'id', 'mobile', 'name', 'img', 'phone', 'role', 'ostan as state', 'zip_code')
->first();
$user_data->city = $city;
$user_data->state = $state;
self::$result_json['success'] = 1;
self::$result_json['user_data'] = $user_data;
}
it worked when I send data in form_data but do not work in raw when i send my data
you need to convert your associative array into json object format using "json_encode() function" which is string, postman cannot read array, I hope this one will do

datatables, change results from SSI

i use the SSI-Solution from the datatables-examples.
Now, i want to change and edit some results of the database (for example, i want to change a stored id throug an icon for this id etc.).
For the moment i have no idear at wich point i can catch the results and work with them. Maybe someone can explain it for me.
Here is the code if use for getting the database results
// DB table to use
$table = 'MODUL_1_CONTACTS';
// Table's primary key
$primaryKey = 'ACCOUNT_ID';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'CONTACT_GROUP', 'dt' => 0 ),
array( 'db' => 'KD_NO', 'dt' => 1 ),
array( 'db' => 'TYPE', 'dt' => 2 ),
array( 'db' => 'ORG_NAME', 'dt' => 3 ),
array( 'db' => 'VORNAME', 'dt' => 4 ),
array( 'db' => 'NAME', 'dt' => 5 )
);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
require( $vz.'assets/global/plugins/datatables/ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $table, $primaryKey, $columns )
);
Here is the JS Code
var table = $('#ajax_table1').DataTable( {
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline( {
url: 'data.php',
pages: 5 // number of pages to cache
} ),
"columnDefs": [
{
"targets": -1,
"data": null,
"defaultContent": "<button class=\"btn yellow-mint uppercase btn-circle\" data-toggle=\"confirmation\" id=\"bs_confirmation_demo_1\">Confirmation 1</button><div class=\"btn-group pull-right\"><button class=\"btn green btn-xs btn-outline dropdown-toggle\" data-toggle=\"dropdown\">Tools<i class=\"fa fa-angle-down\"></i></button><ul class=\"dropdown-menu pull-right\"><li><i class=\"fa fa-trash\"></i> delete </li><li><i class=\"fa fa-file-text\"></i> write letter </li><li><i class=\"fa fa-calendar-plus-ot\"></i> new todo/date </li><li><i class=\"fa fa-file-cubes\"></i> new work </li><li><i class=\"fa fa-print\"></i> Print </li><li><i class=\"fa fa-file-pdf-o\"></i> Save as PDF </li><li><i class=\"fa fa-file-excel-o\"></i> Export to Excel </li></ul></div>"
}],
"language": {
url: '../lang/<?php echo $_GET['lang'].'/'.$_GET['lang']; ?>.json'
},
// setup buttons extentension: http://datatables.net/extensions/buttons/
buttons: [
{ extend: 'print', className: 'btn dark btn-outline' },
{ extend: 'pdf', className: 'btn green btn-outline' },
{ extend: 'csv', className: 'btn purple btn-outline' }
],
"lengthMenu": [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"] // change per page values here
],
//responsive: true,
"bFilter": true,
// set the initial value
"pageLength": 10,
//Layout
"dom": "<'pull-left'f><'pull-right' B>r<'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>><'row'<'col-md-5 col-sm-12'l><'col-md-7 col-sm-12'>>",
} );