preference settings api mercadopago - api

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

Related

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

Call a controller with json data on api plateform

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",
* },
* },
* },
* },
* }
* }
* }
* )
*/

How to Alias one of the table sql in cakephp 3.6.3

I'm trying to access Contacts. I'm getting below error
Error: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'Contacts'
If you are using SQL keywords as table column names, you can enable identifier quoting for your database connection in config/app.php.
Check SQL Query Screenshot
How do I setAlias() in table associations ?
ContactsController.php
public function index()
{
$this->paginate = [
'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status',
'Secteurs', 'Products']
];
$contacts = $this->paginate($this->Contacts);
$this->set(compact('contacts'));
}
public function view($id = null)
{
$contact = $this->Contacts->get($id, [
'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status',
'Secteurs', 'Products', 'Leads', 'Accounts']
]);
$this->set('contact', $contact);
}
ContactsTable.php
$this->setTable('contacts');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_type_id'
]);
$this->belongsTo('Leads', [
'foreignKey' => 'lead_id'
]);
$this->belongsTo('SourceProspects', [
'foreignKey' => 'source_prospect_id'
]);
$this->belongsTo('Accounts', [
'foreignKey' => 'account_id'
]);
$this->belongsTo('Status', [
'foreignKey' => 'statut_id'
]);
$this->belongsTo('Secteurs', [
'foreignKey' => 'secteur_id'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id'
]);
$this->hasMany('Accounts', [
'foreignKey' => 'contact_id'
]);
$this->hasMany('Leads', [
'foreignKey' => 'contact_id'
]);
}
The problem seems to be in ContractsTable here
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_type_id'
]);
in this way cake join the Contacts table with itself so creating a non unique alias
maybe is just a typo and you wanted to do
$this->belongsTo('ContactTypes', [
'foreignKey' => 'contact_type_id'
]);
but if you actually want to use that relationship then you have to alias the joined Contacts table
$this->belongsTo('ParentContacts', [ // choose your alias here
'className' => 'Contacts'
'foreignKey' => 'contact_type_id'
]);
so every time you have to refer to the joined table you can do something like
'contain' => [
...,
'ParentContacts',
],

Correct JSON ouput iPhone json_encode

I'm trying to get a correct json output for iPhone i'm using the code:
<?php
$post = array('items' => 1, 'title' => message, 'description' => description);
echo json_encode($post);
?>
And the output is:
{"items":1,"title":"message","description":"description"}
But i want a output with [
{
"items": [
{
"title": "message",
"description": "description"
}
]
}
Can someone tell me how to do that?
try
$post = array('items' => array( 0 => array('title' => message, 'description' => description)));
(warning: untested!)