Skip to content

Commit

Permalink
Merge pull request square#146 from square/xiao/update-to-payments-api
Browse files Browse the repository at this point in the history
update to payments api and v2 sandbox
  • Loading branch information
hukid authored Aug 15, 2019
2 parents 29ea0a9 + 2822272 commit 08681e2
Show file tree
Hide file tree
Showing 1,011 changed files with 102,758 additions and 333 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,31 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Square.Connect.Api;
using Square.Connect.Client;
using Square.Connect.Model;

namespace csharp_checkout.Pages
{
public class CheckoutModel : PageModel
{
private readonly string locationId;
private readonly Configuration configuration;

public CheckoutModel(IConfiguration configuration)
{
locationId = configuration["AppSettings:LocationId"];
// Set 'basePath' to switch between sandbox env and production env
// sandbox: https://connect.squareupsandbox.com
// production: https://connect.squareup.com
string basePath = configuration["AppSettings:Environment"] == "sandbox" ?
"https://connect.squareupsandbox.com" : "https://connect.squareup.com";
this.configuration = new Configuration(new ApiClient(basePath));
this.configuration.AccessToken = configuration["AppSettings:AccessToken"];
}

public IActionResult OnPost()
{
CheckoutApi checkoutApi = new CheckoutApi();
CheckoutApi checkoutApi = new CheckoutApi(configuration: this.configuration);
int amount = (int)float.Parse(Request.Form["amount"]) * 100;

try
Expand Down
10 changes: 4 additions & 6 deletions connect-examples/v2/csharp_checkout/csharp_checkout/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddRazorPagesOptions(o =>
{
// This is for Sample only, remove this to handle the post request in secure way
o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
.AddRazorPagesOptions(o =>
{
// This is for Sample only, remove this to handle the post request in secure way
o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
}

Expand All @@ -45,8 +45,6 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseStaticFiles();

app.UseMvc();

Square.Connect.Client.Configuration.Default.AccessToken = this.Configuration["AppSettings:AccessToken"];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
}
},
"AppSettings": {
"Environment": "production",
"AccessToken": "prod_access_token",
"LocationId": "prod_location_id"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
}
},
"AppSettings": {
"Environment": "sandbox",
"AccessToken": "sandbox_access_token",
"LocationId": "sandbox_location_id"
}
Expand Down
26 changes: 16 additions & 10 deletions connect-examples/v2/csharp_payment/Pages/ProcessPayment.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace sqRazorSample.Pages
{
public class ProcessPaymentModel : PageModel
{
private readonly string LocationId;
readonly Configuration configuration;

public string ResultMessage
{
Expand All @@ -18,13 +18,19 @@ public string ResultMessage
}

public ProcessPaymentModel(IConfiguration configuration) {
this.LocationId = configuration["AppSettings:LocationId"];
// Set 'basePath' to switch between sandbox env and production env
// sandbox: https://connect.squareupsandbox.com
// production: https://connect.squareup.com
string basePath = configuration["AppSettings:Environment"] == "sandbox" ?
"https://connect.squareupsandbox.com" : "https://connect.squareup.com";
this.configuration = new Configuration(new ApiClient(basePath));
this.configuration.AccessToken = configuration["AppSettings:AccessToken"];
}

public void OnPost()
{
string nonce = Request.Form["nonce"];
TransactionsApi transactionsApi = new TransactionsApi();
PaymentsApi paymentsApi = new PaymentsApi(configuration: this.configuration);
// Every payment you process with the SDK must have a unique idempotency key.
// If you're unsure whether a particular payment succeeded, you can reattempt
// it with the same idempotency key without worrying about double charging
Expand All @@ -34,17 +40,17 @@ public void OnPost()
// Monetary amounts are specified in the smallest unit of the applicable currency.
// This amount is in cents. It's also hard-coded for $1.00,
// which isn't very useful.
Money amount = new Money(100, Money.CurrencyEnum.USD);
Money amount = new Money(100, "USD");

// To learn more about splitting transactions with additional recipients,
// see the Transactions API documentation on our [developer site]
// (https://docs.connect.squareup.com/payments/transactions/overview#mpt-overview).
ChargeRequest body = new ChargeRequest(AmountMoney: amount, IdempotencyKey: uuid, CardNonce: nonce);
// To learn more about splitting payments with additional recipients,
// see the Payments API documentation on our [developer site]
// (https://developer.squareup.com/docs/payments-api/overview).
CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest(AmountMoney: amount, IdempotencyKey: uuid, SourceId: nonce);

try
{
var response = transactionsApi.Charge(LocationId, body);
this.ResultMessage = "Transaction complete! " + response.ToJson();
var response = paymentsApi.CreatePayment(createPaymentRequest);
this.ResultMessage = "Payment complete! " + response.ToJson();
}
catch (ApiException e)
{
Expand Down
2 changes: 1 addition & 1 deletion connect-examples/v2/csharp_payment/Pages/index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
}
@section Scripts {
<!-- link to the SqPaymentForm library -->
<script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
<script type="text/javascript" src="@Model.PaymentFormUrl"></script>
<script type="text/javascript">
window.applicationId = "@Model.ApplicationId";
window.locationId = "@Model.LocationId";
Expand Down
3 changes: 3 additions & 0 deletions connect-examples/v2/csharp_payment/Pages/index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace sqRazorSample.Pages
{
public class IndexModel : PageModel
{
public string PaymentFormUrl { get; set; }
public string ApplicationId { get; set; }
public string LocationId { get; set; }

Expand All @@ -16,6 +17,8 @@ public IndexModel(IConfiguration configuration)
{
this.ApplicationId = configuration["AppSettings:ApplicationId"];
this.LocationId = configuration["AppSettings:LocationId"];
this.PaymentFormUrl = configuration["AppSettings:Environment"] == "sandbox" ?
"https://js.squareupsandbox.com/v2/paymentform" : "https://js.squareup.com/v2/paymentform" ;
}
}
}
16 changes: 8 additions & 8 deletions connect-examples/v2/csharp_payment/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ After cloning this sample project to local, open command line tool, and from the

### Provide required credentials

Open `./appsettings.json` and replace "AccessToken", "LocationId" and "ApplicationId" with the ids you get from your square application created in [Square Developer Portal](https://connect.squareup.com/apps).
Open `./appsettings.json`, specify "Environment" and replace "AccessToken", "LocationId" and "ApplicationId" with the ids you get from your square application created in [Square Developer Portal](https://connect.squareup.com/apps).
<b>WARNING</b>: never upload `appsettings.json` with your credentials/access_token.

If you're just testing things out, it's recommended that you use your _sandbox_
Expand Down Expand Up @@ -116,17 +116,17 @@ All the remaining actions take place in the **ProcessPayment.cshtml.cs**. This
public void OnPost()
{
string nonce = Request.Form["nonce"];
TransactionsApi transactionsApi = new TransactionsApi();
string uuid = NewIdempotencyKey();
Money amount = new Money(100, Money.CurrencyEnum.USD);
IPaymentsApi paymentsApi = new PaymentsApi(this.BasePath);
paymentsApi.Configuration.AccessToken = this.AccessToken;
ChargeRequest body = new ChargeRequest(AmountMoney: amount, IdempotencyKey: uuid, CardNonce: nonce);
string uuid = NewIdempotencyKey();
Money amount = new Money(100, "USD");
CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest(AmountMoney: amount, IdempotencyKey: uuid, SourceId: nonce);
try
{
var response = transactionsApi.Charge(LocationId, body);
this.ResultMessage = "Transaction complete! " + response.ToJson();
var response = paymentsApi.CreatePayment(createPaymentRequest);
this.ResultMessage = "Payment complete! " + response.ToJson();
}
catch (ApiException e)
{
Expand Down
2 changes: 0 additions & 2 deletions connect-examples/v2/csharp_payment/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseStaticFiles();

app.UseMvc();

Square.Connect.Client.Configuration.Default.AccessToken = this.Configuration["AppSettings:AccessToken"];
}
}
}
5 changes: 3 additions & 2 deletions connect-examples/v2/csharp_payment/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
}
},
"AppSettings": {
"Environment": "sandbox or production",
"ApplicationId": "your-application-id",
"AccessToken": "your-access-token",
"LocationId": "your-location-id",
"ApplicationId": "your-application-id"
"LocationId": "your-location-id"
}
}
4 changes: 2 additions & 2 deletions connect-examples/v2/csharp_payment/sqRazorSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="RestSharp" Version="106.2.2" />
<PackageReference Include="Square.Connect" Version="2.10.0.294" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
<PackageReference Include="RestSharp" Version="106.3.1" />
<PackageReference Include="Square.Connect" Version="2.22.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" />
Expand Down
32 changes: 17 additions & 15 deletions connect-examples/v2/java_payment/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ sensitive and must remain private.
To get up and running, first clone the repo to your local computer.
Then open a command line terminal and run the following command:

```
```bash
cd <example repo root>/connect-examples/v2/square-connect-sdk/java
mvn install -DskipTests
cd <example repo root>/connect-examples/v2/java_payment
# The following command sets environment variables and starts the application locally:
SQUARE_APP_ID=replace_me SQUARE_ACCESS_TOKEN=replace_me SQUARE_LOCATION_ID=replace_me mvn spring-boot:run
SQUARE_ENV=<sandbox or production> SQUARE_APP_ID=replace_me SQUARE_ACCESS_TOKEN=replace_me SQUARE_LOCATION_ID=replace_me mvn spring-boot:run
```

After running the above command, you can open a browser and go to
Expand All @@ -58,7 +61,7 @@ called the **SqPaymentForm**) you accept payment source information and generate
<img src="./PaymentFormExampleJava.png" width="300"/>

2. Charge the payment source using the nonce - Using a server-side component, that uses the Connect V2
**Transaction** API, you charge the payment source using the nonce.
**Payments** API, you charge the payment source using the nonce.
s
The following sections describe how the Java sample implements these steps.

Expand Down Expand Up @@ -98,22 +101,21 @@ After the buyer enters their information in the form and clicks **Pay $1 Now**,
This invokes the form action **charge**, described in next step.

### Step 2: Charge the Payment Source Using the Nonce
All the remaining actions take place in the **Main.java**. This server-side component uses the Square Java SDK library to call the Connect V2 **Transaction** API to charge the payment source using the nonce as shown in the following code fragment.
All the remaining actions take place in the **Main.java**. This server-side component uses the Square Java SDK library to call the Connect V2 **Payments** API to charge the payment source using the nonce as shown in the following code fragment.
```java
String charge(@ModelAttribute NonceForm form, Map<String, Object> model) throws ApiException {
ChargeRequest chargeRequest = new ChargeRequest()
.idempotencyKey(UUID.randomUUID().toString())
.amountMoney(new Money().amount(1_00L).currency(CurrencyEnum.USD))
.cardNonce(form.getNonce())
.note("From a Square sample Java app");
CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest()
.idempotencyKey(UUID.randomUUID().toString())
.amountMoney(new Money().amount(1_00L).currency("USD"))
.sourceId(form.getNonce())
.note("From a Square sample Java app");
TransactionsApi transactionsApi = new TransactionsApi();
transactionsApi.setApiClient(squareClient);
PaymentsApi paymentsApi = new PaymentsApi(squareClient);
ChargeResponse response = transactionsApi.charge(squareLocationId, chargeRequest);
CreatePaymentResponse response = paymentsApi.createPayment(createPaymentRequest);
model.put("transaction", response.getTransaction());
model.put("payment", response.getPayment());
return "charge";
}
return "charge";
}
```
2 changes: 1 addition & 1 deletion connect-examples/v2/java_payment/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<dependency>
<groupId>com.squareup</groupId>
<artifactId>connect</artifactId>
<version>2.20180712.1</version>
<version>2.20190814.0</version>
<scope>compile</scope>
</dependency>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@

import com.squareup.connect.ApiClient;
import com.squareup.connect.ApiException;
import com.squareup.connect.Configuration;
import com.squareup.connect.api.LocationsApi;
import com.squareup.connect.api.TransactionsApi;
import com.squareup.connect.api.PaymentsApi;
import com.squareup.connect.auth.OAuth;
import com.squareup.connect.models.*;
import com.squareup.connect.models.Location.CapabilitiesEnum;
import com.squareup.connect.models.Money.CurrencyEnum;

import java.util.Currency;
import java.util.Map;
import java.util.UUID;
import org.springframework.boot.SpringApplication;
Expand All @@ -49,18 +47,28 @@ public class Main {
// This must be set in order for the application to start.
private static final String SQUARE_LOCATION_ID_ENV_VAR = "SQUARE_LOCATION_ID";

private final ApiClient squareClient = Configuration.getDefaultApiClient();
// The environment variable indicate the square environment - sandbox or production.
// This must be set in order for the application to start.
private static final String SQUARE_ENV_ENV_VAR = "SQUARE_ENV";

private final ApiClient squareClient;
private final String squareLocationId;
private final String squareAppId;
private final String squareEnvironment;

public Main() throws ApiException {
squareEnvironment = mustLoadEnvironmentVariable(SQUARE_ENV_ENV_VAR);
squareAppId = mustLoadEnvironmentVariable(SQUARE_APP_ID_ENV_VAR);
squareLocationId = mustLoadEnvironmentVariable(SQUARE_LOCATION_ID_ENV_VAR);

squareClient = new ApiClient();
// Configure OAuth2 access token for authorization: oauth2
OAuth oauth2 = (OAuth) squareClient.getAuthentication("oauth2");
oauth2.setAccessToken(mustLoadEnvironmentVariable(SQUARE_ACCESS_TOKEN_ENV_VAR));

squareLocationId = mustLoadEnvironmentVariable(SQUARE_LOCATION_ID_ENV_VAR);
// Set 'basePath' to switch between sandbox env and production env
// sandbox: https://connect.squareupsandbox.com
// production: https://connect.squareup.com
squareClient.setBasePath(squareEnvironment.equals("sandbox") ? "https://connect.squareupsandbox.com" : "https://connect.squareup.com");
}

public static void main(String[] args) throws Exception {
Expand All @@ -79,6 +87,8 @@ private String mustLoadEnvironmentVariable(String name) {

@RequestMapping("/")
String index(Map<String, Object> model) throws ApiException {
model.put("paymentFormUrl", squareEnvironment.equals("sandbox") ?
"https://js.squareupsandbox.com/v2/paymentform" : "https://js.squareup.com/v2/paymentform");
model.put("locationId", squareLocationId);
model.put("appId", squareAppId);

Expand All @@ -87,21 +97,20 @@ String index(Map<String, Object> model) throws ApiException {

@PostMapping("/charge")
String charge(@ModelAttribute NonceForm form, Map<String, Object> model) throws ApiException {
// To learn more about splitting transactions with additional recipients,
// see the Transactions API documentation on our [developer site]
// (https://docs.connect.squareup.com/payments/transactions/overview#mpt-overview).
ChargeRequest chargeRequest = new ChargeRequest()
// To learn more about splitting payments with additional recipients,
// see the Payments API documentation on our [developer site]
// (https://developer.squareup.com/docs/payments-api/overview).
CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest()
.idempotencyKey(UUID.randomUUID().toString())
.amountMoney(new Money().amount(1_00L).currency(CurrencyEnum.USD))
.cardNonce(form.getNonce())
.amountMoney(new Money().amount(1_00L).currency("USD"))
.sourceId(form.getNonce())
.note("From a Square sample Java app");

TransactionsApi transactionsApi = new TransactionsApi();
transactionsApi.setApiClient(squareClient);
PaymentsApi paymentsApi = new PaymentsApi(squareClient);

ChargeResponse response = transactionsApi.charge(squareLocationId, chargeRequest);
CreatePaymentResponse response = paymentsApi.createPayment(createPaymentRequest);

model.put("transaction", response.getTransaction());
model.put("payment", response.getPayment());

return "charge";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

<body>
<p>
<span th:text="${transaction}"></span>
<span th:text="${payment}"></span>
</p>
</body>

Expand Down
Loading

0 comments on commit 08681e2

Please sign in to comment.