Stripe webhook error fails on wordpress theme - php

I am trying to solve a problem, I am currently doing tests with stripe where the user pays for a small percentage of a reservation, this payment is reflected in my stripe account (test) and everything is in order. The problem is that there is an event that fails and it is retried to send from webhook, when this event is retried to send it causes me on the web page to be marked as fully paid, the ideal would be that this event always comes out as successful or that it does not return to try, hope there is a solution.
This is the code from the theme when the function take place of payment_intent.succeeded:
$endpoint_secret = esc_html ( wprentals_get_option('wp_estate_stripe_webhook','') );
$payload = #file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400); // PHP 5.4 or greater
exit('');
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400); // PHP 5.4 or greater
exit();
}
if ($event->type == "payment_intent.succeeded") {
$intent = $event->data->object;
$pay_type = intval($event->data->object->charges->data[0]->metadata->pay_type);
$userId = intval($event->data->object->charges->data[0]->metadata->user_id);
$depozit = intval($intent->amount);
if($pay_type==1){
$invoice_id = intval($event->data->object->charges->data[0]->metadata->invoice_id);
$booking_id = intval($event->data->object->charges->data[0]->metadata->booking_id );
$is_stripe=1;
wpestate_booking_mark_confirmed($booking_id,$invoice_id,$userId,$depozit,$user_email,$is_stripe);
$redirect=wpestate_get_template_link('user_dashboard_my_reservations.php');
http_response_code(200);
wp_redirect($redirect);exit();
}else if($pay_type==2){
$listing_id = intval($event->data->object->charges->data[0]->metadata->listing_id);
$is_featured = intval($event->data->object->charges->data[0]->metadata->featured_pay);
$is_upgrade = intval($event->data->object->charges->data[0]->metadata->is_upgrade);
$time = time();
$date = date('Y-m-d H:i:s',$time);
if($is_upgrade==1){
update_post_meta($listing_id, 'prop_featured', 1);
$invoice_id = wpestate_insert_invoice('Upgrade to Featured','One Time',$listing_id,$date,$current_user->ID,0,1,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
wpestate_email_to_admin(1);
}else{
update_post_meta($listing_id, 'pay_status', 'paid');
$admin_submission_status = esc_html ( wprentals_get_option('wp_estate_admin_submission','') );
$paid_submission_status = esc_html ( wprentals_get_option('wp_estate_paid_submission','') );
if($admin_submission_status=='no' && $paid_submission_status=='per listing' ){
$post = array(
'ID' => $listing_id,
'post_status' => 'publish'
);
$post_id = wp_update_post($post );
}
// end make post publish
if($is_featured==1){
update_post_meta($listing_id, 'prop_featured', 1);
$invoice_id = wpestate_insert_invoice('Publish Listing with Featured','One Time',$listing_id,$date,$current_user->ID,1,0,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
}else{
$invoice_id = wpestate_insert_invoice('Listing','One Time',$listing_id,$date,$current_user->ID,0,0,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
}
wpestate_email_to_admin(0);
}
$redirect = wpestate_get_template_link('user_dashboard.php');
http_response_code(200);
wp_redirect($redirect);exit();
}

Related

square payment form php check customer exists in directory and make payment

Am new to Square Payment Form using PHP and trying to do following steps
Check If customer Exists in Directory
If Customer Does not exist - create new customer and collect CUSTOMER_ID
MAKE PAYMENT & get Payment ID
Couple of time this script worked by started getting Maximum execution time of 30 seconds exceeded AND created multiple customer entries in directory and payment failed
PS : am using GOTO to loop and ENV file for credentials
Any help will be appreciated in advance
print_r($_POST);
$booknow = $_POST;
require 'vendor/autoload.php';
use Dotenv\Dotenv;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Environment;
use SquareConnect\ApiClient;
use Square\Models\CreateCustomerRequest;
$idem = UUID::v4();
$sname = explode(' ', $_POST["cname"]);
$sname0 = $sname[0];
$sname1 = $sname[1];
$cphone = $_POST["cphone"];
//$cphone = '9848848450';
$cemailid = $_POST["cemailid"];
$ifare = ($_POST["ifare"] * 100);
$xnote = $_POST["note"];
//echo '<br><br>fare : ' . $ifare . '<br><br>';
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
$upper_case_environment = strtoupper(getenv('ENVIRONMENT'));
$access_token = getenv($upper_case_environment.'_ACCESS_TOKEN');
//print_r($access_token);
//echo '<br><br><br>';
$client = new SquareClient([
'accessToken' => $access_token,
'environment' => getenv('ENVIRONMENT')
]);
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('Received a non-POST request');
echo 'Request not allowed';
http_response_code(405);
return;
}
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo 'Invalid card data';
http_response_code(422);
return;
}
searchCustomers: ///search customers
$phone_number = new \Square\Models\CustomerTextFilter();
$phone_number->setFuzzy($cphone);
$filter = new \Square\Models\CustomerFilter();
$filter->setPhoneNumber($phone_number);
$query = new \Square\Models\CustomerQuery();
$query->setFilter($filter);
$body = new \Square\Models\SearchCustomersRequest();
$body->setQuery($query);
$api_response = $client->getCustomersApi()->searchCustomers($body);
if ($api_response->isSuccess()) {
$rmn = $api_response->getBody();
$stx = json_decode($rmn,true);
echo '<br><br>';
echo '# of arrays : ' . count($stx);
if(count($stx) != 0){
//echo '<br><br>';
$cust_id = $stx["customers"][0]["id"];
//echo "Customer ID : " . $cust_id;
goto makePayment;
//goto end;
} else {
//echo 'user do not exists';
/// new customer - start
$body1 = new \Square\Models\CreateCustomerRequest();
$body1->setIdempotencyKey($idem);
$body1->setGivenName($sname0);
$body1->setFamilyName($sname1);
$body1->setEmailAddress($cemailid);
$body1->setPhoneNumber($cphone);
$api_response = $client->getCustomersApi()->createCustomer($body1);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
goto searchCustomers;
} else {
$errors = $api_response->getErrors();
}
/// new customer - end
}
} else {
echo '<br><br>sorry not found!<bR><br>';
}
goto end;
makePayment:
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($ifare);
$amount_money->setCurrency('USD');
$body = new \Square\Models\CreatePaymentRequest(
'cnon:card-nonce-ok',
$idem,
$amount_money
);
$body->setCustomerId($cust_id);
$body->setNote($xnote);
$api_response = $client->getPaymentsApi()->createPayment($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$srt = json_encode($result);
echo '<br><br>';
echo "PAYEMNT SUCCESSUFLL <BR><br><br>";
//print_r($srt);
goto end;
} else {
$errors = $api_response->getErrors();
echo 'payment FAILEDDDDDDDDDD';
}
goto end;
end:

502 Bad Gateway Foreach loop

hope for some help, basically i have a script that gets the latest posts from facebook users, and basically i check if there is any new post that is not available on my database, in case that this post is new, than i save it in my database along with the post id (this way i check if exist on DB).
But i have a issue with it, in my case i need to check a number of users, and this users keeps growing, in my case i have 400 users. If i go more thatn 100 users i get the 500 error of course, it is many requests.
So does someone have a ideia of how could i handle it?
My code: FarcebookParcer.php
public function facebook($id, $num) {
//Set your App ID and App Secret.
$appID = 'xxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
//Create an access token using the APP ID and APP Secret.
$accessToken = $appID . '|' . $appSecret;
//Tie it all together to construct the URL
$url = "https://graph.facebook.com/$id/posts?fields=attachments,created_time&limit=$num&access_token=$accessToken";
if (Helper::get_http_response_code($url) != 200) {
return false;
}
//Make the API call
$opts = array(
'http' => array(
'method' => 'GET',
'timeout' => 120
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//Decode the JSON result.
$dt = json_decode($result, true);
$posts = $dt;
return $posts;
}
CronController.php
public function socialfacebook() {
$facebook = SocialSnap::all();
$socialparser = new FacebookParser();
$appID = 'xxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = $appID . '|' . $appSecret;
set_time_limit(0);
foreach ($facebook as $key => $value) {
if ($value->facebook != NULL) {
$facebook_user = $socialparser->facebook_user(substr($value->facebook, 1));
$facebook_posts = $socialparser->facebook(substr($value->facebook, 1), 1);
//Check if valid url
if ($facebook_posts == false || $facebook_user == false) {
continue;
}
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['target']['url']) && isset($facebook_posts['data'][0]['attachments']['data'][0]['description'])) {
SnapChat::where('facebook', $value->facebook)->update(['facebook_photo' => 'https://graph.facebook.com/'. substr($value->facebook, 1) . '/picture/?type=normal']);
$post_current = SocialSnap::where('id_social', $facebook_posts['data'][0]['id'])->first();
//return $post_current;
if ($post_current == NULL) {
$post = new SocialSnap;
$post->id_social = $facebook_posts['data'][0]['id'];
$post->id_snapchats = $value->id;
$post->date_social = isset($facebook_posts['data'][0]['created_time']) ? date("Y-m-d H:m:s", strtotime($facebook_posts['data'][0]['created_time'])) : "";
$post->type = 'facebook';
$post->url = $facebook_posts['data'][0]['attachments']['data'][0]['target']['url'];
$post->message = $facebook_posts['data'][0]['attachments']['data'][0]['description'];
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'])) {
$post->image = $facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'];
}
$post->save();
}
}
}
}
echo 'DONE';
}

wp_set_auth_cookie() not working for some users only

I have a login form and using REST api service for login to the Wordpress. I can login to the wordpress using the form. But for some users wp_set_auth_cookie() function not working and I am getting 502 bad gateway. Can any one help me for sort out this?
This is my login endpoint function
function user_authentication() {
global $wp_rest_auth_cookie;
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = false;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID);
wp_set_auth_cookie ( $user->ID );
$wp_rest_auth_cookie = wp_create_nonce('wp-rest') ;
$token = encrypt_decrypt('encrypt',$user->ID);
$name = get_name($user->ID);
$response = array(
'status'=> 'success',
'token' => $token,
'username' => $name,
'uname' => $user->ID
);
return json_encode( $response);
}else{
$response = array(
'status' => 'fail',
'message'=> "The username and password you entered don't match."
);
return json_encode($response);
}
die();
}
Add below code into your code and check wp_set_auth_cookie working or not.
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = true;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_set_auth_cookie( $user->ID, true );
} else {
echo $user->get_error_message();
}
I have solved this myself. There was some undefined variable errors along with the api response. Those errors was conflicting with the wp_set_auth_cookie() function. When I fixed those errors from my code, the 502 bad gate way issue get solved.

why sometime can get error 404 not found (soapclient- response has contents of the response), how to solve

i have a NUSOAP webservice
when i run from client it visbile the error
wsdl error: Getting http://carvilshoe.cz.cc/index.wsdl.php?wsdl - HTTP ERROR: Unsupported HTTP response status 404 Not Found (soapclient->response has contents of the response)
below is my code at client
i have to client (mitra)
mitra = http://pakalolosepatu.cu.cc/
mitra1 = http://carvilshoe.cz.cc/
--
//wsdl configuration
$wsdl = mitra . 'index.wsdl.php?wsdl';
$ws_client_pakalolo = new nusoap_client ( $wsdl, true );
$wsdl = mitra1 . 'index.wsdl.php?wsdl';
$ws_client_sepatubermerek = new nusoap_client ( $wsdl, true );
//debug if needed
//$ws_client->debugLevel = 1;
//header configuration
$user = "+++";
$pass = "+++";
//encrypt header value
$user = base64_encode ( $user );
$pass = base64_encode ( $pass );
$header = '<AuthSoapHeader>
<UserName>' . $user . '</UserName>
<Password>' . $pass . '</Password>
</AuthSoapHeader>';
//set header
$ws_client_pakalolo->setHeaders ( $header );
$ws_client_sepatubermerek->setHeaders ( $header );
// Function to print Fault
function detect_fault() {
global $ws_client_pakalolo;
//detect fault and error
if ($ws_client_pakalolo->fault) {
exit ( $ws_client_pakalolo->faultstring );
} else {
$err = $ws_client_pakalolo->getError ();
if ($err) {
exit ( $err );
}
}
}
function detect_fault_mitra2() {
global $ws_client_sepatubermerek;
//detect fault and error
if ($ws_client_sepatubermerek->fault) {
exit ( $ws_client_sepatubermerek->faultstring );
} else {
$err = $ws_client_sepatubermerek->getError ();
if ($err) {
exit ( $err );
}
}
}
function call_list_barang($limit, $offset, $order_by, $where) {
global $ws_client_pakalolo,$ws_client_sepatubermerek;
//parameters configuration
$params = array ('limit' => $limit, 'offset' => $offset, 'order_by' => $order_by, 'where' => $where);
//call method service
$ws_data = $ws_client_pakalolo->call ( 'data_barang', $params);
detect_fault ();
//decode data
$ws_data = unserialize ( base64_decode ( $ws_data ) );
//call method service
$ws_data1 = $ws_client_sepatubermerek->call ( 'data_barang', $params);
detect_fault_mitra2 ();
//decode data
$ws_data1 = unserialize ( base64_decode ( $ws_data1 ) );
$data_paka = $ws_data['data'];
$data_se = $ws_data1['data'];
$data = array_merge($data_paka,$data_se);
return $data;
}
function call_list_stock($mitra,$no_barang) {
global $ws_client_sepatubermerek, $ws_client_pakalolo;
//parameters configuration
$params = array ('no_barang' => $no_barang );
if($mitra == "Pakalolo"){
//call method service
$ws_data = $ws_client_pakalolo->call ( 'list_stock', $params);
detect_fault ();
//decode data
}else{
//call method service
$ws_data = $ws_client_sepatubermerek->call ( 'list_stock', $params);
detect_fault_mitra2 ();
//decode data
}
$ws_data = unserialize ( base64_decode ( $ws_data ) );
return $ws_data;
}
?>
why can happen this error and how to solve,
can someone help??
thanks
Try to set forced endpoint
$client = new nusoap_client('http://LOCATION_TO_WSDL','wsdl');
$client -> setEndpoint('http://LOCATION_OF_ENDPOINT');
The endpoint is a connection point where HTML files or active server pages are exposed.

Error #520009 - Account is restricted

I get a 520009 error (Account xx#xx.com is restricted) when trying to make a parallel payment. My code worked fine using the sandbox but I switched to the live endpoint and it began failing. The account in question is a valid paypal account and I am using "feespayer=SENDER". Am I missing something? Shouldn't the pay call go through even if the payee is a basic account? Why would this occur?
Here is my code for reference
function deposit($config) {
try {
if (isset($config['return_url']))
$this->return_url = $config['return_url'];
else
return 'Return URL should be set';
if (isset($config['return_url']))
$this->cancel_url = $config['cancel_url'];
else
return 'Cancel URL should be set';
if (isset($config['email']))
$this->sender_email = $config['email'];
else
return 'Email should be defined';
if (isset($config['amount']))
$this->amount = $config['amount'];
else
return 'Amount should be defined';
$returnURL = $this->return_url;
$cancelURL = $this->cancel_url;
$currencyCode = 'USD';
$memo = 'Deposit to ' . $this->ci->config->item('site_name');
$feesPayer = 'SENDER';
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL;
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->ci->config->item('application_id');
$payRequest->clientDetails->deviceId = $this->ci->config->item('device_id');
$payRequest->clientDetails->ipAddress = $this->ci->input->ip_address();
$payRequest->currencyCode = $currencyCode;
//$payRequest->senderEmail = $this->sender_email;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
$receivers = array();
$receiver = new receiver();
$receiver->email = $this->ci->config->item('moneyfan_account');
$receiver->amount = $this->amount;
$receiver->primary = 'false';
$receivers[] = $receiver;
$payRequest->receiverList = $receivers;
$payRequest->feesPayer = $feesPayer;
$payRequest->memo = $memo;
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if (strtoupper($ap->isSuccess) == 'FAILURE') {
$this->ci->session->set_userdata('FAULTMSG', $ap->getLastError());
return json_encode(array('status' => 'false', 'msg' => $ap->getLastError()->error->errorId .' : '. $ap->getLastError()->error->message));
//redirect(site_url('home/api_error'));
} else {
$this->ci->session->set_userdata('payKey', $response->payKey);
if ($response->paymentExecStatus == "COMPLETED") {
redirect($returnURL);
} else {
$token = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $token;
return json_encode(array('status' => 'true', 'msg' => $payPalURL));
//header("Location: " . $payPalURL);
}
}
} catch (Exception $ex) {
$fault = new FaultMessage();
$errorData = new ErrorData();
$errorData->errorId = $ex->getFile();
$errorData->message = $ex->getMessage();
$fault->error = $errorData;
$this->ci->session->set_userdata('FAULTMSG', $fault);
redirect(site_url('home/api_error'));
}
}
No! You cannot do that with a basic account.
For API to work you need to have a VERIFIED Business Account.
In their API it says:
NOTE:
The application owner must have a PayPal Business account.
There are two sources of reference for the PayPal API:
cms.paypal.com pages like the one referenced by Mihai Iorga, and
www.x.com pages like this one:
https://www.x.com/developers/paypal/documentation-tools/going-live-with-your-application
On x.com, it says you must have a verified business account, even though it is unclear from cms.paypal.com that this is the case.

Categories