Get Stripe Payment by metadata Value

This PHP function lets you get a Stripe payment by a custom metadata value. It searches the Payment Intents API for a “succeeded” Payment Intent that has a metadata key/value pair that you want to search by.

This function is for when you’re not using the Stripe PHP library, and just want to use your own PHP functions.

Parameters

  1. $key – The metadata key to search for. (This refers to the custom metadata that you set when you initially created the Payment Intent.)
  2. $value – The metadata value to search for. (This refers to the custom metadata that you set when you initially created the Payment Intent.)
  3. $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 returns the Payment Intent object if a payment with a matching metadata value is found, otherwise it returns null.

Required

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

PHP

/**
 * Get a Stripe payment by metadata
 * @param string $key The metadata key to search for
 * @param string $value The metadata value to search for
 * @param int $months Number of months to search, default is 1
 * @return object|null PaymentIntent object if found, otherwise null
 */
function get_stripe_by_metadata($key, $value, int $months = 1) {
	// search Stripe payments by metadata
	$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 matching payment
			foreach ($data as $obj) {

				if(empty($obj->metadata->{$key})) continue;

				if($value == $obj->metadata->{$key} && 'succeeded' == $obj->status) {
					$payment = $obj;
					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));
		}
	}
	return $payment ?? null;
}

See more:

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]