<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[2532] sites/trunk/wordcamp.org/public_html/wp-content/plugins: WordCamp Budgets Dashboard: Send Sponsor Invoices to QuickBooks.</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="http://meta.trac.wordpress.org/changeset/2532">2532</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"http://meta.trac.wordpress.org/changeset/2532","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>iandunn</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2016-02-19 00:10:43 +0000 (Fri, 19 Feb 2016)</dd>
</dl>
<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>WordCamp Budgets Dashboard: Send Sponsor Invoices to QuickBooks.
This includes several interconnected pieces:
* Creating new Customers
* Fetching existing Customers
* Creating Invoices
* Sending Invoices</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcamppaymentsnetworkincludessponsorinvoicesdashboardphp">sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-payments-network/includes/sponsor-invoices-dashboard.php</a></li>
<li><a href="#sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcampqbowordcampqbophp">sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo/wordcamp-qbo.php</a></li>
<li><a href="#sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcampqboclientwordcampqboclientphp">sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo-client/wordcamp-qbo-client.php</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcamppaymentsnetworkincludessponsorinvoicesdashboardphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-payments-network/includes/sponsor-invoices-dashboard.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-payments-network/includes/sponsor-invoices-dashboard.php 2016-02-18 23:18:12 UTC (rev 2531)
+++ sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-payments-network/includes/sponsor-invoices-dashboard.php 2016-02-19 00:10:43 UTC (rev 2532)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -216,7 +216,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> switch_to_blog( $site_id );
</span><span class="cx" style="display: block; padding: 0 10px">
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">- $quickbooks_result = send_invoice_to_quickbooks( $site_id, $invoice_id );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ $quickbooks_result = \WordCamp_QBO_Client::send_invoice_to_quickbooks( $invoice_id );
</ins><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> if ( is_int( $quickbooks_result ) ) {
</span><span class="cx" style="display: block; padding: 0 10px"> update_post_meta( $invoice_id, '_wcbsi_qbo_invoice_id', absint( $quickbooks_result ) );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -238,50 +238,6 @@
</span><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">- * Send an invoice to the sponsor through QuickBooks Online's API
- *
- * @param int $site_id
- * @param int $invoice_id
- *
- * @return int|string
- */
-function send_invoice_to_quickbooks( $site_id, $invoice_id ) {
- switch_to_blog( $site_id );
-
- $invoice_meta = get_post_custom( $invoice_id );
- $sponsor_meta = get_post_custom( $invoice_meta['_wcbsi_sponsor_id'][0] );
-
- /* these are the values needed for the API call. they're guaranteed to exist.
- wp_send_json_error( array(
- $sponsor_meta['_wcpt_sponsor_company_name'][0],
- $sponsor_meta['_wcpt_sponsor_first_name'][0],
- $sponsor_meta['_wcpt_sponsor_last_name'][0],
- $sponsor_meta['_wcpt_sponsor_email_address'][0],
- $sponsor_meta['_wcpt_sponsor_phone_number'][0],
-
- $sponsor_meta['_wcpt_sponsor_street_address1'][0],
- $sponsor_meta['_wcpt_sponsor_street_address2'][0],
- $sponsor_meta['_wcpt_sponsor_city'][0],
- $sponsor_meta['_wcpt_sponsor_state'][0],
- $sponsor_meta['_wcpt_sponsor_zip_code'][0],
- $sponsor_meta['_wcpt_sponsor_country'][0],
-
- $invoice_meta['_wcbsi_due_date'][0],
- $invoice_meta['_wcbsi_description'][0],
- $invoice_meta['_wcbsi_currency'][0],
- $invoice_meta['_wcbsi_amount'][0],
- ) );
- */
-
- $sent = 'QuickBooks integration is not complete yet.';
- // todo return QBO invoice ID on success, or an error message string on failure
-
- restore_current_blog();
-
- return $sent;
-}
-
-/**
</del><span class="cx" style="display: block; padding: 0 10px"> * Send a request to QuickBooks to check if any sent invoices have been paid
</span><span class="cx" style="display: block; padding: 0 10px"> *
</span><span class="cx" style="display: block; padding: 0 10px"> * If any have been, update the status of the local copy, and notify the organizer who sent the invoice.
</span></span></pre></div>
<a id="sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcampqbowordcampqbophp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo/wordcamp-qbo.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo/wordcamp-qbo.php 2016-02-18 23:18:12 UTC (rev 2531)
+++ sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo/wordcamp-qbo.php 2016-02-19 00:10:43 UTC (rev 2532)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -83,6 +83,11 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 'methods' => 'GET',
</span><span class="cx" style="display: block; padding: 0 10px"> 'callback' => array( __CLASS__, 'rest_callback_classes' ),
</span><span class="cx" style="display: block; padding: 0 10px"> ) );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+ register_rest_route( 'wordcamp-qbo/v1', '/invoice', array(
+ 'methods' => 'GET, POST',
+ 'callback' => array( __CLASS__, 'rest_callback_invoice' ),
+ ) );
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -263,6 +268,571 @@
</span><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ * REST: /invoice
+ *
+ * Creates a new Invoice in QuickBooks and sends it to the Customer
+ *
+ * @param WP_REST_Request $request
+ *
+ * @return int|WP_Error The invoice ID on success, or a WP_Error on failure
+ */
+ public static function rest_callback_invoice( $request ) {
+ if ( ! self::_is_valid_request( $request ) ) {
+ return new WP_Error( 'unauthorized', 'Unauthorized', array( 'status' => 401 ) );
+ }
+
+ $invoice_id = self::create_invoice(
+ $request->get_param( 'sponsor' ),
+ $request->get_param( 'currency_code' ),
+ $request->get_param( 'qbo_class_id' ),
+ $request->get_param( 'invoice_title' ),
+ $request->get_param( 'amount' ),
+ $request->get_param( 'description' ),
+ $request->get_param( 'due_date' ),
+ $request->get_param( 'statement_memo' )
+ );
+
+ if ( is_wp_error( $invoice_id ) ) {
+ return $invoice_id;
+ }
+
+ /*
+ * @todo Sending invoices automatically is initially disabled so we can manually review them for accuracy
+ $invoice_sent = self::send_invoice( $invoice_id );
+
+ if ( is_wp_error( $invoice_sent ) ) {
+ self::notify_invoice_failed_to_send( $invoice_id, $invoice_sent );
+ }
+ */
+
+ return $invoice_id;
+ }
+
+ /**
+ * Creates an Invoice in QuickBooks
+ *
+ * @param array $sponsor
+ * @param string $currency_code
+ * @param int $class_id
+ * @param string $invoice_title
+ * @param float $amount
+ * @param string $description
+ * @param string $due_date
+ * @param string $statement_memo
+ *
+ * @return int|WP_Error Invoice ID on success; error on failure
+ */
+ protected static function create_invoice( $sponsor, $currency_code, $class_id, $invoice_title, $amount, $description, $due_date, $statement_memo ) {
+ $qbo_request = self::build_qbo_create_invoice_request(
+ $sponsor,
+ $currency_code,
+ $class_id,
+ $invoice_title,
+ $amount,
+ $description,
+ $due_date,
+ $sponsor['email-address'],
+ $statement_memo
+ );
+
+ if ( is_wp_error( $qbo_request ) ) {
+ return $qbo_request;
+ }
+
+ $response = wp_remote_post( $qbo_request['url'], $qbo_request['args'] );
+
+ if ( is_wp_error( $response ) ) {
+ $result = $response;
+ } elseif ( 200 != wp_remote_retrieve_response_code( $response ) ) {
+ $result = new WP_Error( 'invalid_http_code', 'Invalid HTTP response code', $response );
+ } else {
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( isset( $body['Invoice']['Id'] ) ) {
+ $result = absint( $body['Invoice']['Id'] );
+ } else {
+ $result = new WP_Error( 'empty_body', 'Could not decode invoice result.', $response );
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Build the requset to create an invoice in QuickBooks
+ *
+ * @param array $sponsor
+ * @param string $currency_code
+ * @param int $class_id
+ * @param string $invoice_title
+ * @param float $amount
+ * @param string $description
+ * @param string $due_date
+ * @param string $customer_email
+ * @param string $statement_memo
+ *
+ * @return array|WP_Error
+ */
+ protected static function build_qbo_create_invoice_request( $sponsor, $currency_code, $class_id, $invoice_title, $amount, $description, $due_date, $customer_email, $statement_memo ) {
+ $customer_id = self::probably_get_customer_id( $sponsor, $currency_code );
+
+ if ( is_wp_error( $customer_id ) ) {
+ return $customer_id;
+ }
+
+ $class_id = sanitize_text_field( $class_id );
+ $invoice_title = sanitize_text_field( $invoice_title );
+ $amount = floatval( $amount );
+ $description = sanitize_text_field( $description );
+ $due_date = sanitize_text_field( $due_date );
+ $statement_memo = sanitize_text_field( $statement_memo );
+
+ /*
+ * The currency code only needs to be sanitized, not validated, because QBO will reject the invoice if
+ * an invalid code is passed. We don't have to worry about an invoice being assigned the the home currency
+ * by accident.
+ */
+ $currency_code = sanitize_text_field( $currency_code );
+
+ /*
+ * QBO sandboxes will send invoices to whatever e-mail address you assign them, rather than sending them
+ * to the sandbox owner. So to avoid sending sandbox e-mails to real sponsor addresses, we use a fake
+ * address instead.
+ */
+ if ( self::$sandbox_mode ) {
+ $customer_email = 'jane.doe@example.org';
+ } else {
+ $customer_email = is_email( $customer_email );
+ }
+
+ foreach ( array( 'amount', 'due_date', 'customer_id', 'customer_email' ) as $field ) {
+ if ( empty( $$field ) ) {
+ return new WP_Error( 'required_field_empty', "$field cannot be empty." );
+ }
+ }
+
+ self::load_options();
+ $oauth = self::_get_oauth();
+ $oauth->set_token( self::$options['auth']['oauth_token'], self::$options['auth']['oauth_token_secret'] );
+
+ $payment_instructions = str_replace( "\t", '', "
+ Please remit checks to: WordPress Community Support, PBC, 3426 SE Kathryn Ct, Milwaukie, OR 97222
+
+ For payments via ACH or international wire transfers:
+
+ Bank Name: JPMorgan Chase Bank, N.A.
+ Bank Address: 4 New York Plaza, Floor 15, New York, NY 10004, USA
+ SWIFT/BIC: CHASUS33
+ Bank Routing & Transit Number: 021000021
+ Account Number: 791828879
+
+ To pay via credit card: Please send the payment via PayPal to sponsor@wordcamp.org. An additional 3% on the payment to cover PayPal fees is highly appreciated."
+ );
+
+ $payload = array(
+ 'PrivateNote' => $statement_memo,
+
+ 'Line' => array(
+ array(
+ 'Amount' => $amount,
+ 'Description' => $invoice_title,
+ 'DetailType' => 'SalesItemLineDetail',
+
+ 'SalesItemLineDetail' => array(
+ 'ItemRef' => array(
+ 'value' => '20', // Sponsorship
+ ),
+
+ 'ClassRef' => array(
+ 'value' => $class_id,
+ ),
+
+ 'UnitPrice' => $amount,
+ 'Qty' => 1,
+ )
+ )
+ ),
+
+ 'CustomerRef' => array(
+ 'value' => $customer_id,
+ ),
+
+ // Note: the limit for this is 1,000 characters
+ 'CustomerMemo' => array(
+ 'value' => sprintf( "%s\n%s", $description, $payment_instructions ),
+ ),
+
+ 'SalesTermRef' => array(
+ 'value' => 1, // Due on receipt
+ ),
+
+ 'DueDate' => $due_date,
+
+ 'BillEmail' => array(
+ 'Address' => $customer_email,
+ ),
+ );
+
+ /*
+ * QuickBooks doesn't have a CustomerCurrency row for the home currency, so a CurrencyRef is only used
+ * for foreign currencies.
+ *
+ * QBO will automatically activate a valid currency for our Company when we create an invoice using it
+ * for the first time, so we don't need any code to automatically activate them.
+ */
+ if ( 'USD' != $currency_code ) {
+ $payload['CurrencyRef'] = array(
+ 'value' => $currency_code,
+ );
+ }
+
+ $request_url = sprintf(
+ '%s/v3/company/%d/invoice',
+ self::$api_base_url,
+ rawurlencode( self::$options['auth']['realmId'] )
+ );
+
+ $payload = wp_json_encode( $payload );
+
+ $args = array(
+ 'headers' => array(
+ 'Authorization' => $oauth->get_oauth_header( 'POST', $request_url, $payload ),
+ 'Accept' => 'application/json',
+ 'Content-Type' => 'application/json',
+ ),
+ 'body' => $payload,
+ );
+
+ return array(
+ 'url' => $request_url,
+ 'args' => $args
+ );
+ }
+
+ /**
+ * Email a QuickBooks invoice to the Customer
+ *
+ * @param int $invoice_id
+ *
+ * @return bool|WP_Error true on success; WP_Error on failure
+ */
+ protected static function send_invoice( $invoice_id ) {
+ $qbo_request = self::build_qbo_send_invoice_request( $invoice_id );
+ $response = wp_remote_post( $qbo_request['url'], $qbo_request['args'] );
+
+ if ( is_wp_error( $response ) ) {
+ $result = $response;
+ } elseif ( 200 != wp_remote_retrieve_response_code( $response ) ) {
+ $result = new WP_Error( 'invalid_http_code', 'Invalid HTTP response code', $response );
+ } else {
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( isset( $body['Invoice']['EmailStatus'] ) && 'EmailSent' === $body['Invoice']['EmailStatus'] ) {
+ $result = true;
+ } else {
+ $result = new WP_Error( 'empty_body', 'Could not decode invoice result.', $response );
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Build a request to send an Invoice via QuickBook's API
+ *
+ * @param int $invoice_id
+ *
+ * @return array
+ */
+ protected static function build_qbo_send_invoice_request( $invoice_id ) {
+ self::load_options();
+ $oauth = self::_get_oauth();
+ $oauth->set_token( self::$options['auth']['oauth_token'], self::$options['auth']['oauth_token_secret'] );
+
+ $request_url = sprintf(
+ '%s/v3/company/%d/invoice/%s/send',
+ self::$api_base_url,
+ rawurlencode( self::$options['auth']['realmId'] ),
+ rawurlencode( absint( $invoice_id ) )
+ );
+
+ $args = array(
+ 'headers' => array(
+ 'Authorization' => $oauth->get_oauth_header( 'POST', $request_url ),
+ 'Accept' => 'application/json',
+ 'Content-Type' => 'application/octet-stream',
+ ),
+ 'body' => '',
+ );
+
+ return array(
+ 'url' => $request_url,
+ 'args' => $args,
+ );
+ }
+
+ /**
+ * Notify Central that an invoice was created but couldn't be sent to the sponsor
+ *
+ * @param int $invoice_id
+ * @param WP_Error $error
+ *
+ * @return bool
+ */
+ protected static function notify_invoice_failed_to_send( $invoice_id, $error ) {
+ $message = sprintf( "
+ QuickBooks invoice $invoice_id was created, but an error occurred while trying to send it to the sponsor.
+
+ This may be an indication of a bug on WordCamp.org, so please ask your friendly neighborhood developers to investigate.
+
+ The invoice will probably need to be sent manually in QuickBooks, but let the developers investigate first, and then go from there.
+
+ Debugging information for the developers:
+
+ %s",
+ print_r( $error, true )
+ );
+ $message = str_replace( "\t", '', $message );
+
+ return wp_mail( 'support@wordcamp.org', "QuickBooks invoice $invoice_id failed to send", $message );
+ }
+
+ /**
+ * Get a Customer ID, either by finding an existing one, or creating a new one
+ *
+ * @param string $sponsor
+ * @param string $currency_code
+ *
+ * @return int|WP_Error The customer ID if success; a WP_Error if failure
+ */
+ protected static function probably_get_customer_id( $sponsor, $currency_code ) {
+ $customer_id = self::get_customer( $sponsor['company-name'], $currency_code );
+
+ if ( is_wp_error( $customer_id ) || ! $customer_id ) {
+ $customer_id = self::create_customer( $sponsor, $currency_code );
+ }
+
+ return $customer_id;
+ }
+
+ /**
+ * Fetch a Customer record from QBO
+ *
+ * @param string $customer_name
+ * @param string $currency_code
+ *
+ * @return int|false|WP_Error A customer ID as integer, if one was found; false if no match was found; a WP_Error if an error occurred.
+ */
+ protected static function get_customer( $customer_name, $currency_code ) {
+ $qbo_request = self::build_qbo_get_customer_request( $customer_name );
+
+ if ( is_wp_error( $qbo_request ) ) {
+ return $qbo_request;
+ }
+
+ $response = wp_remote_get( $qbo_request['url'], $qbo_request['args'] );
+
+ if ( is_wp_error( $response ) ) {
+ $result = $response;
+ } elseif ( 200 != wp_remote_retrieve_response_code( $response ) ) {
+ $result = new WP_Error( 'invalid_http_code', 'Invalid HTTP response code', $response );
+ } else {
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( isset( $body['QueryResponse']['Customer'][0]['Id'] ) ) {
+ $result = self::pluck_customer_id_by_currency( $body['QueryResponse']['Customer'], $currency_code );
+ } elseif ( isset( $body['QueryResponse'] ) && 0 === count( $body['QueryResponse'] ) ) {
+ $result = false;
+ } else {
+ $result = new WP_Error( 'invalid_response_body', 'Could not extract information from response.', $response );
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Build a request to fetch a Customer from QuickBook's API
+ *
+ * @param string $customer_name
+ *
+ * @return array|WP_Error
+ */
+ protected static function build_qbo_get_customer_request( $customer_name ) {
+ global $wpdb;
+
+ $customer_name = sanitize_text_field( $customer_name );
+
+ self::load_options();
+ $oauth = self::_get_oauth();
+ $oauth->set_token( self::$options['auth']['oauth_token'], self::$options['auth']['oauth_token_secret'] );
+
+ $request_url = sprintf(
+ '%s/v3/company/%d/query',
+ self::$api_base_url,
+ rawurlencode( self::$options['auth']['realmId'] )
+ );
+
+ $request_url_query = array(
+ 'query' => $wpdb->prepare(
+ "SELECT * FROM Customer WHERE CompanyName = '%s'",
+ $customer_name
+ ),
+ );
+
+ $args = array(
+ 'headers' => array(
+ 'Authorization' => $oauth->get_oauth_header( 'GET', $request_url, $request_url_query ),
+ 'Accept' => 'application/json',
+ ),
+ );
+
+ $request_url_query = array_map( 'rawurlencode', $request_url_query ); // has to be done after get_oauth_header(), or oauth_signature won't be generated correctly
+ $request_url = add_query_arg( $request_url_query, $request_url );
+
+ return array(
+ 'url' => $request_url,
+ 'args' => $args,
+ );
+ }
+
+ /**
+ * Pluck a Customer out of an array based on their currency
+ *
+ * QuickBook's API doesn't allow you to filter query results based on a CurrencyRef, so we have to do it
+ * manually.
+ *
+ * @param array $customers
+ * @param string $currency_code
+ *
+ * @return int|false A customer ID on success, or false on failure
+ */
+ protected static function pluck_customer_id_by_currency( $customers, $currency_code ) {
+ $customer_id = false;
+
+ foreach ( $customers as $customer ) {
+ if ( $customer['CurrencyRef']['value'] === $currency_code ) {
+ $customer_id = absint( $customer['Id'] );
+ break;
+ }
+ }
+
+ return $customer_id;
+ }
+
+ /**
+ * Create a customer in QuickBooks for a corresponding Sponsor in WordCamp.org
+ *
+ * @param array $sponsor
+ * @param string $currency_code
+ *
+ * @return int|WP_Error The customer ID if success; a WP_Error if failure
+ */
+ protected static function create_customer( $sponsor, $currency_code ) {
+ $qbo_request = self::build_qbo_create_customer_request( $sponsor, $currency_code );
+
+ if ( is_wp_error( $qbo_request ) ) {
+ return $qbo_request;
+ }
+
+ $response = wp_remote_post( $qbo_request['url'], $qbo_request['args'] );
+
+ if ( is_wp_error( $response ) ) {
+ $result = $response;
+ } elseif ( 200 != wp_remote_retrieve_response_code( $response ) ) {
+ $result = new WP_Error( 'invalid_http_code', 'Invalid HTTP response code', $response );
+ } else {
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( isset( $body['Customer']['Id'] ) ) {
+ $result = absint( $body['Customer']['Id'] );
+ } else {
+ $result = new WP_Error( 'invalid_response_body', 'Could not extract customer ID from response.', $response );
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Build a request to create a Customer via QuickBook's API
+ *
+ * @param array $sponsor
+ * @param string $currency_code
+ *
+ * @return array|WP_Error
+ */
+ protected static function build_qbo_create_customer_request( $sponsor, $currency_code ) {
+ self::load_options();
+ $oauth = self::_get_oauth();
+ $oauth->set_token( self::$options['auth']['oauth_token'], self::$options['auth']['oauth_token_secret'] );
+
+ $sponsor = array_map( 'sanitize_text_field', $sponsor );
+ $sponsor['email-address'] = is_email( $sponsor['email-address'] );
+ $currency_code = sanitize_text_field( $currency_code );
+
+ if ( empty( $sponsor['company-name'] ) || empty( $sponsor['email-address'] ) ) {
+ return new WP_Error( 'required_fields_missing', 'Required fields are missing.', $sponsor );
+ }
+
+ $payload = array(
+ 'BillAddr' => array(
+ 'Line1' => $sponsor['address1'],
+ 'City' => $sponsor['city'],
+ 'Country' => $sponsor['country'],
+ 'CountrySubDivisionCode' => $sponsor['state'],
+ 'PostalCode' => $sponsor['zip-code'],
+ ),
+
+ 'CurrencyRef' => array(
+ 'value' => $currency_code
+ ),
+
+ 'PreferredDeliveryMethod' =>'Email',
+
+ 'GivenName' => $sponsor['first-name'],
+ 'FamilyName' => $sponsor['last-name'],
+ 'CompanyName' => $sponsor['company-name'],
+ 'DisplayName' => sprintf( '%s - %s', $sponsor['company-name'], $currency_code ),
+ 'PrintOnCheckName' => $sponsor['company-name'],
+
+ 'PrimaryPhone' => array(
+ 'FreeFormNumber' => $sponsor['phone-number'],
+ ),
+
+ 'PrimaryEmailAddr' => array(
+ 'Address' => $sponsor['email-address'],
+ ),
+ );
+
+ if ( isset( $sponsor['address2'] ) ) {
+ $payload['BillAddr']['Line2'] = $sponsor['address2'];
+ }
+
+ $request_url = sprintf(
+ '%s/v3/company/%d/customer',
+ self::$api_base_url,
+ rawurlencode( self::$options['auth']['realmId'] )
+ );
+
+ $payload = wp_json_encode( $payload );
+
+ $args = array(
+ 'headers' => array(
+ 'Authorization' => $oauth->get_oauth_header( 'POST', $request_url, $payload ),
+ 'Accept' => 'application/json',
+ 'Content-Type' => 'application/json',
+ ),
+ 'body' => $payload,
+ );
+
+ return array(
+ 'url' => $request_url,
+ 'args' => $args,
+ );
+ }
+
+ /**
</ins><span class="cx" style="display: block; padding: 0 10px"> * Verify an HMAC signature for an API request.
</span><span class="cx" style="display: block; padding: 0 10px"> *
</span><span class="cx" style="display: block; padding: 0 10px"> * @param WP_REST_Request $request The REST API request.
</span></span></pre></div>
<a id="sitestrunkwordcamporgpublic_htmlwpcontentpluginswordcampqboclientwordcampqboclientphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo-client/wordcamp-qbo-client.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo-client/wordcamp-qbo-client.php 2016-02-18 23:18:12 UTC (rev 2531)
+++ sites/trunk/wordcamp.org/public_html/wp-content/plugins/wordcamp-qbo-client/wordcamp-qbo-client.php 2016-02-19 00:10:43 UTC (rev 2532)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -269,6 +269,101 @@
</span><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px">
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ * Send an invoice to the sponsor through QuickBooks Online's API
+ *
+ * @param int $invoice_id
+ *
+ * @return string
+ */
+ public static function send_invoice_to_quickbooks( $invoice_id ) {
+ $request = self::build_send_invoice_request( $invoice_id );
+ $response = wp_remote_post( $request['url'], $request['args'] );
+
+ if ( is_wp_error( $response ) ) {
+ $sent = $response->get_error_message();
+ } else {
+ $body = json_decode( wp_remote_retrieve_body( $response ) );
+
+ if ( is_numeric( $body ) ) {
+ $sent = absint( $body );
+ } elseif ( isset( $body->message ) ) {
+ $sent = $body->message;
+ } else {
+ $sent = 'Unknown error.';
+ }
+ }
+
+ return $sent;
+ }
+
+ /**
+ * Build a request for sending an invoice to QuickBooks
+ *
+ * @param int $invoice_id
+ *
+ * @return array
+ */
+ protected static function build_send_invoice_request( $invoice_id ) {
+ $invoice = get_post( $invoice_id );
+ $invoice_meta = get_post_custom( $invoice_id );
+ $sponsor_meta = get_post_custom( $invoice_meta['_wcbsi_sponsor_id'][0] );
+
+ $due_date = new \DateTime(
+ date( 'Y-m-d', $invoice_meta['_wcbsi_due_date'][0] ),
+ new \DateTimeZone( get_option('timezone_string') )
+ );
+
+ $payload = array(
+ 'invoice_title' => sanitize_text_field( $invoice->post_title ),
+ 'currency_code' => sanitize_text_field( $invoice_meta['_wcbsi_currency' ][0] ),
+ 'qbo_class_id' => sanitize_text_field( $invoice_meta['_wcbsi_qbo_class_id' ][0] ),
+ 'amount' => floatval( $invoice_meta['_wcbsi_amount' ][0] ),
+ 'description' => sanitize_text_field( $invoice_meta['_wcbsi_description' ][0] ),
+ 'due_date' => $due_date->format( 'Y-m-dP' ),
+
+ 'statement_memo' => sprintf(
+ 'WordCamp.org Invoice: %s',
+ esc_url_raw( admin_url( sprintf( 'post.php?post=%s&action=edit', $invoice_id ) ) )
+ ),
+
+ 'sponsor' => array(
+ 'company-name' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_company_name' ][0] ),
+ 'first-name' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_first_name' ][0] ),
+ 'last-name' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_last_name' ][0] ),
+ 'email-address' => is_email( $sponsor_meta['_wcpt_sponsor_email_address'][0] ),
+ 'phone-number' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_phone_number' ][0] ),
+
+ 'address1' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_street_address1'][0] ),
+ 'city' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_city' ][0] ),
+ 'state' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_state' ][0] ),
+ 'zip-code' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_zip_code' ][0] ),
+ 'country' => sanitize_text_field( $sponsor_meta['_wcpt_sponsor_country' ][0] ),
+ )
+ );
+
+ if ( isset( $sponsor_meta['_wcpt_sponsor_street_address2'][0] ) ) {
+ $payload['sponsor']['address2'] = sanitize_text_field( $sponsor_meta['_wcpt_sponsor_street_address2'][0] );
+ }
+
+ $request_url = self::$api_base . '/invoice';
+ $body = wp_json_encode( $payload );
+ $oauth_header = self::_get_auth_header( 'post', $request_url, $body );
+
+ $args = array(
+ 'headers' => array(
+ 'Authorization' => $oauth_header,
+ 'Content-Type' => 'application/json',
+ ),
+ 'body' => $body,
+ );
+
+ return array(
+ 'url' => $request_url,
+ 'args' => $args,
+ );
+ }
+
+ /**
</ins><span class="cx" style="display: block; padding: 0 10px"> * Create an HMAC signature header for a request.
</span><span class="cx" style="display: block; padding: 0 10px"> *
</span><span class="cx" style="display: block; padding: 0 10px"> * Use with Authorization HTTP header.
</span></span></pre>
</div>
</div>
</body>
</html>