$args Request args to merge. * @return array */ public static function http_request_args( array $args = [] ): array { return array_merge( [ 'timeout' => 15, 'headers' => [ 'Content-Type' => 'application/json; charset=utf-8' ], ], $args ); } /** * Trade a one-time token or a known license key for every license on that shop account. * * Error codes (`network`, `invalid_token`, `no_licenses`) match the `advads_exchange_error` * notices on the License screen. * * @param array $credentials `site` plus either `token`, or `license` with optional `license_id`. * @return array>|WP_Error License rows. */ public static function exchange( array $credentials ) { $response = self::post_json( self::endpoint( 'exchange' ), $credentials ); if ( is_wp_error( $response ) ) { return new WP_Error( 'network' ); } $status = (int) wp_remote_retrieve_response_code( $response ); if ( 200 !== $status ) { // shortcut: the shop's error codes aren't documented; maps by HTTP status, refine once they are. if ( 404 === $status ) { return new WP_Error( 'no_licenses' ); } return new WP_Error( $status >= 400 && $status < 500 ? 'invalid_token' : 'network' ); } $rows = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $rows ) ) { return new WP_Error( 'network' ); } return [] === $rows ? new WP_Error( 'no_licenses' ) : $rows; } /** * Run an EDD Software Licensing action (`?edd_action=` on the shop root, not REST). * * EDD answers HTTP 200 with `success` false on refusals, so the caller reads `success` and `error`. * * @param string $action EDD action, e.g. `activate_license`. * @param array $params Form fields such as `license`, `item_name` and `url`. * @return array|WP_Error Decoded response, or `network` when there is no readable answer. */ public static function edd( string $action, array $params ) { $response = wp_remote_post( self::base_url() . '/', [ 'timeout' => 15, 'body' => array_merge( [ 'edd_action' => $action ], $params ), ] ); $body = is_wp_error( $response ) ? null : json_decode( wp_remote_retrieve_body( $response ), true ); return is_array( $body ) ? $body : new WP_Error( 'network' ); } /** * POST JSON to a shop URL. * * @param string $url Request URL. * @param array $payload Request body. * @param array $extra_headers Optional headers merged onto Content-Type. * @return array|\WP_Error wp_remote_post result. */ public static function post_json( string $url, array $payload, array $extra_headers = [] ) { return wp_remote_post( $url, self::http_request_args( [ 'headers' => array_merge( [ 'Content-Type' => 'application/json; charset=utf-8' ], $extra_headers ), 'body' => wp_json_encode( $payload ), ] ) ); } }