Skip to content

Commit

Permalink
Update all examples for Web Payments SDK and 2021-05-13 release (#242)
Browse files Browse the repository at this point in the history
* upgrade node-payment sample app to use the web payment sdk

* use fetch instead of form submit

* fix typo

* Adds snippet sample application to connect examples

* disable input field if ACH is unavailable

* remove used files

* Upgrade Java OAuth sample app to use the latest Square SDK

* update comment

update comment

* update link in README

* add more comments

* remove unwanted files

* allow node and php oauth example to test in both sandbox and production mode

* modify some comments

* upgrade python and ruby

* use default registry to resolve node dependencies

* update README

* add style.css

* update ruby example

* add styling to python oauth

* follow sinatra conventions

* add templating to ruby and node for simpler code

* addressed some comments in PR

* use window.createPayment

* rename function to SquarePaymentFlow()

* Update node_orders-payments to use web payment sdk

* remove unused css elements

* Migrate Java payments app to new web payments SDK

* Add some comments and minor fixes

* update return values

* add http code

* use production url for web payment sdk

* use different library urls for different environments

* display apple pay button

* address best practice problems

* reuse variable and replace nonce with token

* preventDefault() is removed for button

* add suggested changes from other PRs

* use web sdk styling for google pay and apple pay

* addressed more comments

* address some nits

* remove await from Square.payments()

* added more changes

* remove unwanted file

* rename variable

* fix missed comment

* made some changes to be consistent with other apps

* log error messages in payment-flow-message element

* Apply suggestions from code review

* Hide ACH payment method unless it's enabled

* Fix ACH payment method

* add last style changes

* Upgrade to Ruby 2.7.2

* Update Rails to 6.1 and associated gems

* Initial copying of node payment sample app

* Update Rails payment project to work with Web Payments SDK

* Fix a typo for Turbolinks

* Refactor the python portion of the app to handle POSTs

* Remove unused files

* Fix spelling and clean up logging

* Update PHP to use web payment sdk

* add .env.example file

* small edit in README

* remove extra whitespace

* fix typo

* - remove empty lines
- change capitalization
- simplify server creation

* Address comments

* Uppercase the dynamic html

* Trim idempotency key to 45 chars. Reduce some duplicate code

* Fix bug with client

* Pass errors correctly

* Fix css based on feedback

* Fix errors typo

* update error handling

* Update idempotency key to match other langs

* Minor tweaks

* Fix minor issues

* Switch to using FastAPI

* Fix nits and make js consistent

* Fix imports

* address some comments

* update README for Node.js

* Apply suggestions from code review

Co-authored-by: Dean Papastrat <[email protected]>

* fix a couple of other terminilogy issues

* add space

* Upgrading the csharp sample app to work with the Web Payments SDK (#12)

All Javascript, for the most part, is copied directly from emmac@'s PR.

However, I had to redo a lot of the actual routing. This project uses Razor Pages, which means it doesn't have a good Web API underneath. A more targeted upgrade would add Web API bindings too from ASP.NET.

1. Fetching the location in the index.cs
2. Converting ProcessPayment.cs to work with `fetch`. Note that this is not generally a supported thing in Razor Pages, and usually requires Web API
3. Converted all HTML and Styles

README still needs an update

* Update Rails readme

* Address PR feedback on Rails readme updates

* Update python sample readme

* Change README to support payment SDK

* Fix minor issue

* Apply suggestions from code review for Python readme

* Update connect-examples/v2/java_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/java_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* update php README

* fix typo

* update node order payment README

* Update connect-examples/v2/php_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/php_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/php_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Standardize all payment JS / CSS files

* Update connect-examples/v2/node_orders-payments/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Fix minor html problem

* Improving dotnet readme (#19)

* Improving dotnet readme

Improving the .NET README according to the template done by emmac@ in the nodejs version.

* Update connect-examples/v2/csharp_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/csharp_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/csharp_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

* Update connect-examples/v2/csharp_payment/README.md

Co-authored-by: Dean Papastrat <[email protected]>

Co-authored-by: Dean Papastrat <[email protected]>

* Update all ReadMe files to be consistent and use developer.squareup.com

* Returning the Square Error objects on error (#20)

The Java SDK, when using futures, wraps all exceptions in a `CompletionException`. So to get the root `ApiException`, you must call `exception.getCause()`.

Then, if we return the Square Error objects, the frontend code just works

* Bump SDK versions to 11

Co-authored-by: Emma Chen <[email protected]>
Co-authored-by: Bryan Ashley <[email protected]>
Co-authored-by: Barak Jacob <[email protected]>
Co-authored-by: emmac3 <[email protected]>
Co-authored-by: Wolfgang Schuster <[email protected]>
Co-authored-by: Justin Guze <[email protected]>
  • Loading branch information
7 people authored May 13, 2021
1 parent fd43422 commit 1861420
Show file tree
Hide file tree
Showing 296 changed files with 15,993 additions and 16,707 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Square Connect API and templates to simplify use of our SDKs and APIs.
## Getting help

Complete documentation for Square APIs is available at
[docs.connect.squareup.com].
[developer.squareup.com/docs].

If you have questions about Square Connect API features or implementation,
you can ask for help on [Stack Overflow] or in our [Slack community].
Expand Down Expand Up @@ -53,4 +53,4 @@ application's behavior in the `v1` directory.
[SDK blog post]: https://medium.com/square-corner-blog/announcing-our-new-versions-of-our-client-sdks-1336d26e8099
[Stack Overflow]: https://stackoverflow.com/questions/tagged/square-connect
[Slack community]: https://squ.re/2Hks3YE
[docs.connect.squareup.com]: https://docs.connect.squareup.com
[developer.squareup.com/docs]: https://developer.squareup.com/docs
2 changes: 2 additions & 0 deletions connect-examples/oauth/java/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.classpath
.settings/*
15 changes: 9 additions & 6 deletions connect-examples/oauth/java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This example demonstrates a bare-bones Java implementation of the Square Connect
OAuth flow. The application links merchants to the OAuth Permissions form and
handles the result of the authorization, which is sent to the application's Redirect URL.

For more information, see [OAuth Overview](https://docs.connect.squareup.com/api/oauth#oauth-overview),
For more information, see [OAuth Overview](https://developer.squareup.com/docs/oauth-api/overview),
along with the comments included in `OAuthHandler.java`.

## Setup
Expand Down Expand Up @@ -35,17 +35,20 @@ allowed for `localhost` URLs to simplify the development process.

In order for the sample to work, you must specify the following fields in `OAuthHandler.java`:

* Set the value of `ENVIRONMENT` to one of `Environment.SANDBOX`, `Environment.PRODUCTION` or `Environment.CUSTOM`

* For sandbox testing, set the value of `CONNECT_HOST` to `https://connect.squareupsandbox.com`.
Otherwise, use `https://connect.squareup.com`

* Replace the value of `APPLICATION_ID` with your application's ID, available on your
[application dashboard](https://connect.squareup.com/apps).

* Replace the value of `APPLICATION_SECRET` with your application's secret, also
available on your application dashboard.
* Replace the value of `APPLICATION_SECRET` with the application secret, available from the OAuth tab in the Developer Dashboard

* (OPTIONAL) Set the value of `SCOPES` to the [permission set](../OAuthPermissions.md) you
* (OPTIONAL) Change the values in the list `SCOPES` to the [permission set](../OAuthPermissions.md) you
want to authorize the account to get authorization for. If you do not set this value,
`MERCHANT_PROFILE_READ PAYMENTS_READ SETTLEMENTS_READ BANK_ACCOUNTS_READ` are applied.
* For sandbox testing, set the value of `CONNECT_HOST` to `https://connect.squareupsandbox.com`.
Otherwise, use `https://connect.squareup.com`


### Compile with Maven

Expand Down
20 changes: 10 additions & 10 deletions connect-examples/oauth/java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@
<artifactId>oauthexample</artifactId>
<version>1.5-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.6</version>
</dependency>
<dependencies>
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.11.09</version>
</dependency>

<dependency>
<groupId>com.squareup</groupId>
<artifactId>connect</artifactId>
<version>2.20191120.0</version>
<artifactId>square</artifactId>
<version>10.0.0.20210421</version>
<scope>compile</scope>
</dependency>
</dependencies>

<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@
This sample requires the Unirest Java library. Download instructions are here:
http://unirest.io/java.html
This sample requires Java SE 6 or later.
This sample requires Java SE 8 or later.
*/

package com.squareup.oauthexample;

import com.squareup.connect.ApiException;
import com.squareup.connect.Configuration;
import com.squareup.connect.api.OAuthApi;
import com.squareup.connect.ApiClient;
import com.squareup.connect.models.ObtainTokenRequest;
import com.squareup.connect.models.ObtainTokenResponse;
import com.squareup.square.exceptions.ApiException;
import com.squareup.square.api.OAuthApi;
import com.squareup.square.SquareClient;
import com.squareup.square.models.ObtainTokenRequest;
import com.squareup.square.models.ObtainTokenResponse;
import com.squareup.square.Environment;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
Expand All @@ -35,30 +35,38 @@
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;
import java.util.LinkedList;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import org.json.JSONObject;

public class OAuthHandler {

// Options are Environment.SANDBOX, Environment.PRODUCTION
private static final Environment ENVIRONMENT = Environment.SANDBOX;

// FOR SANDBOX TESTING:
// Your application's ID and secret, available from the OAuth tab in the Developer Dashboard
// If you are testing the OAuth flow in the sandbox, use your sandbox application
// ID and secret. You MUST also set the CONNECT_HOST to "https://connect.squareupsandbox.com"

// Your application's ID and secret, available from your application dashboard.
private static final String APPLICATION_ID = "REPLACE_ME";
private static final String APPLICATION_SECRET = "REPLACE_ME";
// The base URL for every Connect API request
private static final String CONNECT_HOST = "https://connect.squareup.com";
private static final String SCOPES = "REPLACE_ME";
// ID and secret. If you are testing in production, use the production application ID and secret.
private static final String APPLICATION_ID = "REPLACE ME";
private static final String APPLICATION_SECRET = "REPLACE ME";
// Modify this list as needed
private static final String[] SCOPES = { "MERCHANT_PROFILE_READ", "PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS", "PAYMENTS_WRITE", "PAYMENTS_READ" };
// Serves the authorize link

static class AuthorizeHandler implements HttpHandler {

public void handle(HttpExchange t) throws IOException {

String connect_host;
// For testing in sandbox, the base url is "https://connect.squareupsandbox.com",
// and https://connect.squareup.com for production mode
if (ENVIRONMENT == Environment.SANDBOX) {
connect_host = "https://connect.squareupsandbox.com";
} else {
connect_host = "https://connect.squareup.com";
}

// Reject non-GET requests
if (!t.getRequestMethod().equals("GET")) {
t.sendResponseHeaders(405, 0);
Expand All @@ -68,9 +76,9 @@ public void handle(HttpExchange t) throws IOException {

String authorizeURL = String.format(
"<a href=\"%s/oauth2/authorize?client_id=%s&scope=%s\">Click here</a> ",
CONNECT_HOST,
connect_host,
APPLICATION_ID,
SCOPES)
String.join("+", SCOPES))
+ "to authorize the application.";

System.out.println(authorizeURL);
Expand Down Expand Up @@ -101,6 +109,8 @@ public void handle(HttpExchange t) throws IOException {
List<NameValuePair> queryParameters = URLEncodedUtils.parse(requestUri, "UTF-8");
String authorizationCode = null;
for (NameValuePair param : queryParameters) {
System.out.println(param.getName());
System.out.println(param.getValue());
if(param.getName().equals("code")) {
authorizationCode = param.getValue();
break;
Expand All @@ -117,39 +127,51 @@ public void handle(HttpExchange t) throws IOException {
return;
}

ObtainTokenRequest body = new ObtainTokenRequest();
body.setClientId(APPLICATION_ID);
body.setClientSecret(APPLICATION_SECRET);
body.setCode(authorizationCode);
body.setGrantType("authorization_code");

//The default base path is 'https://connect.squareup.com'
//When you are testing OAuth in the Square Sandbox, this resets
//the base path to the Square Sandbox domain
ApiClient apiClient = Configuration.getDefaultApiClient();
apiClient.setBasePath(CONNECT_HOST);

OAuthApi oAuthApi = new OAuthApi();
ObtainTokenResponse response = null;
try {
response = oAuthApi.obtainToken(body);
} catch (ApiException e) {
System.out.print(e.getResponseBody());
t.sendResponseHeaders(405, 0);
t.getResponseBody().close();
return;
}
SquareClient client = new SquareClient.Builder()
.environment(ENVIRONMENT)
.build();

if (response != null) {
System.out.println("Access token: " + response.getAccessToken());
System.out.println("Refresh token: " + response.getRefreshToken());
System.out.println("Authorization succeeded!");
t.sendResponseHeaders(200, 0);
t.getResponseBody().close();
List<String> bodyScopes = new LinkedList<>();
for (String scope : SCOPES) {
bodyScopes.add(scope);
}

t.sendResponseHeaders(200, 0);
t.getResponseBody().close();
// Create obtain token request body
ObtainTokenRequest body = new ObtainTokenRequest.Builder(
APPLICATION_ID,
APPLICATION_SECRET,
"authorization_code")
.code(authorizationCode)
.scopes(bodyScopes)
.build();

OAuthApi oAuthApi = client.getOAuthApi();

// Call obtain token API and print the results on success
// In production, you should never write tokens to the page.
// You should encrypt the tokens and handle them securely.
oAuthApi.obtainTokenAsync(body).thenAccept(result -> {
if (result != null) {
System.out.println("Access token: " + result.getAccessToken());
System.out.println("Refresh token: " + result.getRefreshToken());
System.out.println("Merchant id: " + result.getMerchantId());
System.out.println("Authorization succeeded!");
try {
t.sendResponseHeaders(200, 0);
t.getResponseBody().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).exceptionally(exception -> {
try {
t.sendResponseHeaders(405, 0);
t.getResponseBody().close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
});
}
}

Expand Down
5 changes: 3 additions & 2 deletions connect-examples/oauth/node/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
SQ_SANDBOX_APP_ID=YOUR_SANDBOX_APPLICATION_ID
SQ_SANDBOX_APP_SECRET=YOUR_SANDBOX_APPLICATION_SECRET
SQ_ENVIRONMENT=your-environment
SQ_APPLICATION_ID=your-application-id
SQ_APPLICATION_SECRET=your-application-secret
19 changes: 10 additions & 9 deletions connect-examples/oauth/node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,18 @@ npm install

1. Open the [Developer Dashboard](https://developer.squareup.com/apps).
1. Choose **Open** on the card for an application.
1. At the top of the page, set the dashboard mode to **Sandbox**.
1. At the top of the page, set the dashboard mode to the environment that you want to work with by choosing **Sandbox** or **Production**.
1. Choose **OAuth** in the left navigation pane. The OAuth page is shown.
1. In the **Sandbox Redirect URL** box, enter the URL for the callback you will implement to complete the OAuth flow:
`http://localhost:8000/sandbox_callback`
1. In the **Redirect URL** box, enter the URL for the callback you will implement to complete the OAuth flow:
`http://localhost:8000/callback`

This example uses localhost in the Square Sandbox. You can use HTTP for localhost but an actual web server implementation must use HTTPS.
1. In the **Sandbox Application ID** box, copy the application ID.
1. In the **Sandbox Application Secret** box, choose **Show**, and then copy the application secret.
You can use HTTP for localhost but an actual web server implementation must use HTTPS.
1. In the **Application ID** box, copy the application ID.
1. In the **Application Secret** box, choose **Show**, and then copy the application secret.
1. Click **Save**.
1. In your project directory, create a copy of the `.env.example` file and name it `.env`
1. In the newly created .env file, replace the `YOUR_SANDBOX_APPLICATION_ID` and `YOUR_SANDBOX_APPLICATION_SECRET` placeholders with the Sandbox application ID and Sandbox application secret, respectively.
1. In the newly created .env file, replace the `your-environment` with either `sandbox` or `production`
1. Replace the `your-application-id` and `your-application-secret` placeholders with the Sandbox or Production application ID and application secret, respectively.

Note that OAuth Sandbox credentials begin with a sandbox prefix and that the base URL for calling Sandbox endpoints is https://connect.squareupsandbox.com. When you implement for production, you need production credentials and use https://connect.squareup.com as the base URL.

Expand All @@ -40,15 +41,15 @@ npm install

1. Open the [Developer Dashboard](https://developer.squareup.com/apps).

1. In the Sandbox Test Accounts section, find one test acount and choose Open.
1. For testing in sandbox mode, in the Sandbox Test Accounts section, find one test acount and choose Open. For production mode, open the seller dashboard at https://squareup.com/dashboard/

1. Start the Node server, if it is not running:

```
npm start
```
1. Open http://localhost:8000/sandbox_request_token to start.
1. Open http://localhost:8000/request_token to start.
# License
Copyright 2020 Square, Inc.
Expand Down
Loading

0 comments on commit 1861420

Please sign in to comment.