how to get transaction id in stripe payment gateway - stripe-payments

I am using stripe payment gateway in php. Everything is working. But not showing transaction id after successful payment. How to get transaction id?
if(isset($_POST['stripeToken']))
{
$amount_cents = str_replace(".","","1.00"); // Chargeble amount
$invoiceid = "14526321"; // Invoice ID
$description = "Invoice #" . $invoiceid . " - " . $invoiceid;
try {
$charge = Stripe_Charge::create(array(
"amount" => $amount_cents,
"currency" => "usd",
"source" => $_POST['stripeToken'],
"description" => $description)
);
// Payment has succeeded, no exceptions were thrown or otherwise caught
$result = "success";
} catch(Stripe_CardError $e) {
$error = $e->getMessage();
$result = "declined";
} catch (Stripe_InvalidRequestError $e) {
$result = "declined";
} catch (Stripe_AuthenticationError $e) {
$result = "declined";
} catch (Stripe_ApiConnectionError $e) {
$result = "declined";
} catch (Stripe_Error $e) {
$result = "declined";
} catch (Exception $e) {
}
// Charge the Customer instead of the card
if($result=="success") {
$response = "<div class='col-sm-offset-3 col-sm-9 text-success'>Your Payment has been processed successfully.</div>";
} else{
$response = "<div class='text-danger'>Stripe Payment Status : \".$result.</div>";
}
}
?>
Above code is for after form submit.

You are getting your API response in the variable $charge. Comment out $result = s"success"; and write echo($charge);. You will see the response. In the response, the 'balance_transaction' value that starts with 'tx_' is the transaction id. Do save it to your database for further use.
Check the stripe API docs: https://stripe.com/docs/api/charges/object

Related

Stripe symfony subscription user

I'm new to stripe, I managed to make the payment via the doc but I can't link my user to the subscription, for example I would like that when the payment is made, in my user entity I would like whether the user is put in premium or when the subscription is cancelled, whether the user is not in premium.
In my user entity I put a "premium" boolean field
Can you help me please?
#[Route('/abonnement/panier/2/checkout', name: 'aboCheck')]
public function stripe2(Request $request): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('public');
}
\Stripe\Stripe::setApiKey('sk_test....');
$priceId = 'price.....';
if (!$priceId) {
throw $this->createNotFoundException('Bad plan id!');
}
$username = $this->getUser()->getUsername();
$email = $this->getUser()->getEmail();
$session = \Stripe\Checkout\Session::create([
'success_url' => 'http://127.0.0.1:8000/abonnement/panier/2/order/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://127.0.0.1:8000/abonnement/panier/2',
'mode' => 'subscription',
'line_items' => [[
'price' => $priceId,
// For metered billing, do not pass quantity
'quantity' => 1,
]],
'client_reference_id' => $username,
'customer_email' => $email,
'metadata' => [
'username' => $username
]
]);
return $this->redirect($session->url);
}
#[Route('/webhook', name: 'webhook')]
public function handle(ManagerRegistry $doctrine)
{
\Stripe\Stripe::setApiKey('sk....');
$endpoint_secret = 'whsec.....';
$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);
exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
$user = $this->getUser();
// Handle the event
switch ($event->type) {
case 'customer.subscription.trial_will_end':
$subscription = $event->data->object;
print_r($subscription); // contains a \Stripe\Subscription
// Then define and call a method to handle the trial ending.
// handleTrialWillEnd($subscription);
break;
case 'customer.subscription.created':
$subscription = $event->data->object;
print_r($subscription); // contains a \Stripe\Subscription
// Then define and call a method to handle the subscription being created.
// handleSubscriptionCreated($subscription);
break;
case 'customer.subscription.deleted':
$subscription = $event->data->object;
print_r($subscription); // contains a \Stripe\Subscription
// Then define and call a method to handle the subscription being deleted.
// handleSubscriptionDeleted($subscription);
break;
case 'customer.subscription.updated':
$subscription = $event->data->object;
print_r($subscription); // contains a \Stripe\Subscription
// Then define and call a method to handle the subscription being updated.
// handleSubscriptionUpdated($subscription);
break;
default:
// Unexpected event type
error_log('Received unknown event type');
}
return new Response(Response::HTTP_OK);
}
#[Route('/abonnement/panier/2/order/success', name: 'success')]
public function successStripe(ManagerRegistry $doctrine, Request $request): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('public');
}
$priceId = 'price......';
\Stripe\Stripe::setApiKey('sk......');
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
$myuser = $this->getUser();
$session = \Stripe\Checkout\Session::retrieve($request->get('session_id'));
$customer = \Stripe\Customer::retrieve($session->customer);
if (($session->status == 'complete') & ($customer->email == $myuser->getEmail())) {
$entityManager = $doctrine->getManager();
$myuser->setProfileId($customer->id);
$myuser->setPremium(true);
$entityManager->flush();
} else {
return $this->redirectToRoute('aboStripe');
}
return $this->render('stripe/success.html.twig', [
'customer' => $customer
]);
}
#[Route('/customer-portal', name: 'customer-portal')]
public function portal(): Response
{
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
\Stripe\Stripe::setApiKey('sk_test.....');
// This is the URL to which the user will be redirected after they have
// finished managing their billing in the portal.
$myuser = $this->getUser();
$stripe_customer_id = $myuser->getProfileId();
$session = \Stripe\BillingPortal\Session::create([
'customer' => $stripe_customer_id,
'return_url' => 'http://127.0.0.1:8000/abonnement/panier/2',
]);
return $this->redirect($session->url);
}

How to add Azure AD user to Azure DevOps organisation programmatically

My organisation is connected to Azure AD.
I'd like to add AD users to my Azure DevOps organisation with C# or via Microsoft REST/Graph API.
You can do it with User Entitlements - Add Rest API:
POST https://vsaex.dev.azure.com/{organization}/_apis/userentitlements?api-version=5.1-preview.2
Example of the json body:
{
"accessLevel": {
"accountLicenseType": "express"
},
"extensions": [
{
"id": "ms.feed"
}
],
"user": {
"principalName": "newuser#fabrikam.com",
"subjectKind": "user"
},
"projectEntitlements": [
{
"group": {
"groupType": "projectContributor"
},
"projectRef": {
"id": "e5943a98-a842-4001-bd3b-06e756a7dfac"
}
}
]
}
You can use the User Entitlements - Add API as Shayki mentioned, however, I would like to share the code I used with Azure function to do the same,
public static async Task<string> AddUserEntitlment(
[ActivityTrigger] VSTSIntegrationContext vstsIntegrationContext,
ILogger log
)
{
try
{
var accountName = vstsIntegrationContext.VstsInstance;
string Url = string.Format(#"https://{0}.vsaex.visualstudio.com/_apis/userentitlements?api-version=4.1-preview"
, vstsIntegrationContext.VstsInstance);
var content = JsonConvert.SerializeObject(
new
{
accessLevel = new
{
accountLicenseType = "express"
},
user = new
{
principalName = vstsIntegrationContext.Email,
subjectKind = "user"
}
});
log.LogInformation("===========PAT: vstsIntegrationContext.VstsPAT");
var response = await VSTSHelpers.CallVSTSAPI(vstsIntegrationContext.VstsInstance, vstsIntegrationContext.VstsPAT, Url, "POST", content);
log.LogInformation("====response:" + response);
response.EnsureSuccessStatusCode();
dynamic data = await response.Content.ReadAsAsync<object>();
return data.operationResult.userId;
}
catch (Exception ex)
{
log.LogError(ex.ToString());
throw;
}
}
Powershell script
function Add-UserEntitlement {
[OutputType([int])]
Param
(
[String]$userEmail,
[String]$projAccessLevel,
[String]$projId
)
Begin {
$creds = Import-Clixml -Path creds.xml
[string]$AccName = $creds.AccountName
[string]$userName = $creds.UserName
[string]$vstsToken = $creds.Token
$VstsAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $userName, $vstsToken)))
}
Process {
$vstsUri = "https://$AccName.vsaex.visualstudio.com/_apis/userentitlements?api-version=4.1-preview"
$vstsUEBody = #{
accessLevel = #{ accountLicenseType = "express" }
user = #{ principalName = $userEmail; subjectKind = "user" }
projectEntitlements = #{
group = #{ groupType = $projAccessLevel }
projectRef = #{ id = $projId }
}
}
$RestParams = #{
ContentType = "application/json"
Method = 'Post'
URI = $vstsUserUri
Body = $vstsUEBody | ConvertTo-Json
Headers = #{Authorization=("Basic {0}" -f $VstsAuth)}
}
$vstsUpdateResult = Invoke-RestMethod #RestParams
}
End {
}
}

How to get Get Unsettled Transaction List from authoriz.net?

the above image shows list of unsettled transaction in authorize.net UI. When I request by the getUnsettledTransactionList API call I am receiving the empty result set, why?
"response": {
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00004",
"text": "No records found."
}
]
},
"totalNumInResultSet": 0
}
I am using a sandbox account in Authorize.net and NodeJs for development based on following code
https://developer.authorize.net/api/reference/index.html#transaction-reporting-get-unsettled-transaction-list
here is my code
function getUnsettledTransactionList() {
var merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName( process.env.SERVICE_CREDITCARD_API_APILOGINKEY );
merchantAuthenticationType.setTransactionKey( process.env.SERVICE_CREDITCARD_API_TRANSACTIONKEY );
var getRequest = new ApiContracts.GetUnsettledTransactionListRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setStatus(ApiContracts.TransactionGroupStatusEnum.PENDINGAPPROVAL);
//keeping promise resolve and reject funcs outside the promise scope
var promiseResolve, promiseReject;
var promise = new Promise( (_resolve, _reject)=>{
promiseResolve = _resolve;
promiseReject = _reject;
});
var ctrl = new ApiControllers.GetUnsettledTransactionListController(getRequest.getJSON());
ctrl.execute(function(){
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.GetUnsettledTransactionListResponse(apiResponse);
if(response != null){
if(response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK){
var result = {
message: response.getMessages().getMessage()[0].getText(),
messageCode: response.getMessages().getMessage()[0].getCode(),
transactions: [],
status: true,
response: response
}
if(response.getTransactions() != null)
result.transactions = response.getTransactions().getTransaction();
promiseResolve( result );
}
else{
promiseReject({
resultCode: response.getMessages().getResultCode(),
errorCode: response.getMessages().getMessage()[0].getCode(),
errorMessage: response.getMessages().getMessage()[0].getText(),
status: false,
response: response
});
}
}
else{
promiseReject( { message: 'Null Response.', status: false } );
}
});
return promise;
}
You are not supposed to set the Status for the transactions, remove this line of code.
getRequest.setStatus(ApiContracts.TransactionGroupStatusEnum.PENDINGAPPROVAL);
If you add this field in your request, you get only transaction which are pending for approval, and you might be having no transaction pending for approval thus you are getting an empty list.

Stripe with multi step form user registration

So I started playing with stripe yesterday and so far so good. I have a three step registration form, first is personal info (name), second one is password and email and third tab is for payment (monthly subscription). My logic is that if payment succeeded, then create the account on my end, if it did not, then throw the error.
So far so good- my logic works, but I have few issues. As I read this documentation then I should store the customer ID in database for later use and checking if the subscription is active or not. In my function stripeResponseHandler(status, response) {} when I console.log(response) I see the token code and card information, but I never see the customer object.
Here comes few questions:
Is my method and logic safe what I described in the first paragraph?
How can I get the customer object so I could insert the id and corresponding data into the database during the registration process?
JS
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $("#registrationForm"),
formData = new FormData(),
params = $form.serializeArray();
if (response.error) { // Problem!
// Show the errors on the form:
console.log(response.error.message);
$form.find('#btn-signup').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
console.log(token);
console.log(response);
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
cache: false,
success: function(data) {
$("#formAlert").empty();
console.log(data);
var items = '';
$.each(data.status, function(key, val) {
items += '<li>' + val + '</li>';
$(".se-pre-con").fadeOut("slow");
});
$("#registerAlerts").append(items);
},
error: function(jqXHR, textStatus, errorThrown, data) {
$(".se-pre-con").fadeOut("slow");
console.log(jqXHR, textStatus, errorThrown, data);
}
});
}
}
$("#btn-signup").on("click", function(e) {
e.preventDefault();
$(".se-pre-con").show();
var $form = $("#registrationForm");
// Request a token from Stripe:
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
});
PHP
<?php
header('Content-type: application/json');
require_once 'class.user.php';
require_once ('../plugins/stripe/init.php');
$errors = 0;
if ($stmt->rowCount() > 0)
{
$errors++;
$errors_query["status"][] = 'User exists';
}
if ($errors == 0)
{
try
{
$customer = StripeCustomer::create(array(
'email' => $_POST['formEmail'],
'source' => $token,
'plan' => '123456789',
"description" => "Subscription for user " . $uFirstname
));
if ($reg_user->register($email, $upass, $code, $utype, $uFirstname, $uLastname, $termAndAgreement))
{
$user_id = $reg_user->lasdID();
$family_files = $reg_user->runQuery("INSERT into user_files (user_id, file_type, file_size, file_name, file_new_name, file_path, file_cat, file_folder, date_created) VALUES (:user_id, 'X', '0', 'X', 'X', 'X', 'profilePicture', 'profilePicture', NOW())");
$family_files->bindparam(':user_id', $user_id, PDO::PARAM_STR);
$family_files->execute();
}
else
{
$errors++;
$errors_query["status"][] = 'error';
}
}
catch(Exception $e)
{
$errors++;
$errors_query["status"][] = 'Error with payment';
$e->getMessage();
}
}
if ($errors > 0)
{
echo json_encode($errors_query);
exit();
}
else
{
$errors_query["status"][] = 'user_welcome';
echo json_encode($errors_query);
exit();
}
?>
Using custom Stripe Payment form is completely safe. Stripe also wrote in their documentation about it and as long as you are using Stripe.js it is safe.
When you register any user using the credit card then it always returns a Stripe token. It will not return the customer id nither customer is created at this time so for this you have to call the create customer API and pass the above token in it and It will return customer object using customer Id.
you can read about stripe create customer API here

Checkout page is not working

i am using lotusbreath one step checkout. its work fine on localhost but its not working after uploading on server.
On server place order button is not redirected to order successfully page.
Both place(sever and localhost) has same file, so i doesn't understand what to do.
Can anybody help me what to do?
This is the link of checkout page on server: this
here is the validation of placed order button
public function saveOrderAction()
{
if (!$this->_validateFormKey()) {
$this->_redirect('*/*');
return;
}
if ($this->_expireAjax()) {
return;
}
$result = array();
try {
$requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds();
if ($requiredAgreements) {
$postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
$diff = array_diff($requiredAgreements, $postedAgreements);
if ($diff) {
$result['success'] = false;
$result['error'] = true;
$result['error_messages'] = $this->__('Please agree to all the terms and conditions before placing the order.');
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
return;
}
}
$data = $this->getRequest()->getPost('payment', array());
if ($data) {
$data['checks'] = Mage_Payment_Model_Method_Abstract::CHECK_USE_CHECKOUT
| Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
| Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
| Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
| Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL;
$this->getOnepage()->getQuote()->getPayment()->importData($data);
}
$this->getOnepage()->saveOrder();
$redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();
$result['success'] = true;
$result['error'] = false;
} catch (Mage_Payment_Model_Info_Exception $e) {
$message = $e->getMessage();
if (!empty($message)) {
$result['error_messages'] = $message;
}
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
} catch (Mage_Core_Exception $e) {
Mage::logException($e);
Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
$result['success'] = false;
$result['error'] = true;
$result['error_messages'] = $e->getMessage();
$gotoSection = $this->getOnepage()->getCheckout()->getGotoSection();
if ($gotoSection) {
$result['goto_section'] = $gotoSection;
$this->getOnepage()->getCheckout()->setGotoSection(null);
}
$updateSection = $this->getOnepage()->getCheckout()->getUpdateSection();
if ($updateSection) {
if (isset($this->_sectionUpdateFunctions[$updateSection])) {
$updateSectionFunction = $this->_sectionUpdateFunctions[$updateSection];
$result['update_section'] = array(
'name' => $updateSection,
'html' => $this->$updateSectionFunction()
);
}
$this->getOnepage()->getCheckout()->setUpdateSection(null);
}
} catch (Exception $e) {
Mage::logException($e);
Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
$result['success'] = false;
$result['error'] = true;
$result['error_messages'] = $this->__('There was an error processing your order. Please contact us or try again later.');
}
$this->getOnepage()->getQuote()->save();

Resources