[JAVA] How to register as a customer with Square using Tomcat

table of contents

--Create Maven project in Eclipse --Register Tomcat (Java Servlet API) and Square in Maven project --Registration page creation (JSP creation) --Create internal processing-1- (communication with JSP) --Create internal processing-2- (Communication with Square)

Create Maven project in Eclipse

Reference site [Eclipse / Tomcat] Servlet + JSP in Maven webapp project

1. Right-click inside the ** Package Explorer ** in Eclipse

スクリーンショット 2020-04-26 4.39.07.png

2. Click ** New ** to ** Maven Project **

スクリーンショット 2020-04-26 4.42.01.png

3. Click ** Next **

-(** Not selected ) Create a simple project (skip archetype selection) -( Select ) Use default workspace location -( not selected ) Add project to working space -( Not set **) Extended

スクリーンショット 2020-04-26 4.44.11.png

4. Select ** maven-archetype-webapp ** ** Next **

5. Enter ** group id ** and ** artifact id ** and click ** Done **

To briefly explain

-** Group id ** is ** Group to which you belong ** -** Artifid id ** is ** project name **

You can think of it. If you don't know what the group id should be, "com. ○○" ← ○ should be the ID that skipped @ on Twitter. For those who want to know more ↓ 「Guide to naming conventions on groupId, artifactId, and version」 "Create a new Maven project in Eclipse (Java)"

スクリーンショット 2020-04-26 4.59.35.png

6. Success if you have a Maven project you created!

スクリーンショット 2020-04-26 5.09.05.png

7. Change the JRE (Java Runtime Environment) version from 1.7 to 11 (8 is acceptable)

  1. Right-click ** JRE system library [JavaSE-1.7] ** in your Maven project

  2. Click ** Properties ** スクリーンショット 2020-04-26 5.13.35.png

  3. Click ** Java SE-1.7 (java7) ** in the execution environment スクリーンショット 2020-04-26 5.16.41.png

  4. Click ** Java SE-11 (java11) ** スクリーンショット 2020-04-26 5.18.32.png

  5. Success if it becomes Java SE-11! スクリーンショット 2020-04-26 5.21.15.png

8. Revive the missing folder!

  1. Right-click ** JRE system library [JavaSE-11] ** in your Maven project

  2. Click ** Build Path ** to ** Build Path Configuration ** スクリーンショット 2020-04-26 5.23.04.png

  3. Select ** Source ** (Top "** Source **" "Project" "Library" "Order and Export" "Module Dependencies")

  4. Select ** Adapt and Close ** スクリーンショット 2020-04-26 5.25.16.png

  5. Success if the missing folder is created! スクリーンショット 2020-04-26 5.28.13.png

Register Tomcat (Java Servlet API) in Maven project

Reference site [Eclipse / Tomcat] Servlet + JSP in Maven webapp project

1. Double-click ** pom.xml ** in the created Maven project

スクリーンショット 2020-04-26 5.36.50.png

2. Copy the latest Java Servlet API xml code

https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api ↓ xml code Ver: 4.0.1 at the time of article creation (April 26, 2020)

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

3. Insert .....

4. Copy the latest Square SDK xml code

https://search.maven.org/search?q=g:com.squareup%20AND%20a:square ↓ xml code Ver: 5.2.2.20200422 at the time of article creation (April 26, 2020)

<dependency>
  <groupId>com.squareup</groupId>
  <artifactId>square</artifactId>
  <version>5.2.2.20200422</version>
</dependency>

5. Insert .....

Inserted between line 36 (</ dependency>) and line 37 (</ dependency>) at the time of article creation ↓ Inserted from the 37th line to the 41st line スクリーンショット 2020-04-26 7.16.33.png

4. Success if added to Maven dependency!

スクリーンショット 2020-04-26 7.19.58.png

Registration page creation (JSP creation)

Thank you for waiting! Now that the preparations are complete, I'm going to program!

1. Right-click "src"-> "main"-> "webapp"-> "WEB-INF" of the created Maven project and click "New"-> "Other"

スクリーンショット 2020-04-26 7.23.59.png

2. Select "JSP File" in "Web" and Next

スクリーンショット 2020-04-26 7.29.08.png

3. Enter the file name and complete

I made it MainServlet. スクリーンショット 2020-04-26 7.31.45.png

4. Display the first name (last name and first name) and the submit button

MainServlet.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!--↓ Site name-->
<title>square customer registration page</title>
</head>
<body>
<!--↓ Destination Java-->
<form action="./Main">
<p>name</p>
<a>sex</a>
<!--↓ Box to put the surname-->
<input type="text" name="name1">
<a>Name</a>
<!--↓ Box to put your name-->
<input type="text" name="name2">
<br>
<!--↓ Send button to Jsp-->
<input type="submit" value="Send">
</form>
</body>
</html>

Create internal processing-1- (communication with JSP)

1. Right-click "src / main / java" of the created Maven project and click "New"-> "Other"

2. Select "Servlet" of "Web" ** Next **

スクリーンショット 2020-04-26 7.42.36.png

3. Enter the class name and complete

I get angry when I do this in my actual work ... スクリーンショット 2020-04-26 7.44.33.png

4. If created, it will be like this ↓

Be careful not to be killed by Ahagon. Headshot attention スクリーンショット 2020-04-26 7.46.23.png

5. First, write a program that will be transferred from java to jsp

Changed (added) location ↓

Main.java


//Forward to JSP (specify file location)
String view = "/WEB-INF/MainServlet.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);

All ↓

Main.java



import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Main
 */
public class Main extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Main() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());

		//Forward to JSP (specify file location)
		String view = "/WEB-INF/MainServlet.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

6. Try running it and if the content described in Jsp is displayed, it's OK!

↓ Success! スクリーンショット 2020-04-26 7.59.08.png

↓ If the characters are garbled スクリーンショット 2020-04-26 8.01.12.png

Main.java


response.getWriter().append("Served at: ").append(request.getContextPath());

↑ Let's comment this out!

7. Let's receive the characters entered in Jsp in Java

Description: Put the characters in the Jsp "id = name1" textbox into "String name1"

Main.java


//Received from jsp
String name1 = request.getParameter("name1");//name(sex)
String name2 = request.getParameter("name2");//name(Name)

7. If it is null, do not execute it

Description: Run if name1 and name2 are not null

Main.java


if (name1 != null || name2 != null) {
}

8. I get an error if it is blank

Description: Run if name1 and name2 are not blank. If it is blank, an error will be issued.

Main.java


if (!name1.equals("") && !name2.equals("")) {
}else{
System.out.println("Please enter your gender and name");
}

9. I'll send it to Square.java

Description: Send sex and name to Square.java

Main.java


//Send to square
Square square = new Square();
square.main(name1, name2);

10. All described so far ↓

Main.java


import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import square.SquareMain;

/**
 * Servlet implementation class Main
 */
public class Main extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Main() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());
		//Received from jsp
		String name1 = request.getParameter("name1");//name(sex)
		String name2 = request.getParameter("name2");//name(Name)
		if (name1 != null || name2 != null) {
			if (!name1.equals("") && !name2.equals("")) {
				//Send to square
				Square square = new Square();
				square.main(name1, name2);
				System.out.println("Done:");
			} else {
				System.out.println("Please enter your gender and name");
			}
		}
		//Forward to JSP (specify file location)
		String view = "/WEB-INF/MainServlet.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Create internal processing-2- (communication with Square)

Referenced site "Java client library for the Square API"

1. Right-click "src / main / java"-> "Default Package" of the created Maven project and click "New"-> "Class".

スクリーンショット 2020-04-26 8.15.47.png

2. Enter your name and click Finish

Also pay attention to Eclipse ... スクリーンショット 2020-04-26 8.19.03.png

3. First, enter the access token

↓ For testing

Square.java


SquareClient client = new SquareClient.Builder()
            .environment(Environment.SANDBOX)
            .accessToken("YOUR_SANDBOX_ACCESS_TOKEN")
            .build();

↓ For production

Square.java


SquareClient client = new SquareClient.Builder()
    .environment(Environment.PRODUCTION)
    .accessToken("ACCESS TOKEN HERE")
    .build();

4.CustomersAPI Details: "Customers"

Square.java


CustomersApi api = client.getCustomersApi();

5. Make a shape to send

Details: "Create Customer"

Square.java


CreateCustomerRequest createCustomerRequest = new CreateCustomerRequest.Builder()
				.idempotencyKey("unique_idempotency_key")
				.givenName(name1)//sex
				.familyName(name2)//Name
				.address(null)//Not used this time
				.build();

6. I'll send it!

Square.java


try {
			CreateCustomerResponse response = api.createCustomer(createCustomerRequest);
		} catch (ApiException e) {
			List<Error> errors = e.getErrors();
			int statusCode = e.getResponseCode();
			HttpContext httpContext = e.getHttpContext();

			// Your error handling code
			System.err.println("ApiException error when calling API");
			e.printStackTrace();
		} catch (IOException e) {
			// Your error handling code
			System.err.println("IOException error when calling API");
			e.printStackTrace();
		}

7. All of Square.java

Square.java


import java.io.IOException;
import java.util.List;

import com.squareup.square.Environment;
import com.squareup.square.SquareClient;
import com.squareup.square.api.CustomersApi;
import com.squareup.square.exceptions.ApiException;
import com.squareup.square.http.client.HttpContext;
import com.squareup.square.models.CreateCustomerRequest;
import com.squareup.square.models.CreateCustomerResponse;
import com.squareup.square.models.Error;

public class Square {
	public void main(String name1, String name2) {
		SquareClient client = new SquareClient.Builder()
				.environment(Environment.PRODUCTION)
				.accessToken("ACCESS TOKEN HERE")
				.build();

		CustomersApi api = client.getCustomersApi();
		CreateCustomerRequest createCustomerRequest = new CreateCustomerRequest.Builder()
				.idempotencyKey("unique_idempotency_key")
				.givenName(name1)//sex
				.familyName(name2)//Name
				.address(null)//Not used this time
				.build();

		try {
			CreateCustomerResponse response = api.createCustomer(createCustomerRequest);
		} catch (ApiException e) {
			List<Error> errors = e.getErrors();
			int statusCode = e.getResponseCode();
			HttpContext httpContext = e.getHttpContext();

			// Your error handling code
			System.err.println("ApiException error when calling API");
			e.printStackTrace();
		} catch (IOException e) {
			// Your error handling code
			System.err.println("IOException error when calling API");
			e.printStackTrace();
		}

	}
}

Complete!

スクリーンショット 2020-04-26 4.23.37.png スクリーンショット 2020-04-26 4.23.29.png

I found that it would be difficult to read the article if I wrote the article as if I were teaching it because it was a video.

I will be careful from the next time

PS insertion is erotic, isn't it?

Recommended Posts

How to register as a customer with Square using Tomcat
How to request a CSV file as JSON with jMeter
How to execute a contract using web3j
How to sort a List using Comparator
[Rails] How to create a graph using lazy_high_charts
How to delete a controller etc. using a command
[Ethereum] How to execute a contract using web3j-Part 2-
How to generate a primary key using @GeneratedValue
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
How to make a factory with a model with polymorphic association
How to run the SpringBoot app as a service
How to switch Tomcat context.xml with WTP in Eclipse
How to delete a new_record object built with Rails
How to manually generate a JWT with Rails Knock
[How to insert a video in haml with Rails]
How to download a file (Servlet, HTML, Apache, Tomcat)
How to convert A to a and a to A using AND and OR in Java
How to start tomcat local server without using eclipse
[Java] How to start a new line with StringBuilder
[Rails] How to install a decorator using gem draper
How to take a screenshot with the Android Studio emulator
How to set environment variables when using Payjp with Rails
How to divide a two-dimensional array into four with ruby
How to use a foreign key with FactoryBot ~ Another solution
Learning Ruby with AtCoder 13 How to make a two-dimensional array
How to number (number) with html.erb
How to test a private method with RSpec for yourself
How to update with activerecord-import
How to move another class with a button action of another class.
How to output array values without using a for statement
How to make an app using Tensorflow with Android Studio
Mapping to a class with a value object in How to MyBatis
How to develop and register a Sota app in Java
How to join a table without using DBFlute and sql
How to install GNOME as a desktop environment on CentOS 7
How to get started with JDBC using PostgresSQL on MacOS
How to insert a video
How to set up a proxy with authentication in Feign
How to create a method
How to authorize using graphql-ruby
How to create a jar file or war file using the jar command
How to deal with 405 Method Not Allowed error in Tomcat + JSP
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
How to make a jar file with no dependencies in Maven
How to run a mock server on Swagger-ui using stoplight/prism (using AWS/EC2/Docker)
[Rails 6] How to create a dynamic form input screen using cocoon
How to read a file and treat it as standard input
How to run a job with docker login in AWS batch
How to rename a model with foreign key constraints in Rails
How to output a list of strings in JSF as comma-separated strings
How to open a script file from Ubuntu with VS code
How to build a little tricky with dynamic SQL query generation
How to make a groundbreaking diamond using Java for statement wwww
How to use MinIO with the same function as S3 Use docker-compose
How to scroll horizontally with ScrollView
How to get started with slim
Build a Tomcat 8.5 environment with Pleiades 4.8
Create a tomcat project using Eclipse
How to make a Java container
How to enclose any character with "~"