Description
I'm getting an error when attempting to create a stripe subscription using Laravel + the API.
Before you create the subscription you must get the token by requesting it, I have successfully created this token and I'm now using the "createSubscription()" method from the API (referenced in my code), but this is where the error is occurring.
Code
public function create()
{
$user = Auth::user();
$plan = 'prod_**********';
// Do some checks
if ($user->subscribed('main')){
return [
'status' => 'failed',
'message' => 'You are already subscribed!',
];
}
// Set the stripe Key
Stripe::setApiKey(env('STRIPE_SECRET'));
// Create the stripe token
try {
$stripeToken = Token::create([
'card' => [
'number' => str_replace(' ', '', Input::get('number')),
'exp_month' => Input::get('exp_month'),
'exp_year' => Input::get('exp_year'),
'cvc' => Input::get('cvc')
]
]);
}
catch (\Stripe\Error\InvalidRequest $e)
{
return [
'status' => 'failed',
'message' => $e->getMessage(),
];
}
try{
// This is the line thats failing
$user->newSubscription('main', $plan)->create($stripeToken);
} catch (\Stripe\Error\InvalidRequest $e) {
dd($e->getMessage());
}
return [
'status' => 'success',
'message' => 'Subscription was successful!',
];
}
The Error
The error in full is:
Invalid request. Hint: check the encoding for your request parameters
and URL (http://en.wikipedia.org/wiki/percent-encoding). For
assistance, email support#stripe.com.
I've spoken to stripe support and they're saying they think the error is on my end, everything seems good on the stripe end.
I've checked the card detailed and customer details are correct (This is why the token being created).
I've searched this error but nothing seems to come up for this, there are other questions somewhat similar but no answers.
I've uninstalled / reinstalled laravel-cashier package to no success.
Whats strange is how i've managed to solve this problem. It would seem that passing the entire stripe token does not work and instead I only needed to pass the token ID.
Simply changing
$user->newSubscription('main', $plan)->create($stripeToken);
to this
$user->newSubscription('main', $plan)->create($stripeToken->id);
Solved this error
Invalid request. Hint: check the encoding for your request parameters
and URL (http://en.wikipedia.org/wiki/percent-encoding). For
assistance, email support#stripe.com.
I'm sure that nowhere in either documentation is states that this is the solution? Or maybe I overlooked this somewhere... but this has solved it for me.
Related
I am setting up Twilio's Verify service to authenticate with a text number. The service works and sends a code to a cell phone, but when it gets to the verificationChecks part of the code, I receive the following error Twilio\Rest\Verify\V2\Service\VerificationCheckList::create(): Argument #1 ($options) must be of type array, string given, called in /Users/charles/Documents/Development/guard/app/Http/Controllers/Auth/RegisteredUserController.php on line 83.
If it helps, I am using the following tutorial on Twilio's site. And if you look at Twilio's API where their API still matches their tutorial document.
RegisteredUserController.php
...
protected function verify(Request $request)
{
$data = $request->validate([
'verification_code' => ['required', 'numeric'],
'phone_number' => ['required', 'string'],
]);
/* Get credentials from .env */
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio_sid = getenv("TWILIO_SID");
$twilio_verify_sid = getenv("TWILIO_VERIFY_SID");
$twilio = new Client($twilio_sid, $token);
$verification = $twilio->verify->v2->services($twilio_verify_sid)
->verificationChecks
->create($data['verification_code'], array('to' => $data['phone_number']));
if ($verification->valid) {
$user = tap(User::where('phone_number', $data['phone_number']))->update(['isVerified' => true]);
/* Authenticate user */
Auth::login($user->first_name());
return redirect()->route('home')->with(['message' => 'Phone number verified']);
}
return back()->with(['phone_number' => $data['phone_number'], 'error' => 'Invalid verification code entered!']);
}
...
The same issue just popped up for me over the weekend on code that I haven't touched in a very long time. I believe they updated something recently and the docs may be outdated. The docs show sending a string, while if you look at the actual vendor file, it is looking for an array now.
Try this:
$verification = $twilio->verify->v2->services($twilio_verify_sid)
->verificationChecks
->create(['code' => $data['verification_code'], 'to' => $data['phone_number']]);
I have a weird issue with microsoft graph api v1.
I am trying to setup a subscription, so that I get webhook notification after a new outlook email arrives.
$body = [
"changeType" => "created,updated",
"notificationUrl" => route('api.outlook.push'),
"resource" => "me/messages",
"expirationDateTime" => now()->addMinutes(self::SUBSCRIPTION_EXPIRATION_MINUTES),
];
$response = null;
try {
$response = $this->service->createRequest('POST', '/subscriptions')
->attachBody(json_encode($body))
->setReturnType(Subscription::class)
->execute();
} catch (Exception $exception) {
logger()->info('outlook subscription exception', ['message' => $exception->getMessage()]);
}
This seems to be working correctly as microsoft is sending a notification to specified url with verification code, that I'm returning and the message says that subscription was created. The issue is that even though it was set up properly - I am not getting a single one webhook. Did any of you guys had this issue and manage to fix it?
I am developing a Web application. In my app, I need to login user to the AWS cognito system. I can log in to the system successfully. But the only problem is when the username and password provided by the user are not valid, my Laravel framework kills the application returning 500 internal server status code. But I want to do something else when the username and password are not valid. I tried using try catch block, but it is not overriding the error. Please, see my code below.
try{
$client = new CognitoIdentityProviderClient([
'version' => 'latest',
'region' => env('AWS_REGION', '')
'credentials' => [
'key' => env('AWS_IAM_KEY', ''),
'secret' => env('AWS_IAM_SECRET', '')
]
]);
$result = $client->adminInitiateAuth([
'AuthFlow' => 'ADMIN_NO_SRP_AUTH',
'ClientId' => COGNITO_APP_CLIENT_ID,
'UserPoolId' => COGNITO_USER_POOL_ID,
'AuthParameters' => [
'USERNAME' => $request->email,
'PASSWORD' => $request->password,
],
]);
//Error thrown here if the username and password are not valid.
//continue
}
catch(Exception $e)
{
//I want to do something here if the error is thrown because of the invalid credentials without killing the app by throwing 500 status code.
}
As you can see in the above code if the user credentials are not valid, the SDK will throw the error. It will kill the app by returning 500 status code. I do not want to stop there. So, I used the try catch block to catch the error and continue in the code. But the try catch block is not catching the error as well.
This is the screenshot.
So, how can I stop the AWS sdk from stopping the application throwing 500 status code?
Finally, I found the solution. Laravel works with namespaces. So, instead of using just Exception in the try catch block, I needed to put "\" as a prefix. So the try catch becomes like this.
try{
//code
}
catch(\Exception $e) //pay attention to the "\"
{
}
I'm currently trying to implement a way to synchronize my PHP App calendar with the Outlook calendar of my clients, using Azure API.
I use OAuth2 and the custom Microsoft provider by Steven Maguire.
I currently run in an issue where I get an error in my response :
{"error":"unsupported_grant_type","error_description":"The provided value for the input parameter 'grant_type' is not valid. Expected values are the following: 'authorization_code', 'refresh_token'."}
I'm having trouble understanding why the grant_type password is not supported, even though it says on the documentation of Azure that it is.
The request looks like this :
client_id=44bef79b-**********************&client_secret=H****************&redirect_uri=https%3A%2F%2F192.168.1.123%2Fmapeyral%2Fcalendarsync.php&grant_type=password&username=******************&password=***********&scope=openid%20profile%20offline_access%20Calendars.ReadWrite
The Authorize url used is : https://login.live.com/oauth20_token.srf
as defined in the Steven Maguire provider.
The header contains the content-type application/x-www-form-urlencoded (I've seen a lot of post where this was what caused the error).
Some of my code :
$this->provider = new Microsoft([
'clientId' => MicrosoftGraphConstants::CLIENT_ID,
'clientSecret' => MicrosoftGraphConstants::CLIENT_SECRET,
'redirectUri' => MicrosoftGraphConstants::REDIRECT_URI,
'urlAuthorize' => MicrosoftGraphConstants::AUTHORITY_URL . MicrosoftGraphConstants::AUTHORIZE_ENDPOINT,
'urlAccessToken' => MicrosoftGraphConstants::AUTHORITY_URL . MicrosoftGraphConstants::TOKEN_ENDPOINT,
'urlResourceOwnerDetails' => MicrosoftGraphConstants::RESOURCE_ID,
'scope' => MicrosoftGraphConstants::SCOPES
]);
if ($_SERVER['REQUEST_METHOD'] === 'GET' && !isset($_GET['code']))
{
// Try getting access token from Database
$workingAccount = $GLOBALS['AppUI']->getState('working_account');
if (isset($workingAccount))
{
// DB access
$DB = new DatabaseConnection();
$dbAccess = $DB->getConnection();
$contactData = DBUserUtils::getContactDataFromEmail($GLOBALS['AppUI']->getState('working_account'), $dbAccess);
// If at least one user contact found
if (!is_null($contactData))
{
// If has refresh token => fill session variables using refresh token
if (!is_null($contactData['contact_refreshToken']))
{
log_msg('debug.log', 'Has refresh token');
$GLOBALS['AppUI']->setState('preferred_username', $contactData['contact_email']);
$GLOBALS['AppUI']->setState('given_name', $contactData['contact_first_name']." ".$contactData['contact_last_name']);
// Get new tokens
$newAccessToken = $this->provider->getAccessToken('refresh_token', [
'refresh_token' => $contactData['contact_refreshToken']
]);
// Update tokens and DB
$GLOBALS['AppUI']->setState('refresh_token', $newAccessToken->getRefreshToken());
$GLOBALS['AppUI']->setState('access_token', $newAccessToken->getToken());
DBOAuthUtils::updateTokenForUser($contactData['contact_id'], $GLOBALS['AppUI']->getState('refresh_token'), $dbAccess);
$this->redirectTo($redirectURL);
}
else
{
$this->getAccessToken();
}
}
else
{
$this->getAccessToken();
}
}
else
{
$this->getAccessToken();
}
function getAccessToken(){
$accessToken = $this->provider->getAccessToken('password', [
'username' => '*************',
'password' => '********',
'scope' => MicrosoftGraphConstants::SCOPES
]);
}
During the first try it doesn't pass the if (isset($workingAccount)) condition (as expected) and go straight to the last else.
Code is a bit ugly for now but I don't think it has an impact on my problem.
Any help would be appreciated !
Thanks
Edit : added code
That helped me, the problem was that I need to use Azure Active Directory and not Azure AD 2.0.
Problem solved !
I am developing a ecommerce site for a friend and in the process of updating Paypal with the shipping amount prior to executing the payment, and I get the following error. This error is occuring when I call on Patch, PatchRequest, and then try executing the payment. Here is all of the code:
if (Input::get('action', 'get') === "getDetails") { //Check to see if the action parameter is set to getDetails
$payment = \PayPal\Api\Payment::get(Input::get('paymentId', 'get'), $paypalAPI);
$payerInfo = $payment->getPayer()->payer_info;
if (!empty($payment)){
$quantity = 0;
foreach ($payment->transactions[0]->item_list->items as $item) {
$quantity += $item->quantity;
}
if ($quantity <= 20) {
$parcelType = "MediumFlatRateBox";
} else if ($quantity > 20) {
$parcelType = "LargeFlatRateBox";
}
$shipment = \EasyPost\Shipment::create([
'from_address' => \EasyPost\Address::retrieve(Config::get('easypost/addressObjectID')),
'to_address' => [
'name' => $payerInfo->shipping_address->recipient_name,
'street1'=> $payerInfo->shipping_address->line1,
'street2' => (isset($payerInfo->shipping_address->line2)) ? $payerInfo->shipping_address->line2 : null,
'city' =>$payerInfo->shipping_address->city,
'state' => $payerInfo->shipping_address->state,
'country' => $payerInfo->shipping_address->country_code,
'zip' => $payerInfo->shipping_address->postal_code,
'email' => $payerInfo->email
],
'parcel' => [
'predefined_package' => $parcelType,
'weight' => 520
]
]);
//Grab the lowest shipping rate
$shippingRate = $shipment->lowest_rate()->rate;
//Make a call to PayPal updating our transaction with the tax and shipping rate
$amount = $payment->transactions[0]->amount;
$transactionUpdate = new \PayPal\Api\Patch();
$transactionUpdate ->setOp('replace')
->setPath('transactions/0/amount')
->setValue(json_decode('{
"total": "'.$amount->total.'",
"currency":"USD",
"detail": {
"subtotal": "'.$amount->details->subtotal.'",
"shipping":"'.$shippingRate.'"
}
}'));
//Instantiate a new instance of PayPal's Patch Request Class and Update the Transaction with the tax and shipping rate
$updateRequest = new \PayPal\Api\PatchRequest();
$updateRequest->setPatches(
[$transactionUpdate]
);
//Attempt Update
$result = $payment->update($updateRequest, $paypalAPI);
if ($result) {
$transID = generateTransactionID();
$fields = [
'dateCreated' => strtotime($payment->create_time),
'transID' => $transID,
'paymentID' => $payment->id,
'shipmentID' => $shipment->id
];
$db->insert('transactionLog', $fields);
Redirect::to('shoppingCartFinalize.php?transID='.$transID);
exit();
} else {
Alert::set([
'header' => "Uh Oh....Something Went Wrong",
'message' => "Unable to update transaction. Transaction Cancelled. Please try again.",
'type' => 'danger',
'close' => 1
]);
Redirect::to('shoppingCartView.php');
exit();
}
}
THe following is the error i get during the call:
Fatal error: Uncaught exception
'PayPal\Exception\PayPalConnectionException' with message 'Got Http
response code 400 when accessing
https://api.sandbox.paypal.com/v1/payments/payment/PAY-77N347011V970714EKU2D24Q.'
in
/var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:177
Stack trace: #0
/var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(74):
PayPal\Core\PayPalHttpConnection->execute('[{"op":"replace...') #1
/var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(103):
PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...',
'PATCH', '[{"op":"replace...', NULL) #2
/var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Payment.php(474):
PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...',
'PATCH', '[{"op":"replace...', NULL, Object(PayPal\Rest\ApiContext),
NULL) #3 /var/www/html/myla-dev/apiProcessing.php(146):
PayPal\Api\Payment->update(Object(PayPal\Api\ in
/var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php
on line 177
UPDATE: Thank you for the assistance Thaer. It helped. Now I am getting a separate error. When I attempt to update the payment it is now saying the following:
Array (
[name] => PAYMENT_STATE_INVALID
[message] => This request is invalid due to the current state of the payment
[information_link] => https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID
[debug_id] => 1b1b9b71e91d8 )
If you know how to fix this please. I don't know how to change the state so that the payment can be updated.
If you find an error please let me know. I am so stuck it is not funny.
Dave Douglas
Please refer to this Answer
I think you must try - catch your code to determine error
,regards.
First, can you confirm if the payment is already executed or not ?
Note that it can only be updated before the execute is done. Once, the payment is executed it is not possible to udpate that. Docs: https://developer.paypal.com/webapps/developer/docs/api/#update-a-payment-resource
You can follow the code shown here to update the Payment here : http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/UpdatePayment.html
And I think your payment has already been executed, and so the state would be complete and not created, which is causing that 400 Exception of invalid state.
Let me know if that makes sense.
To make a change in the payment, you might be able to create a refund, to return the remaining amount.
Alternatively, you could also use authorize or order, to hold the funds first, and then actually charge them later. Kind of how you see it in restaurants, etc, where they hold the fund of your total, but eventually add the tip later, and complete the transaction later.
For more information read here: https://developer.paypal.com/webapps/developer/docs/integration/direct/create-process-order/