Ei kuvausta

class-wc-gateway-paypal.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /**
  3. * PayPal Standard Payment Gateway.
  4. *
  5. * Provides a PayPal Standard Payment Gateway.
  6. *
  7. * @class WC_Gateway_Paypal
  8. * @extends WC_Payment_Gateway
  9. * @version 2.3.0
  10. * @package WooCommerce\Classes\Payment
  11. */
  12. use Automattic\Jetpack\Constants;
  13. if ( ! defined( 'ABSPATH' ) ) {
  14. exit;
  15. }
  16. /**
  17. * WC_Gateway_Paypal Class.
  18. */
  19. class WC_Gateway_Paypal extends WC_Payment_Gateway {
  20. /**
  21. * Whether or not logging is enabled
  22. *
  23. * @var bool
  24. */
  25. public static $log_enabled = false;
  26. /**
  27. * Logger instance
  28. *
  29. * @var WC_Logger
  30. */
  31. public static $log = false;
  32. /**
  33. * Constructor for the gateway.
  34. */
  35. public function __construct() {
  36. $this->id = 'paypal';
  37. $this->has_fields = false;
  38. $this->order_button_text = __( 'Proceed to PayPal', 'woocommerce' );
  39. $this->method_title = __( 'PayPal Standard', 'woocommerce' );
  40. /* translators: %s: Link to WC system status page */
  41. $this->method_description = __( 'PayPal Standard redirects customers to PayPal to enter their payment information.', 'woocommerce' );
  42. $this->supports = array(
  43. 'products',
  44. 'refunds',
  45. );
  46. // Load the settings.
  47. $this->init_form_fields();
  48. $this->init_settings();
  49. // Define user set variables.
  50. $this->title = $this->get_option( 'title' );
  51. $this->description = $this->get_option( 'description' );
  52. $this->testmode = 'yes' === $this->get_option( 'testmode', 'no' );
  53. $this->debug = 'yes' === $this->get_option( 'debug', 'no' );
  54. $this->email = $this->get_option( 'email' );
  55. $this->receiver_email = $this->get_option( 'receiver_email', $this->email );
  56. $this->identity_token = $this->get_option( 'identity_token' );
  57. self::$log_enabled = $this->debug;
  58. if ( $this->testmode ) {
  59. /* translators: %s: Link to PayPal sandbox testing guide page */
  60. $this->description .= ' ' . sprintf( __( 'SANDBOX ENABLED. You can use sandbox testing accounts only. See the <a href="%s">PayPal Sandbox Testing Guide</a> for more details.', 'woocommerce' ), 'https://developer.paypal.com/docs/classic/lifecycle/ug_sandbox/' );
  61. $this->description = trim( $this->description );
  62. }
  63. add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
  64. add_action( 'woocommerce_order_status_processing', array( $this, 'capture_payment' ) );
  65. add_action( 'woocommerce_order_status_completed', array( $this, 'capture_payment' ) );
  66. add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
  67. if ( ! $this->is_valid_for_use() ) {
  68. $this->enabled = 'no';
  69. } else {
  70. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-ipn-handler.php';
  71. new WC_Gateway_Paypal_IPN_Handler( $this->testmode, $this->receiver_email );
  72. if ( $this->identity_token ) {
  73. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-pdt-handler.php';
  74. new WC_Gateway_Paypal_PDT_Handler( $this->testmode, $this->identity_token );
  75. }
  76. }
  77. if ( 'yes' === $this->enabled ) {
  78. add_filter( 'woocommerce_thankyou_order_received_text', array( $this, 'order_received_text' ), 10, 2 );
  79. }
  80. }
  81. /**
  82. * Return whether or not this gateway still requires setup to function.
  83. *
  84. * When this gateway is toggled on via AJAX, if this returns true a
  85. * redirect will occur to the settings page instead.
  86. *
  87. * @since 3.4.0
  88. * @return bool
  89. */
  90. public function needs_setup() {
  91. return ! is_email( $this->email );
  92. }
  93. /**
  94. * Logging method.
  95. *
  96. * @param string $message Log message.
  97. * @param string $level Optional. Default 'info'. Possible values:
  98. * emergency|alert|critical|error|warning|notice|info|debug.
  99. */
  100. public static function log( $message, $level = 'info' ) {
  101. if ( self::$log_enabled ) {
  102. if ( empty( self::$log ) ) {
  103. self::$log = wc_get_logger();
  104. }
  105. self::$log->log( $level, $message, array( 'source' => 'paypal' ) );
  106. }
  107. }
  108. /**
  109. * Processes and saves options.
  110. * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
  111. *
  112. * @return bool was anything saved?
  113. */
  114. public function process_admin_options() {
  115. $saved = parent::process_admin_options();
  116. // Maybe clear logs.
  117. if ( 'yes' !== $this->get_option( 'debug', 'no' ) ) {
  118. if ( empty( self::$log ) ) {
  119. self::$log = wc_get_logger();
  120. }
  121. self::$log->clear( 'paypal' );
  122. }
  123. return $saved;
  124. }
  125. /**
  126. * Get gateway icon.
  127. *
  128. * @return string
  129. */
  130. public function get_icon() {
  131. // We need a base country for the link to work, bail if in the unlikely event no country is set.
  132. $base_country = WC()->countries->get_base_country();
  133. if ( empty( $base_country ) ) {
  134. return '';
  135. }
  136. $icon_html = '';
  137. $icon = (array) $this->get_icon_image( $base_country );
  138. foreach ( $icon as $i ) {
  139. $icon_html .= '<img src="' . esc_attr( $i ) . '" alt="' . esc_attr__( 'PayPal acceptance mark', 'woocommerce' ) . '" />';
  140. }
  141. $icon_html .= sprintf( '<a href="%1$s" class="about_paypal" onclick="javascript:window.open(\'%1$s\',\'WIPaypal\',\'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=1060, height=700\'); return false;">' . esc_attr__( 'What is PayPal?', 'woocommerce' ) . '</a>', esc_url( $this->get_icon_url( $base_country ) ) );
  142. return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->id );
  143. }
  144. /**
  145. * Get the link for an icon based on country.
  146. *
  147. * @param string $country Country two letter code.
  148. * @return string
  149. */
  150. protected function get_icon_url( $country ) {
  151. $url = 'https://www.paypal.com/' . strtolower( $country );
  152. $home_counties = array( 'BE', 'CZ', 'DK', 'HU', 'IT', 'JP', 'NL', 'NO', 'ES', 'SE', 'TR', 'IN' );
  153. $countries = array( 'DZ', 'AU', 'BH', 'BQ', 'BW', 'CA', 'CN', 'CW', 'FI', 'FR', 'DE', 'GR', 'HK', 'ID', 'JO', 'KE', 'KW', 'LU', 'MY', 'MA', 'OM', 'PH', 'PL', 'PT', 'QA', 'IE', 'RU', 'BL', 'SX', 'MF', 'SA', 'SG', 'SK', 'KR', 'SS', 'TW', 'TH', 'AE', 'GB', 'US', 'VN' );
  154. if ( in_array( $country, $home_counties, true ) ) {
  155. return $url . '/webapps/mpp/home';
  156. } elseif ( in_array( $country, $countries, true ) ) {
  157. return $url . '/webapps/mpp/paypal-popup';
  158. } else {
  159. return $url . '/cgi-bin/webscr?cmd=xpt/Marketing/general/WIPaypal-outside';
  160. }
  161. }
  162. /**
  163. * Get PayPal images for a country.
  164. *
  165. * @param string $country Country code.
  166. * @return array of image URLs
  167. */
  168. protected function get_icon_image( $country ) {
  169. switch ( $country ) {
  170. case 'US':
  171. case 'NZ':
  172. case 'CZ':
  173. case 'HU':
  174. case 'MY':
  175. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo/AM_mc_vs_dc_ae.jpg';
  176. break;
  177. case 'TR':
  178. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_paypal_odeme_secenekleri.jpg';
  179. break;
  180. case 'GB':
  181. $icon = 'https://www.paypalobjects.com/webstatic/mktg/Logo/AM_mc_vs_ms_ae_UK.png';
  182. break;
  183. case 'MX':
  184. $icon = array(
  185. 'https://www.paypal.com/es_XC/Marketing/i/banner/paypal_visa_mastercard_amex.png',
  186. 'https://www.paypal.com/es_XC/Marketing/i/banner/paypal_debit_card_275x60.gif',
  187. );
  188. break;
  189. case 'FR':
  190. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_paypal_moyens_paiement_fr.jpg';
  191. break;
  192. case 'AU':
  193. $icon = 'https://www.paypalobjects.com/webstatic/en_AU/mktg/logo/Solutions-graphics-1-184x80.jpg';
  194. break;
  195. case 'DK':
  196. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_PayPal_betalingsmuligheder_dk.jpg';
  197. break;
  198. case 'RU':
  199. $icon = 'https://www.paypalobjects.com/webstatic/ru_RU/mktg/business/pages/logo-center/AM_mc_vs_dc_ae.jpg';
  200. break;
  201. case 'NO':
  202. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/banner_pl_just_pp_319x110.jpg';
  203. break;
  204. case 'CA':
  205. $icon = 'https://www.paypalobjects.com/webstatic/en_CA/mktg/logo-image/AM_mc_vs_dc_ae.jpg';
  206. break;
  207. case 'HK':
  208. $icon = 'https://www.paypalobjects.com/webstatic/en_HK/mktg/logo/AM_mc_vs_dc_ae.jpg';
  209. break;
  210. case 'SG':
  211. $icon = 'https://www.paypalobjects.com/webstatic/en_SG/mktg/Logos/AM_mc_vs_dc_ae.jpg';
  212. break;
  213. case 'TW':
  214. $icon = 'https://www.paypalobjects.com/webstatic/en_TW/mktg/logos/AM_mc_vs_dc_ae.jpg';
  215. break;
  216. case 'TH':
  217. $icon = 'https://www.paypalobjects.com/webstatic/en_TH/mktg/Logos/AM_mc_vs_dc_ae.jpg';
  218. break;
  219. case 'JP':
  220. $icon = 'https://www.paypal.com/ja_JP/JP/i/bnr/horizontal_solution_4_jcb.gif';
  221. break;
  222. case 'IN':
  223. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo/AM_mc_vs_dc_ae.jpg';
  224. break;
  225. default:
  226. $icon = WC_HTTPS::force_https_url( WC()->plugin_url() . '/includes/gateways/paypal/assets/images/paypal.png' );
  227. break;
  228. }
  229. return apply_filters( 'woocommerce_paypal_icon', $icon );
  230. }
  231. /**
  232. * Check if this gateway is available in the user's country based on currency.
  233. *
  234. * @return bool
  235. */
  236. public function is_valid_for_use() {
  237. return in_array(
  238. get_woocommerce_currency(),
  239. apply_filters(
  240. 'woocommerce_paypal_supported_currencies',
  241. array( 'AUD', 'BRL', 'CAD', 'MXN', 'NZD', 'HKD', 'SGD', 'USD', 'EUR', 'JPY', 'TRY', 'NOK', 'CZK', 'DKK', 'HUF', 'ILS', 'MYR', 'PHP', 'PLN', 'SEK', 'CHF', 'TWD', 'THB', 'GBP', 'RMB', 'RUB', 'INR' )
  242. ),
  243. true
  244. );
  245. }
  246. /**
  247. * Admin Panel Options.
  248. * - Options for bits like 'title' and availability on a country-by-country basis.
  249. *
  250. * @since 1.0.0
  251. */
  252. public function admin_options() {
  253. if ( $this->is_valid_for_use() ) {
  254. parent::admin_options();
  255. } else {
  256. ?>
  257. <div class="inline error">
  258. <p>
  259. <strong><?php esc_html_e( 'Gateway disabled', 'woocommerce' ); ?></strong>: <?php esc_html_e( 'PayPal Standard does not support your store currency.', 'woocommerce' ); ?>
  260. </p>
  261. </div>
  262. <?php
  263. }
  264. }
  265. /**
  266. * Initialise Gateway Settings Form Fields.
  267. */
  268. public function init_form_fields() {
  269. $this->form_fields = include __DIR__ . '/includes/settings-paypal.php';
  270. }
  271. /**
  272. * Get the transaction URL.
  273. *
  274. * @param WC_Order $order Order object.
  275. * @return string
  276. */
  277. public function get_transaction_url( $order ) {
  278. if ( $this->testmode ) {
  279. $this->view_transaction_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_view-a-trans&id=%s';
  280. } else {
  281. $this->view_transaction_url = 'https://www.paypal.com/cgi-bin/webscr?cmd=_view-a-trans&id=%s';
  282. }
  283. return parent::get_transaction_url( $order );
  284. }
  285. /**
  286. * Process the payment and return the result.
  287. *
  288. * @param int $order_id Order ID.
  289. * @return array
  290. */
  291. public function process_payment( $order_id ) {
  292. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-request.php';
  293. $order = wc_get_order( $order_id );
  294. $paypal_request = new WC_Gateway_Paypal_Request( $this );
  295. return array(
  296. 'result' => 'success',
  297. 'redirect' => $paypal_request->get_request_url( $order, $this->testmode ),
  298. );
  299. }
  300. /**
  301. * Can the order be refunded via PayPal?
  302. *
  303. * @param WC_Order $order Order object.
  304. * @return bool
  305. */
  306. public function can_refund_order( $order ) {
  307. $has_api_creds = false;
  308. if ( $this->testmode ) {
  309. $has_api_creds = $this->get_option( 'sandbox_api_username' ) && $this->get_option( 'sandbox_api_password' ) && $this->get_option( 'sandbox_api_signature' );
  310. } else {
  311. $has_api_creds = $this->get_option( 'api_username' ) && $this->get_option( 'api_password' ) && $this->get_option( 'api_signature' );
  312. }
  313. return $order && $order->get_transaction_id() && $has_api_creds;
  314. }
  315. /**
  316. * Init the API class and set the username/password etc.
  317. */
  318. protected function init_api() {
  319. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-api-handler.php';
  320. WC_Gateway_Paypal_API_Handler::$api_username = $this->testmode ? $this->get_option( 'sandbox_api_username' ) : $this->get_option( 'api_username' );
  321. WC_Gateway_Paypal_API_Handler::$api_password = $this->testmode ? $this->get_option( 'sandbox_api_password' ) : $this->get_option( 'api_password' );
  322. WC_Gateway_Paypal_API_Handler::$api_signature = $this->testmode ? $this->get_option( 'sandbox_api_signature' ) : $this->get_option( 'api_signature' );
  323. WC_Gateway_Paypal_API_Handler::$sandbox = $this->testmode;
  324. }
  325. /**
  326. * Process a refund if supported.
  327. *
  328. * @param int $order_id Order ID.
  329. * @param float $amount Refund amount.
  330. * @param string $reason Refund reason.
  331. * @return bool|WP_Error
  332. */
  333. public function process_refund( $order_id, $amount = null, $reason = '' ) {
  334. $order = wc_get_order( $order_id );
  335. if ( ! $this->can_refund_order( $order ) ) {
  336. return new WP_Error( 'error', __( 'Refund failed.', 'woocommerce' ) );
  337. }
  338. $this->init_api();
  339. $result = WC_Gateway_Paypal_API_Handler::refund_transaction( $order, $amount, $reason );
  340. if ( is_wp_error( $result ) ) {
  341. $this->log( 'Refund Failed: ' . $result->get_error_message(), 'error' );
  342. return new WP_Error( 'error', $result->get_error_message() );
  343. }
  344. $this->log( 'Refund Result: ' . wc_print_r( $result, true ) );
  345. switch ( strtolower( $result->ACK ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
  346. case 'success':
  347. case 'successwithwarning':
  348. $order->add_order_note(
  349. /* translators: 1: Refund amount, 2: Refund ID */
  350. sprintf( __( 'Refunded %1$s - Refund ID: %2$s', 'woocommerce' ), $result->GROSSREFUNDAMT, $result->REFUNDTRANSACTIONID ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
  351. );
  352. return true;
  353. }
  354. return isset( $result->L_LONGMESSAGE0 ) ? new WP_Error( 'error', $result->L_LONGMESSAGE0 ) : false; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
  355. }
  356. /**
  357. * Capture payment when the order is changed from on-hold to complete or processing
  358. *
  359. * @param int $order_id Order ID.
  360. */
  361. public function capture_payment( $order_id ) {
  362. $order = wc_get_order( $order_id );
  363. if ( 'paypal' === $order->get_payment_method() && 'pending' === $order->get_meta( '_paypal_status', true ) && $order->get_transaction_id() ) {
  364. $this->init_api();
  365. $result = WC_Gateway_Paypal_API_Handler::do_capture( $order );
  366. if ( is_wp_error( $result ) ) {
  367. $this->log( 'Capture Failed: ' . $result->get_error_message(), 'error' );
  368. /* translators: %s: Paypal gateway error message */
  369. $order->add_order_note( sprintf( __( 'Payment could not be captured: %s', 'woocommerce' ), $result->get_error_message() ) );
  370. return;
  371. }
  372. $this->log( 'Capture Result: ' . wc_print_r( $result, true ) );
  373. // phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
  374. if ( ! empty( $result->PAYMENTSTATUS ) ) {
  375. switch ( $result->PAYMENTSTATUS ) {
  376. case 'Completed':
  377. /* translators: 1: Amount, 2: Authorization ID, 3: Transaction ID */
  378. $order->add_order_note( sprintf( __( 'Payment of %1$s was captured - Auth ID: %2$s, Transaction ID: %3$s', 'woocommerce' ), $result->AMT, $result->AUTHORIZATIONID, $result->TRANSACTIONID ) );
  379. update_post_meta( $order->get_id(), '_paypal_status', $result->PAYMENTSTATUS );
  380. update_post_meta( $order->get_id(), '_transaction_id', $result->TRANSACTIONID );
  381. break;
  382. default:
  383. /* translators: 1: Authorization ID, 2: Payment status */
  384. $order->add_order_note( sprintf( __( 'Payment could not be captured - Auth ID: %1$s, Status: %2$s', 'woocommerce' ), $result->AUTHORIZATIONID, $result->PAYMENTSTATUS ) );
  385. break;
  386. }
  387. }
  388. // phpcs:enable
  389. }
  390. }
  391. /**
  392. * Load admin scripts.
  393. *
  394. * @since 3.3.0
  395. */
  396. public function admin_scripts() {
  397. $screen = get_current_screen();
  398. $screen_id = $screen ? $screen->id : '';
  399. if ( 'woocommerce_page_wc-settings' !== $screen_id ) {
  400. return;
  401. }
  402. $suffix = Constants::is_true( 'SCRIPT_DEBUG' ) ? '' : '.min';
  403. $version = Constants::get_constant( 'WC_VERSION' );
  404. wp_enqueue_script( 'woocommerce_paypal_admin', WC()->plugin_url() . '/includes/gateways/paypal/assets/js/paypal-admin' . $suffix . '.js', array(), $version, true );
  405. }
  406. /**
  407. * Custom PayPal order received text.
  408. *
  409. * @since 3.9.0
  410. * @param string $text Default text.
  411. * @param WC_Order $order Order data.
  412. * @return string
  413. */
  414. public function order_received_text( $text, $order ) {
  415. if ( $order && $this->id === $order->get_payment_method() ) {
  416. return esc_html__( 'Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. Log into your PayPal account to view transaction details.', 'woocommerce' );
  417. }
  418. return $text;
  419. }
  420. /**
  421. * Determines whether PayPal Standard should be loaded or not.
  422. *
  423. * By default PayPal Standard isn't loaded on new installs or on existing sites which haven't set up the gateway.
  424. *
  425. * @since 5.5.0
  426. *
  427. * @return bool Whether PayPal Standard should be loaded.
  428. */
  429. public function should_load() {
  430. $option_key = '_should_load';
  431. $should_load = $this->get_option( $option_key );
  432. if ( '' === $should_load ) {
  433. // New installs without PayPal Standard enabled don't load it.
  434. if ( 'no' === $this->enabled && WC_Install::is_new_install() ) {
  435. $should_load = false;
  436. } else {
  437. $should_load = true;
  438. }
  439. $this->update_option( $option_key, wc_bool_to_string( $should_load ) );
  440. } else {
  441. $should_load = wc_string_to_bool( $should_load );
  442. }
  443. /**
  444. * Allow third-parties to filter whether PayPal Standard should be loaded or not.
  445. *
  446. * @since 5.5.0
  447. *
  448. * @param bool $should_load Whether PayPal Standard should be loaded.
  449. * @param WC_Gateway_Paypal $this The WC_Gateway_Paypal instance.
  450. */
  451. return apply_filters( 'woocommerce_should_load_paypal_standard', $should_load, $this );
  452. }
  453. }