update_meta_data() / $order->get_meta() 経由で持つ。 * - **error_log を書かない**(🟠G)。購入者のメールアドレスをログに落とさない。 * * --------------------------------------------------------------------------- * 二重発火について * --------------------------------------------------------------------------- * processing / completed / payment_complete は決済方法によって * 同じ注文で複数回・別の順で発火する。防御は2段構え。 * 1. 注文メタ `_acscw_processed`(処理済みフラグ) * 2. ACSCW_Access::has_grant_for_order()(注文×コンテンツ単位の実在確認) * 1 だけだと、フラグ書き込み前に別プロセスが走ったときに二重付与になりうる。 */ class ACSCW_Orders { /** 注文メタ: 処理済みフラグ。 */ const ORDER_META_PROCESSED = '_acscw_processed'; /** * フックを登録する。 */ public function __construct() { add_action( 'woocommerce_order_status_processing', array( $this, 'maybe_grant_access' ), 10, 1 ); add_action( 'woocommerce_order_status_completed', array( $this, 'maybe_grant_access' ), 10, 1 ); add_action( 'woocommerce_payment_complete', array( $this, 'maybe_grant_access' ), 10, 1 ); // 注文完了ページ。ここは必ず購入者本人のブラウザなので Cookie を発行する。 // 出力前に走らせる必要があるため template_redirect を使う(thankyou では手遅れ)。 add_action( 'template_redirect', array( $this, 'maybe_issue_cookie_on_order_received' ), 6 ); // 注文完了ページに「記事へ戻る」導線を出す(再設計案 §3-3)。 add_action( 'woocommerce_thankyou', array( $this, 'render_return_link' ), 5, 1 ); // 注文メールにアクセスリンクを同梱する(別端末での復旧手段)。 add_action( 'woocommerce_email_after_order_table', array( $this, 'add_access_link_to_email' ), 20, 4 ); } /* * ----------------------------------------------------------------------- * アクセス付与 * ----------------------------------------------------------------------- */ /** * 注文の内容に応じてアクセス権を付与する。 * * @param int $order_id 注文ID。 * @return int 付与した件数。 */ public function maybe_grant_access( $order_id ) { $order_id = absint( $order_id ); if ( 0 === $order_id || ! function_exists( 'wc_get_order' ) ) { return 0; } $order = wc_get_order( $order_id ); if ( ! $order || ! ACSCW_Cart_Context::order_has_acscw_product( $order ) ) { return 0; } $access = ACSCW_Plugin::instance()->get( 'access' ); if ( ! $access instanceof ACSCW_Access ) { return 0; } $email = ACSCW_Access::normalize_email( $order->get_billing_email() ); if ( '' === $email ) { // メールアドレスが無ければ誰に開放するか決められない。 // 処理済みフラグは立てない(管理者が補完して再発火させれば付与される)。 return 0; } $granted = 0; $currency = (string) $order->get_currency(); foreach ( $order->get_items() as $item_id => $item ) { if ( ! method_exists( $item, 'get_product_id' ) ) { continue; } $product_id = $item->get_product_id(); $type = ACSCW_Products::get_product_type( $product_id ); if ( '' === $type ) { continue; } if ( ACSCW_Products::TYPE_TIP === $type ) { /** * 投げ銭を受け取ったときに発火する。 * * 投げ銭は「支払い」であって「アクセス権」ではないため、 * アクセス記録テーブルには入れない。 * post_id=0 で入れるとサイト全体の閲覧権になってしまい、 * 記事IDで入れると買っていない記事が読めてしまう。 * 投げ銭の集計はフェーズ5で注文側から行う。 * * @since 3.0.0 * * @param int $order_id 注文ID。 * @param int $item_id 注文明細ID。 * @param float $amount 金額。 */ do_action( 'acscw_tip_received', $order_id, (int) $item_id, $this->get_item_amount( $item ) ); continue; } $post_id = $this->get_item_post_id( $item ); if ( $post_id <= 0 ) { continue; } // 二重付与防止。注文フックは同じ注文で何度でも発火しうる。 if ( $access->has_grant_for_order( $order_id, $post_id ) ) { continue; } $result = $access->grant( array( 'post_id' => $post_id, 'email' => $email, 'order_id' => $order_id, 'order_item_id' => (int) $item_id, 'source' => ACSCW_Access::SOURCE_PURCHASE, 'amount' => $this->get_item_amount( $item ), 'currency' => $currency, ) ); if ( ! is_wp_error( $result ) ) { ++$granted; } } $this->mark_processed( $order ); if ( $granted > 0 ) { /** * 注文からアクセス権を付与したあとに発火する。 * * @since 3.0.0 * * @param int $order_id 注文ID。 * @param int $granted 付与件数。 * @param string $email 購入者メールアドレス。 */ do_action( 'acscw_order_access_granted', $order_id, $granted, $email ); } // 購入者本人のリクエストであることが確認できる、支払い済みの注文だけ Cookie を発行する。 if ( method_exists( $order, 'is_paid' ) && $order->is_paid() && $this->is_buyer_request( $order ) ) { $this->issue_cookie_for_order( $order ); } return $granted; } /** * 処理済みフラグを立てる。 * * HPOS でも安全なように、必ず注文オブジェクト経由で書く。 * * @param WC_Order $order 注文。 * @return void */ private function mark_processed( $order ) { if ( '1' === (string) $order->get_meta( self::ORDER_META_PROCESSED ) ) { return; } $order->update_meta_data( self::ORDER_META_PROCESSED, '1' ); $order->save(); } /** * 注文明細からコンテンツIDを取り出す。 * * 優先順: * 1. 注文明細メタ `_acscw_post_id`(カート投入時に載せた値) * 2. 商品メタ `_acscw_post_id`(Paywall 商品はコンテンツと1対1なので確実) * * 2 を残してあるのは、ブロック版チェックアウト(Store API)で * 明細メタを載せるアクションが将来変わっても付与が止まらないようにするため。 * * @param WC_Order_Item_Product $item 注文明細。 * @return int */ private function get_item_post_id( $item ) { if ( method_exists( $item, 'get_meta' ) ) { $post_id = absint( $item->get_meta( ACSCW_Checkout::ORDER_ITEM_POST_ID ) ); if ( $post_id > 0 ) { return $post_id; } } return ACSCW_Products::get_linked_post_id( $item->get_product_id() ); } /** * 注文明細の実支払額(税込)を返す。 * * 集計を「今の価格」ではなく「実際に払った額」に固定するために使う(v2 の🟡J)。 * * @param WC_Order_Item_Product $item 注文明細。 * @return float */ private function get_item_amount( $item ) { $total = method_exists( $item, 'get_total' ) ? (float) $item->get_total() : 0.0; $tax = method_exists( $item, 'get_total_tax' ) ? (float) $item->get_total_tax() : 0.0; return round( $total + $tax, 4 ); } /* * ----------------------------------------------------------------------- * 購入直後の Cookie 発行 * ----------------------------------------------------------------------- */ /** * 注文完了ページで、購入者にアクセス Cookie を発行する。 * * 再設計案 §3-3 の「購入直後にメールアドレスを入力させない」を成立させる要。 * template_redirect で走らせるのは、出力開始後は setcookie() できないため。 * * @return void */ public function maybe_issue_cookie_on_order_received() { if ( ! function_exists( 'is_order_received_page' ) || ! is_order_received_page() ) { return; } $order = $this->get_order_from_received_page(); if ( ! $order ) { return; } if ( ! ACSCW_Cart_Context::order_has_acscw_product( $order ) ) { return; } // 未払い(支払い待ち・保留・失敗)の注文では Cookie を発行しない。 // 請求先メールアドレスは購入者が自由に入力できるため、未払い注文で発行すると // 他人のメールアドレスで注文を作るだけで、その人の購入済みコンテンツが読めてしまう。 // 後から支払いが確定した場合は、注文メールのアクセスリンクで復旧できる。 if ( ! $order->is_paid() ) { return; } // 決済方法によっては、この時点でまだステータスフックが走っていないことがある。 // maybe_grant_access() は冪等なので、ここで呼んでも二重付与にならない。 $this->maybe_grant_access( $order->get_id() ); $this->issue_cookie_for_order( $order ); $this->maybe_redirect_to_content( $order ); } /** * 設定に応じて、注文完了ページから元のコンテンツへ自動で戻す。 * * 既定では戻さない。決済ゲートウェイによっては注文完了ページの表示自体が * 決済の確定処理を兼ねているため、勝手に飛ばすと決済側の後処理を壊すことがある。 * 既定は「記事へ戻る」ボタンを出すだけにして、自動化は明示的に選ばせる。 * * @param WC_Order $order 注文。 * @return void */ private function maybe_redirect_to_content( $order ) { /** * 決済完了後に元のコンテンツへ自動で戻すかどうか。 * * @since 3.0.0 * * @param bool $redirect 既定 false(ボタンを出すだけ)。 * @param int $order_id 注文ID。 */ if ( ! apply_filters( 'acscw_redirect_after_purchase', false, $order->get_id() ) ) { return; } $post_ids = $this->get_purchased_post_ids( $order ); if ( empty( $post_ids ) ) { return; } $permalink = get_permalink( $post_ids[0] ); if ( ! $permalink || headers_sent() ) { return; } wp_safe_redirect( $permalink ); exit; } /** * 注文完了ページの注文を取得する。 * * 注文キーが一致しない場合は扱わない(他人の注文完了URLを開いた場合)。 * * @return WC_Order|false */ private function get_order_from_received_page() { if ( ! function_exists( 'wc_get_order' ) ) { return false; } $order_id = absint( get_query_var( 'order-received' ) ); if ( 0 === $order_id ) { return false; } $order = wc_get_order( $order_id ); if ( ! $order ) { return false; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WooCommerce 標準の注文キーで本人性を確認する。 $key = isset( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : ''; if ( '' === $key || ! hash_equals( (string) $order->get_order_key(), $key ) ) { return false; } return $order; } /** * 現在のリクエストが購入者本人のものと確認できるか。 * * 判定材料は WooCommerce の注文キーだけにする。 * 「フロントのリクエストだから本人だろう」といった推定はしない * (推定を許すと、アクセス Cookie を第三者に発行しうる)。 * * nonce は使えない。この URL を組み立てるのは WooCommerce 自身 * (注文完了ページ・注文メール)で、こちらが nonce を差し込む余地が無い。 * 代わりに WooCommerce の注文キーを hash_equals で照合する。 * 注文キーを知らない第三者はこの分岐へ入れない。 * * @param WC_Order $order 注文。 * @return bool */ private function is_buyer_request( $order ) { if ( is_admin() || ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) ) { return false; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended $key = isset( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : ''; if ( '' === $key || ! method_exists( $order, 'get_order_key' ) ) { return false; } return hash_equals( (string) $order->get_order_key(), $key ); } /** * 注文の購入者に、読むための Cookie を発行する。 * * メールアドレス単位の Cookie は、そのメールアドレスの購入をすべて開放する。 * 請求先メールアドレスは購入者が自由に入力できる(本人確認が無い)ため、 * 次のどちらかのときだけ発行する。 * 1. そのメールアドレスの有効な付与が、この注文のものしか無い * (開放される範囲が、この注文で買ったものと同じ) * 2. ログイン中の顧客本人の注文(注文の customer_id が現在のユーザー)で、 * そのメールアドレスの他の付与もすべて同じ顧客の注文から来ている * それ以外(ゲスト注文で同じメールアドレスに別の購入がある、手動付与がある等)は、 * 注文キーで確認できたこの注文の分だけを開放する注文単位 Cookie を発行する。 * 過去の購入は、注文メールのアクセスリンク(メールの受信で本人確認)で開放できる。 * * @param WC_Order $order 注文。 * @return bool */ private function issue_cookie_for_order( $order ) { $email = ACSCW_Access::normalize_email( $order->get_billing_email() ); if ( '' === $email ) { return false; } if ( $this->may_issue_email_cookie( $order, $email ) ) { return $this->issue_cookie( $email ); } $token = ACSCW_Plugin::instance()->get( 'token' ); if ( ! $token instanceof ACSCW_Access_Token ) { return false; } return (bool) $token->issue_order_cookie( (int) $order->get_id() ); } /** * この注文の購入者に、メールアドレス単位の Cookie を出してよいか。 * * @param WC_Order $order 注文。 * @param string $email 正規化済みの請求先メールアドレス。 * @return bool */ private function may_issue_email_cookie( $order, $email ) { $access = ACSCW_Plugin::instance()->get( 'access' ); if ( ! $access instanceof ACSCW_Access ) { return false; } $order_id = (int) $order->get_id(); $others = array_diff( $access->get_active_grant_order_ids( $email ), array( $order_id ) ); if ( empty( $others ) ) { return true; } $customer_id = method_exists( $order, 'get_customer_id' ) ? (int) $order->get_customer_id() : 0; if ( $customer_id <= 0 || get_current_user_id() !== $customer_id ) { return false; } foreach ( $others as $other_id ) { // 手動付与・移行インポート(注文ID 0)は顧客に紐づけられない。 if ( 0 === (int) $other_id ) { return false; } $other = wc_get_order( (int) $other_id ); if ( ! $other || ! method_exists( $other, 'get_customer_id' ) || (int) $other->get_customer_id() !== $customer_id ) { return false; } } return true; } /** * アクセス Cookie を発行する。 * * @param string $email メールアドレス。 * @return bool */ private function issue_cookie( $email ) { if ( '' === $email ) { return false; } $token = ACSCW_Plugin::instance()->get( 'token' ); if ( ! $token instanceof ACSCW_Access_Token ) { return false; } return (bool) $token->issue_cookie( $email ); } /* * ----------------------------------------------------------------------- * 購入後の戻り導線 * ----------------------------------------------------------------------- */ /** * 注文完了ページに「記事へ戻る」導線を出す(再設計案 §3-3)。 * * 自動で戻したいサイトは acscw_redirect_after_purchase フィルタを使う。 * その処理は出力前(template_redirect)で走らせる必要があるため、 * ここではなく maybe_redirect_to_content() が担当する。 * * @param int $order_id 注文ID。 * @return void */ public function render_return_link( $order_id ) { if ( ! function_exists( 'wc_get_order' ) ) { return; } $order = wc_get_order( absint( $order_id ) ); if ( ! $order ) { return; } $post_ids = $this->get_purchased_post_ids( $order ); if ( empty( $post_ids ) ) { return; } echo '
'; foreach ( $post_ids as $post_id ) { $permalink = get_permalink( $post_id ); if ( ! $permalink ) { continue; } printf( '

%2$s

', esc_url( $permalink ), esc_html( sprintf( /* translators: %s: content title */ __( 'Continue reading "%s"', 'acs-content-for-woocommerce' ), get_the_title( $post_id ) ) ) ); } echo '
'; } /** * 注文で購入されたコンテンツIDの一覧。 * * @param WC_Order $order 注文。 * @return int[] */ private function get_purchased_post_ids( $order ) { $post_ids = array(); foreach ( $order->get_items() as $item ) { if ( ! method_exists( $item, 'get_product_id' ) ) { continue; } if ( ACSCW_Products::TYPE_PAYWALL !== ACSCW_Products::get_product_type( $item->get_product_id() ) ) { continue; } $post_id = $this->get_item_post_id( $item ); if ( $post_id > 0 && ! in_array( $post_id, $post_ids, true ) ) { $post_ids[] = $post_id; } } return $post_ids; } /* * ----------------------------------------------------------------------- * 注文メール * ----------------------------------------------------------------------- */ /** * 注文メールにワンタイムのアクセスリンクを同梱する。 * * 別の端末・別のブラウザで読みたいときの復旧手段になる(再設計案 §3-3)。 * 管理者宛のメールには入れない。 * * @param WC_Order $order 注文。 * @param bool $sent_to_admin 管理者宛かどうか。 * @param bool $plain_text テキストメールかどうか。 * @param WC_Email $email メールオブジェクト。 * @return void */ public function add_access_link_to_email( $order, $sent_to_admin = false, $plain_text = false, $email = null ) { unset( $email ); if ( $sent_to_admin || ! is_object( $order ) || ! method_exists( $order, 'get_items' ) ) { return; } $post_ids = $this->get_purchased_post_ids( $order ); if ( ! $order->is_paid() || empty( $post_ids ) ) { return; } $token = ACSCW_Plugin::instance()->get( 'token' ); if ( ! $token instanceof ACSCW_Access_Token ) { return; } $buyer_email = ACSCW_Access::normalize_email( $order->get_billing_email() ); if ( '' === $buyer_email ) { return; } $one_time = $token->create_one_time_token( $buyer_email, $post_ids[0] ); if ( is_wp_error( $one_time ) ) { return; } $url = $token->build_access_url( $one_time, $post_ids[0] ); $text = __( 'Open the content you bought', 'acs-content-for-woocommerce' ); $note = __( 'Use this link to read on another device. In the browser you bought from, you can simply keep reading.', 'acs-content-for-woocommerce' ); if ( $plain_text ) { echo "\n" . esc_html( $text ) . ': ' . esc_url_raw( $url ) . "\n" . esc_html( $note ) . "\n"; return; } printf( '

%2$s
%3$s

', esc_url( $url ), esc_html( $text ), esc_html( $note ) ); } }