Get Stripe payment by Receipt Number in PHP

This PHP function searches Stripe payments by the Stripe Receipt number, and returns the Payment Intent object. This is for when you’re not using the Stripe PHP library, and just using your own PHP functions for Stripe.

Parameters

  1. $receipt_number – The Stripe receipt number to search for. (This refers to the receipt_number generated by Stripe.)
  2. $months – The number of months to search. The default is 1 (it will search the last 1 month of payments). This must be an integer. Example: if you pass 3 it will search the past 3 months, relative to the current moment.

Return Values

This function will return the Payment Intent object, if a payment with a matching Receipt Number is found. If not found, it will return a string with a message like, “Receipt #9999-9999 was not found for the last 1 month.”

Required

To use the function below, you also need the query_stripe_paymentintents function to query the Stripe Payment Intents API.

PHP

/**
 * Get Stripe payment by Receipt #
 * @param string $receipt_number The Stripe receipt number to search for.
 * @param int $months How many months to search, default is the last 1 month.
 * @return object|string $payment Paymentintent object with matching Receipt #, or string if not found.
 */
function get_stripe_payment_by_receipt($receipt_number, int $months = 1) {
	$ago = strtotime("-$months month");
	$has_more = true;
	$pg = "";
	while($has_more){
		
		$response = query_stripe_paymentintents("?created[gte]={$ago}{$pg}&limit=100");

		if (!empty($response->data)) {
			$data = $response->data;
			// look for receipt
			foreach ($data as $key => $r) {
				if(empty($r->charges->data[0]->receipt_number)) continue;
				if($receipt_number === $r->charges->data[0]->receipt_number && 'succeeded' == $r->status) {
					$payment = $r;
					break 2;
				}
			}
			if($has_more = $response->has_more ?? false) {
				$curs = end($data)->id;//update cursor
				$pg = "&starting_after=$curs";
			}
		} elseif($error = $response->error ?? 0) {
			$err_msg = $response->error->message ?? '';
			error_log(sprintf('Stripe API Error: %s', $err_msg));
		} elseif(is_string($response)) {
			error_log(sprintf('curl error: %s', $response));
		}
	}

	if(empty($payment)) {
		return sprintf('Receipt # %s was not found for the last %d %s.', $receipt_number, $months, ((1 === $months) ? 'month' : 'months'));
	}

	return $payment;
}

See more:

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]