class-wc-gateway-paypal.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. if ( ! defined( 'ABSPATH' ) ) {
  13. exit;
  14. }
  15. /**
  16. * WC_Gateway_Paypal Class.
  17. */
  18. class WC_Gateway_Paypal extends WC_Payment_Gateway {
  19. /**
  20. * Whether or not logging is enabled
  21. *
  22. * @var bool
  23. */
  24. public static $log_enabled = false;
  25. /**
  26. * Logger instance
  27. *
  28. * @var WC_Logger
  29. */
  30. public static $log = false;
  31. /**
  32. * Constructor for the gateway.
  33. */
  34. public function __construct() {
  35. $this->id = 'paypal';
  36. $this->has_fields = false;
  37. $this->order_button_text = __( 'Proceed to PayPal', 'woocommerce' );
  38. $this->method_title = __( 'PayPal', 'woocommerce' );
  39. /* translators: %s: Link to WC system status page */
  40. $this->method_description = __( 'PayPal Standard redirects customers to PayPal to enter their payment information.', 'woocommerce' );
  41. $this->supports = array(
  42. 'products',
  43. 'refunds',
  44. );
  45. // Load the settings.
  46. $this->init_form_fields();
  47. $this->init_settings();
  48. // Define user set variables.
  49. $this->title = $this->get_option( 'title' );
  50. $this->description = $this->get_option( 'description' );
  51. $this->testmode = 'yes' === $this->get_option( 'testmode', 'no' );
  52. $this->debug = 'yes' === $this->get_option( 'debug', 'no' );
  53. $this->email = $this->get_option( 'email' );
  54. $this->receiver_email = $this->get_option( 'receiver_email', $this->email );
  55. $this->identity_token = $this->get_option( 'identity_token' );
  56. self::$log_enabled = $this->debug;
  57. if ( $this->testmode ) {
  58. /* translators: %s: Link to PayPal sandbox testing guide page */
  59. $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/' );
  60. $this->description = trim( $this->description );
  61. }
  62. add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
  63. add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
  64. add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
  65. add_action( 'woocommerce_order_status_on-hold_to_completed', array( $this, 'capture_payment' ) );
  66. if ( ! $this->is_valid_for_use() ) {
  67. $this->enabled = 'no';
  68. } else {
  69. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-ipn-handler.php';
  70. new WC_Gateway_Paypal_IPN_Handler( $this->testmode, $this->receiver_email );
  71. if ( $this->identity_token ) {
  72. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-pdt-handler.php';
  73. new WC_Gateway_Paypal_PDT_Handler( $this->testmode, $this->identity_token );
  74. }
  75. }
  76. }
  77. /**
  78. * Return whether or not this gateway still requires setup to function.
  79. *
  80. * When this gateway is toggled on via AJAX, if this returns true a
  81. * redirect will occur to the settings page instead.
  82. *
  83. * @since 3.4.0
  84. * @return bool
  85. */
  86. public function needs_setup() {
  87. return ! is_email( $this->email );
  88. }
  89. /**
  90. * Logging method.
  91. *
  92. * @param string $message Log message.
  93. * @param string $level Optional. Default 'info'. Possible values:
  94. * emergency|alert|critical|error|warning|notice|info|debug.
  95. */
  96. public static function log( $message, $level = 'info' ) {
  97. if ( self::$log_enabled ) {
  98. if ( empty( self::$log ) ) {
  99. self::$log = wc_get_logger();
  100. }
  101. self::$log->log( $level, $message, array( 'source' => 'paypal' ) );
  102. }
  103. }
  104. /**
  105. * Processes and saves options.
  106. * If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
  107. *
  108. * @return bool was anything saved?
  109. */
  110. public function process_admin_options() {
  111. $saved = parent::process_admin_options();
  112. // Maybe clear logs.
  113. if ( 'yes' !== $this->get_option( 'debug', 'no' ) ) {
  114. if ( empty( self::$log ) ) {
  115. self::$log = wc_get_logger();
  116. }
  117. self::$log->clear( 'paypal' );
  118. }
  119. return $saved;
  120. }
  121. /**
  122. * Get gateway icon.
  123. *
  124. * @return string
  125. */
  126. public function get_icon() {
  127. $icon_html = '';
  128. $icon = (array) $this->get_icon_image( WC()->countries->get_base_country() );
  129. foreach ( $icon as $i ) {
  130. $icon_html .= '<img src="' . esc_attr( $i ) . '" alt="' . esc_attr__( 'PayPal acceptance mark', 'woocommerce' ) . '" />';
  131. }
  132. $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( WC()->countries->get_base_country() ) ) );
  133. return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->id );
  134. }
  135. /**
  136. * Get the link for an icon based on country.
  137. *
  138. * @param string $country Country two letter code.
  139. * @return string
  140. */
  141. protected function get_icon_url( $country ) {
  142. $url = 'https://www.paypal.com/' . strtolower( $country );
  143. $home_counties = array( 'BE', 'CZ', 'DK', 'HU', 'IT', 'JP', 'NL', 'NO', 'ES', 'SE', 'TR', 'IN' );
  144. $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' );
  145. if ( in_array( $country, $home_counties, true ) ) {
  146. return $url . '/webapps/mpp/home';
  147. } elseif ( in_array( $country, $countries, true ) ) {
  148. return $url . '/webapps/mpp/paypal-popup';
  149. } else {
  150. return $url . '/cgi-bin/webscr?cmd=xpt/Marketing/general/WIPaypal-outside';
  151. }
  152. }
  153. /**
  154. * Get PayPal images for a country.
  155. *
  156. * @param string $country Country code.
  157. * @return array of image URLs
  158. */
  159. protected function get_icon_image( $country ) {
  160. switch ( $country ) {
  161. case 'US':
  162. case 'NZ':
  163. case 'CZ':
  164. case 'HU':
  165. case 'MY':
  166. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo/AM_mc_vs_dc_ae.jpg';
  167. break;
  168. case 'TR':
  169. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_paypal_odeme_secenekleri.jpg';
  170. break;
  171. case 'GB':
  172. $icon = 'https://www.paypalobjects.com/webstatic/mktg/Logo/AM_mc_vs_ms_ae_UK.png';
  173. break;
  174. case 'MX':
  175. $icon = array(
  176. 'https://www.paypal.com/es_XC/Marketing/i/banner/paypal_visa_mastercard_amex.png',
  177. 'https://www.paypal.com/es_XC/Marketing/i/banner/paypal_debit_card_275x60.gif',
  178. );
  179. break;
  180. case 'FR':
  181. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_paypal_moyens_paiement_fr.jpg';
  182. break;
  183. case 'AU':
  184. $icon = 'https://www.paypalobjects.com/webstatic/en_AU/mktg/logo/Solutions-graphics-1-184x80.jpg';
  185. break;
  186. case 'DK':
  187. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_PayPal_betalingsmuligheder_dk.jpg';
  188. break;
  189. case 'RU':
  190. $icon = 'https://www.paypalobjects.com/webstatic/ru_RU/mktg/business/pages/logo-center/AM_mc_vs_dc_ae.jpg';
  191. break;
  192. case 'NO':
  193. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo-center/banner_pl_just_pp_319x110.jpg';
  194. break;
  195. case 'CA':
  196. $icon = 'https://www.paypalobjects.com/webstatic/en_CA/mktg/logo-image/AM_mc_vs_dc_ae.jpg';
  197. break;
  198. case 'HK':
  199. $icon = 'https://www.paypalobjects.com/webstatic/en_HK/mktg/logo/AM_mc_vs_dc_ae.jpg';
  200. break;
  201. case 'SG':
  202. $icon = 'https://www.paypalobjects.com/webstatic/en_SG/mktg/Logos/AM_mc_vs_dc_ae.jpg';
  203. break;
  204. case 'TW':
  205. $icon = 'https://www.paypalobjects.com/webstatic/en_TW/mktg/logos/AM_mc_vs_dc_ae.jpg';
  206. break;
  207. case 'TH':
  208. $icon = 'https://www.paypalobjects.com/webstatic/en_TH/mktg/Logos/AM_mc_vs_dc_ae.jpg';
  209. break;
  210. case 'JP':
  211. $icon = 'https://www.paypal.com/ja_JP/JP/i/bnr/horizontal_solution_4_jcb.gif';
  212. break;
  213. case 'IN':
  214. $icon = 'https://www.paypalobjects.com/webstatic/mktg/logo/AM_mc_vs_dc_ae.jpg';
  215. break;
  216. default:
  217. $icon = WC_HTTPS::force_https_url( WC()->plugin_url() . '/includes/gateways/paypal/assets/images/paypal.png' );
  218. break;
  219. }
  220. return apply_filters( 'woocommerce_paypal_icon', $icon );
  221. }
  222. /**
  223. * Check if this gateway is enabled and available in the user's country.
  224. *
  225. * @return bool
  226. */
  227. public function is_valid_for_use() {
  228. return in_array(
  229. get_woocommerce_currency(),
  230. apply_filters(
  231. 'woocommerce_paypal_supported_currencies',
  232. 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' )
  233. ),
  234. true
  235. );
  236. }
  237. /**
  238. * Admin Panel Options.
  239. * - Options for bits like 'title' and availability on a country-by-country basis.
  240. *
  241. * @since 1.0.0
  242. */
  243. public function admin_options() {
  244. if ( $this->is_valid_for_use() ) {
  245. parent::admin_options();
  246. } else {
  247. ?>
  248. <div class="inline error">
  249. <p>
  250. <strong><?php esc_html_e( 'Gateway disabled', 'woocommerce' ); ?></strong>: <?php esc_html_e( 'PayPal does not support your store currency.', 'woocommerce' ); ?>
  251. </p>
  252. </div>
  253. <?php
  254. }
  255. }
  256. /**
  257. * Initialise Gateway Settings Form Fields.
  258. */
  259. public function init_form_fields() {
  260. $this->form_fields = include 'includes/settings-paypal.php';
  261. }
  262. /**
  263. * Get the transaction URL.
  264. *
  265. * @param WC_Order $order Order object.
  266. * @return string
  267. */
  268. public function get_transaction_url( $order ) {
  269. if ( $this->testmode ) {
  270. $this->view_transaction_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_view-a-trans&id=%s';
  271. } else {
  272. $this->view_transaction_url = 'https://www.paypal.com/cgi-bin/webscr?cmd=_view-a-trans&id=%s';
  273. }
  274. return parent::get_transaction_url( $order );
  275. }
  276. /**
  277. * Process the payment and return the result.
  278. *
  279. * @param int $order_id Order ID.
  280. * @return array
  281. */
  282. public function process_payment( $order_id ) {
  283. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-request.php';
  284. $order = wc_get_order( $order_id );
  285. $paypal_request = new WC_Gateway_Paypal_Request( $this );
  286. return array(
  287. 'result' => 'success',
  288. 'redirect' => $paypal_request->get_request_url( $order, $this->testmode ),
  289. );
  290. }
  291. /**
  292. * Can the order be refunded via PayPal?
  293. *
  294. * @param WC_Order $order Order object.
  295. * @return bool
  296. */
  297. public function can_refund_order( $order ) {
  298. $has_api_creds = false;
  299. if ( $this->testmode ) {
  300. $has_api_creds = $this->get_option( 'sandbox_api_username' ) && $this->get_option( 'sandbox_api_password' ) && $this->get_option( 'sandbox_api_signature' );
  301. } else {
  302. $has_api_creds = $this->get_option( 'api_username' ) && $this->get_option( 'api_password' ) && $this->get_option( 'api_signature' );
  303. }
  304. return $order && $order->get_transaction_id() && $has_api_creds;
  305. }
  306. /**
  307. * Init the API class and set the username/password etc.
  308. */
  309. protected function init_api() {
  310. include_once dirname( __FILE__ ) . '/includes/class-wc-gateway-paypal-api-handler.php';
  311. WC_Gateway_Paypal_API_Handler::$api_username = $this->testmode ? $this->get_option( 'sandbox_api_username' ) : $this->get_option( 'api_username' );
  312. WC_Gateway_Paypal_API_Handler::$api_password = $this->testmode ? $this->get_option( 'sandbox_api_password' ) : $this->get_option( 'api_password' );
  313. WC_Gateway_Paypal_API_Handler::$api_signature = $this->testmode ? $this->get_option( 'sandbox_api_signature' ) : $this->get_option( 'api_signature' );
  314. WC_Gateway_Paypal_API_Handler::$sandbox = $this->testmode;
  315. }
  316. /**
  317. * Process a refund if supported.
  318. *
  319. * @param int $order_id Order ID.
  320. * @param float $amount Refund amount.
  321. * @param string $reason Refund reason.
  322. * @return bool|WP_Error
  323. */
  324. public function process_refund( $order_id, $amount = null, $reason = '' ) {
  325. $order = wc_get_order( $order_id );
  326. if ( ! $this->can_refund_order( $order ) ) {
  327. return new WP_Error( 'error', __( 'Refund failed.', 'woocommerce' ) );
  328. }
  329. $this->init_api();
  330. $result = WC_Gateway_Paypal_API_Handler::refund_transaction( $order, $amount, $reason );
  331. if ( is_wp_error( $result ) ) {
  332. $this->log( 'Refund Failed: ' . $result->get_error_message(), 'error' );
  333. return new WP_Error( 'error', $result->get_error_message() );
  334. }
  335. $this->log( 'Refund Result: ' . wc_print_r( $result, true ) );
  336. switch ( strtolower( $result->ACK ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
  337. case 'success':
  338. case 'successwithwarning':
  339. $order->add_order_note(
  340. /* translators: 1: Refund amount, 2: Refund ID */
  341. sprintf( __( 'Refunded %1$s - Refund ID: %2$s', 'woocommerce' ), $result->GROSSREFUNDAMT, $result->REFUNDTRANSACTIONID ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
  342. );
  343. return true;
  344. }
  345. return isset( $result->L_LONGMESSAGE0 ) ? new WP_Error( 'error', $result->L_LONGMESSAGE0 ) : false; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
  346. }
  347. /**
  348. * Capture payment when the order is changed from on-hold to complete or processing
  349. *
  350. * @param int $order_id Order ID.
  351. */
  352. public function capture_payment( $order_id ) {
  353. $order = wc_get_order( $order_id );
  354. if ( 'paypal' === $order->get_payment_method() && 'pending' === get_post_meta( $order->get_id(), '_paypal_status', true ) && $order->get_transaction_id() ) {
  355. $this->init_api();
  356. $result = WC_Gateway_Paypal_API_Handler::do_capture( $order );
  357. if ( is_wp_error( $result ) ) {
  358. $this->log( 'Capture Failed: ' . $result->get_error_message(), 'error' );
  359. /* translators: %s: Paypal gateway error message */
  360. $order->add_order_note( sprintf( __( 'Payment could not captured: %s', 'woocommerce' ), $result->get_error_message() ) );
  361. return;
  362. }
  363. $this->log( 'Capture Result: ' . wc_print_r( $result, true ) );
  364. // phpcs:disable WordPress.NamingConventions.ValidVariableName.NotSnakeCaseMemberVar
  365. if ( ! empty( $result->PAYMENTSTATUS ) ) {
  366. switch ( $result->PAYMENTSTATUS ) {
  367. case 'Completed':
  368. /* translators: 1: Amount, 2: Authorization ID, 3: Transaction ID */
  369. $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 ) );
  370. update_post_meta( $order->get_id(), '_paypal_status', $result->PAYMENTSTATUS );
  371. update_post_meta( $order->get_id(), '_transaction_id', $result->TRANSACTIONID );
  372. break;
  373. default:
  374. /* translators: 1: Authorization ID, 2: Payment status */
  375. $order->add_order_note( sprintf( __( 'Payment could not captured - Auth ID: %1$s, Status: %2$s', 'woocommerce' ), $result->AUTHORIZATIONID, $result->PAYMENTSTATUS ) );
  376. break;
  377. }
  378. }
  379. // phpcs:enable
  380. }
  381. }
  382. /**
  383. * Load admin scripts.
  384. *
  385. * @since 3.3.0
  386. */
  387. public function admin_scripts() {
  388. $screen = get_current_screen();
  389. $screen_id = $screen ? $screen->id : '';
  390. if ( 'woocommerce_page_wc-settings' !== $screen_id ) {
  391. return;
  392. }
  393. $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
  394. wp_enqueue_script( 'woocommerce_paypal_admin', WC()->plugin_url() . '/includes/gateways/paypal/assets/js/paypal-admin' . $suffix . '.js', array(), WC_VERSION, true );
  395. }
  396. }