I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.
Related
Using SquareConnect's PHP Sdk, I am trying to create a very basic variant product using their API.
`
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
//print out the objectid. Works perfectly!
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
//now create the variant and it will fail
$var_api = new \SquareConnect\Api\V1ItemsApi();
$variation = new \SquareConnect\Model\V1Variation(); // \SquareConnect\Model\V1Variation | An object containing the fields to POST for the request. See the corresponding object definition for field details.
$variation->setName("JERSUB");
$variation->setSku("JERSUPPERSKU");
try {
$meresult = $var_api->createVariation($location_id, $object_id, $variation);
print_r($meresult);
} catch (Exception $e) {
echo 'Exception when calling V1ItemsApi->createVariation: ', $e->getMessage(), PHP_EOL;
}
`
No matter what I do I always get a 400 Bad request.
Exception when calling V1ItemsApi->createVariation: [HTTP/1.1 400 Bad Request] {"type":"bad_request","message":"BadRequest"}
I have tried just passing in a blank variation object like the documentation, but it still does not work. How do I get around or diagnose the error?
I was using an older V1 version of the API. I found an OO way of doing it that was actually smarter. Below is a snippet that should hopefully help someone.
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
$clone=$results[0];
$clone->setId("#TEMP123"); //change it to a temp id
$clone->setType("ITEM_VARIATION");
$id=$clone->getId();
$var_data=$clone->getItemVariationData();
//now clear/update the cloned object
$var_data->setName(UPC_FIELD_NAME);
$var_data->setSku("SUPPERSKU_TEST2"); //update sku
$var_data->setPricingType("VARIABLE_PRICING");
$var_data->setTrackInventory(null);
$var_data->setLocationOverrides(null); //got to remove location ovverides or it will track.
$var_data->setPriceMoney(null);
$clone->setItemVariationData($var_data);
//upsert it
$upsert=new \SquareConnect\Model\UpsertCatalogObjectRequest();
//set unique key
$upsert->setIdempotencyKey(md5(time()));
$upsert->setObject($clone);
//fire the update
$update_result=$api_instance->upsertCatalogObject($upsert);
I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??
I have implement the gcm to send notification to my application and its really working perfect.
I am getting notification on device but issue is that I am getting logs detail may be in notification message instead of only human readable message that I am pushing.
Here is my code that I am using to send notification:
$gcmApiKey = GOOGLE_API_KEY;
$pushApi = new PushAPI();
$sender = new \PHP_GCM\Sender($gcmApiKey);
$message = new \PHP_GCM\Message("1", $messsageVal);
try {
$multicastResult = $sender->sendMulti($message, $deviceRegistrationId, 2);
$results = $multicastResult->getResults();
for ($i = 0; $i < count($deviceRegistrationId); $i++) {
$regId = $deviceRegistrationId[$i];
$result = $results[$i];
$messageId = $result->getMessageId();
if ($messageId != null) {
$canonicalRegId = $result->getCanonicalRegistrationId();
if ($canonicalRegId != null) {
// same device has more than on registration id: update it
}
} else {
$error = $result->getErrorCodeName();
if ($error == \PHP_GCM\Constants::$ERROR_NOT_REGISTERED) {
$pushApi->clearDeviceByDeviceId($regId);
}
}
}
} catch (\InvalidArgumentException $e) {
// $deviceRegistrationId was null
} catch (PHP_GCM\InvalidRequestException $e) {
// server returned HTTP code other than 200 or 503
} catch (\Exception $e) {
// message could not be sent
}
Here is the link of whole API that I am using. PHP_GCM
I try to google it but I didn't get anything to rectify this.
Any help will be appreciated.
You have to parse your response same as you parse a webservice response and show only the msg.
Try getting the message from the received intent using:
String msg=intent.getExtras().getString("msg");
Then show the message as :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.app_icon)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(context.getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
am using the php api sdk found here: https://github.com/paypal/PayPal-PHP-SDK but am having trouble issuing a refund.
This is the code I am using:
// CAPTURE THE ORIGINAL AUTHORIZATION
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($amount_authorized);
$capture = new Capture();
$capture->setId($authorization_id);
$capture->setAmount($amount);
$authorization = Authorization::get($transaction_id, $apiContext);
$capt = $authorization->capture($capture, $apiContext);
if ($capt->state == 'completed')
{
$capture_id = $capt->id;
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('Error capturing funds: '.$response->message);
}
catch (Exception $e)
{
die('Error capturing funds: '.$e->getMessage());
}
// REFUND THE CAPTURE
try
{
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($refund_amount);
$refund = new Refund();
$refund->setId($capture_id);
$refund->setAmount($amount);
$capture = Capture::get($capture_id, $apiContext);
$captureRefund = $capture->refund($refund, $apiContext);
if ($captureRefund->state == 'completed')
{
die('REFUNDED');
}
}
catch (PayPal\Exception\PayPalConnectionException $e)
{
$response = json_decode($e->getData());
die('There was an error refunding the funds: '.$response->message);
}
catch (Exception $e)
{
die('There was an error refunding the funds: '.$e->getMessage());
}
I get this error everytime: The requested resource ID was not found
I believe I am following the sample code on the developer site but I'll pulling my hair out. It's probably something pretty easy I hope.
Any ideas?
Thanks
Try block for email sending is working, but it directly redirect to another page without sending mail. smtp setting are okay. This code was working perfectly but now nothing is happening.
try{ ..........................................//mail senting
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
//get customer details
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->getId();
$customer->getEmail();
//get general store details
$from_name = Mage::getStoreConfig('trans_email/ident_general/name');
$from_email = Mage::getStoreConfig('trans_email/ident_general/email');
$templateId=7;
$emailTemplate = Mage::getModel('core/email_template')->load($templateId);
//$emailTemplateVariables = array();
//$emailTemplateVariables[‘name′] = "$mh"";
$processedTemplate = $emailTemplate->getProcessedTemplate();
$mail=Mage::getModel('core/email');
$mail->setToName($customer->getId());
$mail->setToEmail($customer->getEmail());
$mail->setBody($processedTemplate);
$mail->setSubject("Upload Conformation ");
// print_r($mail);
//die;
$mail->setFromEmail($from_email);
$mail->setFromName($from_name);
$mail->setType('html');
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
}
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl().'bank-info/');
} catch (Exception $ex) {
Mage::getSingleton('core/session')->addError($ex->getMessage());
Mage::log($ex->getMessage());
Mage::getSingleton("supplierfrontendproductuploader/session")->setProductData($postData);
if($editMode) {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/edit/id/'.$postData['product_id']);
} else {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/create/');
}