mode ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com'; } public function accessToken( bool $forceRefresh = false ): string { if ( '' === $this->clientId || '' === $this->secret ) { throw new PayPalException( 'PayPal Client ID and Secret are not configured.' ); } $key = 'sg_pp_token_' . md5( $this->mode . '|' . $this->clientId . '|' . $this->secret ); if ( ! $forceRefresh ) { $cached = $this->cache->get( $key ); if ( is_string( $cached ) && '' !== $cached ) { return $cached; } } $res = $this->send( 'POST', '/v1/oauth2/token', array( 'Authorization' => 'Basic ' . base64_encode( $this->clientId . ':' . $this->secret ), 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', ), 'grant_type=client_credentials' ); $data = self::decode( $res['body'] ); if ( $res['status'] < 200 || $res['status'] >= 300 || empty( $data['access_token'] ) ) { if ( 401 === $res['status'] ) { throw new PayPalException( 'PayPal rejected the credentials. Check that the Client ID and Secret belong to the selected ' . ( 'live' === $this->mode ? 'Live' : 'Sandbox' ) . ' mode.', 401 ); } throw self::errorFrom( $res, 'Could not get a PayPal access token' ); } $ttl = max( 60, (int) ( $data['expires_in'] ?? 300 ) - 120 ); $this->cache->set( $key, (string) $data['access_token'], $ttl ); return (string) $data['access_token']; } /** @return string PayPal order id */ public function createOrder( Money $total, string $customId, string $requestId ): string { $res = $this->api( 'POST', '/v2/checkout/orders', array( 'intent' => 'CAPTURE', 'purchase_units' => array( array( 'custom_id' => $customId, 'description' => 'Donation', 'amount' => array( 'currency_code' => $total->currency, 'value' => $total->toDecimalString(), ), ), ), ), array( 'PayPal-Request-Id' => $requestId ) ); if ( empty( $res['id'] ) ) { throw new PayPalException( 'PayPal did not return an order id.' ); } return (string) $res['id']; } /** @return array{status:string,capture_id:string,amount:?Money,custom_id:string} */ public function captureOrder( string $orderId, string $requestId ): array { $res = $this->api( 'POST', '/v2/checkout/orders/' . rawurlencode( $orderId ) . '/capture', new \stdClass(), array( 'PayPal-Request-Id' => $requestId ) ); return self::parseCapture( $res ); } /** @return array{status:string,capture_id:string,amount:?Money,custom_id:string} */ public static function parseCapture( array $order ): array { $cap = $order['purchase_units'][0]['payments']['captures'][0] ?? array(); $amount = null; if ( isset( $cap['amount']['value'], $cap['amount']['currency_code'] ) ) { try { $amount = Money::fromDecimalString( (string) $cap['amount']['value'], (string) $cap['amount']['currency_code'] ); } catch ( \InvalidArgumentException $e ) { $amount = null; } } return array( 'status' => (string) ( $cap['status'] ?? ( $order['status'] ?? '' ) ), 'capture_id' => (string) ( $cap['id'] ?? '' ), 'amount' => $amount, 'custom_id' => (string) ( $cap['custom_id'] ?? ( $order['purchase_units'][0]['custom_id'] ?? '' ) ), ); } /** * @param array $headers Incoming webhook request headers (any case; '-' or '_'). */ public function verifyWebhook( array $headers, string $rawBody, string $webhookId ): bool { $h = WebhookGuard::normalizeHeaders( $headers ); // Local pre-checks (headers present, paypal.com cert_url, replay window, size): never spend an outbound call on junk. if ( null !== WebhookGuard::check( $headers, $rawBody, time() ) ) { return false; } $event = json_decode( $rawBody ); if ( ! is_object( $event ) || '' === $webhookId ) { return false; } $need = array( 'paypal_transmission_id', 'paypal_transmission_time', 'paypal_transmission_sig', 'paypal_cert_url', 'paypal_auth_algo' ); foreach ( $need as $n ) { if ( empty( $h[ $n ] ) ) { return false; } } try { $res = $this->api( 'POST', '/v1/notifications/verify-webhook-signature', array( 'auth_algo' => $h['paypal_auth_algo'], 'cert_url' => $h['paypal_cert_url'], 'transmission_id' => $h['paypal_transmission_id'], 'transmission_sig' => $h['paypal_transmission_sig'], 'transmission_time' => $h['paypal_transmission_time'], 'webhook_id' => $webhookId, 'webhook_event' => $event, ) ); } catch ( PayPalException $e ) { return false; // fail closed } return 'SUCCESS' === ( $res['verification_status'] ?? '' ); } /** @return string The new webhook id (store it in settings as paypal_webhook_id). */ public function createWebhook( string $url ): string { $res = $this->api( 'POST', '/v1/notifications/webhooks', array( 'url' => $url, 'event_types' => array_map( static fn( string $n ): array => array( 'name' => $n ), self::WEBHOOK_EVENTS ), ) ); if ( empty( $res['id'] ) ) { throw new PayPalException( 'PayPal did not return a webhook id.' ); } return (string) $res['id']; } /** Returns null when the credentials work, otherwise a human-readable error. */ public function testConnection(): ?string { try { $this->accessToken( true ); return null; } catch ( PayPalException $e ) { return $e->getMessage(); } } /** * Authenticated JSON call. Retries once with a fresh token on 401. * * @param array|\stdClass $payload * @param array $extraHeaders */ private function api( string $method, string $path, array|\stdClass $payload, array $extraHeaders = array() ): array { $body = self::json( $payload ); for ( $attempt = 0; $attempt < 2; $attempt++ ) { $token = $this->accessToken( 1 === $attempt ); $res = $this->send( $method, $path, array_merge( array( 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', 'Accept' => 'application/json', ), $extraHeaders ), $body ); if ( 401 === $res['status'] && 0 === $attempt ) { continue; } break; } if ( $res['status'] < 200 || $res['status'] >= 300 ) { throw self::errorFrom( $res, 'PayPal request failed' ); } return self::decode( $res['body'] ); } /** @return array{status:int,body:string} */ private function send( string $method, string $path, array $headers, ?string $body ): array { try { return $this->http->request( $method, $this->baseUrl() . $path, $headers, $body ); } catch ( TransportException $e ) { throw new PayPalException( 'Could not reach PayPal: ' . $e->getMessage() ); } } private static function decode( string $json ): array { $d = json_decode( $json, true ); return is_array( $d ) ? $d : array(); } private static function errorFrom( array $res, string $prefix ): PayPalException { $d = self::decode( $res['body'] ); $name = (string) ( $d['name'] ?? $d['error'] ?? '' ); $msg = (string) ( $d['message'] ?? $d['error_description'] ?? '' ); $det = (string) ( $d['details'][0]['description'] ?? $d['details'][0]['issue'] ?? '' ); $text = $prefix . ' (HTTP ' . $res['status'] . ')'; if ( '' !== $msg ) { $text .= ': ' . $msg; } if ( '' !== $det ) { $text .= ' - ' . $det; } if ( '' === $name && '' !== $det ) { $name = $det; } return new PayPalException( $text, $res['status'], $name ); } /** json_encode via wp_json_encode when available. */ private static function json( mixed $data ): string { $out = function_exists( 'wp_json_encode' ) ? wp_json_encode( $data ) : json_encode( $data, JSON_UNESCAPED_SLASHES ); return false === $out ? '{}' : $out; } }