teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

コードを追記しました。

2020/07/14 13:24

投稿

gatta
gatta

スコア0

title CHANGED
File without changes
body CHANGED
@@ -15,4 +15,163 @@
15
15
  公式のドキュメントでは、localhostにnode.jsをインストールして環境構築をしました。
16
16
  server.jsというファイルに、アクセストークンのコードがあるので、server.jsのファイルをサーバーにアップロードしないといけないと考えていますが、local環境と同様に、他のファイルと同じディレクトリにアップロードしても機能しません。
17
17
 
18
- ローカル環境では動作するものが、本番環境では動作しない原因など、もし見当つく方がいればご回答お願いいたします。
18
+ ローカル環境では動作するものが、本番環境では動作しない原因など、もし見当つく方がいればご回答お願いいたします。
19
+
20
+ ### コード
21
+ ```index.html
22
+ <script type="text/javascript">
23
+ // Create and initialize a payment form object
24
+ const paymentForm = new SqPaymentForm({
25
+ // Initialize the payment form elements
26
+
27
+ //TODO: Replace with your sandbox application ID
28
+ applicationId: "application ID",
29
+ inputClass: 'sq-input',
30
+ autoBuild: false,
31
+ // Customize the CSS for SqPaymentForm iframe elements
32
+ inputStyles: [{
33
+ fontSize: '16px',
34
+ lineHeight: '24px',
35
+ padding: '16px',
36
+ placeholderColor: '#a0a0a0',
37
+ backgroundColor: 'transparent',
38
+ }],
39
+ // Initialize the credit card placeholders
40
+ cardNumber: {
41
+ elementId: 'sq-card-number',
42
+ placeholder: 'Card Number'
43
+ },
44
+ cvv: {
45
+ elementId: 'sq-cvv',
46
+ placeholder: 'CVV'
47
+ },
48
+ expirationDate: {
49
+ elementId: 'sq-expiration-date',
50
+ placeholder: 'MM/YY'
51
+ },
52
+ postalCode: {
53
+ elementId: 'sq-postal-code',
54
+ placeholder: 'Postal'
55
+ },
56
+ // SqPaymentForm callback functions
57
+ callbacks: {
58
+ /*
59
+ * callback function: cardNonceResponseReceived
60
+ * Triggered when: SqPaymentForm completes a card nonce request
61
+ */
62
+ cardNonceResponseReceived: function (errors, nonce, cardData) {
63
+ if (errors) {
64
+ // Log errors from nonce generation to the browser developer console.
65
+ console.error('Encountered errors:');
66
+ errors.forEach(function (error) {
67
+ console.error(' ' + error.message);
68
+ });
69
+ alert('Encountered errors, check browser developer console for more details');
70
+ return;
71
+ }
72
+ alert(`The generated nonce is:\n${nonce}`);
73
+ fetch('process-payment', {
74
+ method: 'POST',
75
+ headers: {
76
+ 'Accept': 'application/json',
77
+ 'Content-Type': 'application/json'
78
+ },
79
+ body: JSON.stringify({
80
+ nonce: nonce
81
+ })
82
+ })
83
+ .catch(err => {
84
+ alert('Network error: ' + err);
85
+ })
86
+ .then(response => {
87
+ if (!response.ok) {
88
+ return response.json().then(errorInfo => Promise.reject(errorInfo)); //UPDATE HERE
89
+ }
90
+ return response.json(); //UPDATE HERE
91
+ })
92
+ .then(data => {
93
+ console.log(data); //UPDATE HERE
94
+ alert('Payment complete successfully!\nCheck browser developer console for more details');
95
+ })
96
+ .catch(err => {
97
+ console.error(err);
98
+ alert('Payment failed to complete!\nCheck browser developer console for more details');
99
+ });
100
+ }
101
+ }
102
+ });
103
+ paymentForm.build();
104
+ // onGetCardNonce is triggered when the "Pay $1.00" button is clicked
105
+ function onGetCardNonce(event) {
106
+ // Don't submit the form until SqPaymentForm returns with a nonce
107
+ event.preventDefault();
108
+ // Request a nonce from the SqPaymentForm object
109
+ paymentForm.requestCardNonce();
110
+ }
111
+ </script>
112
+ ```
113
+
114
+ ```server.js
115
+ const express = require('express');
116
+ const bodyParser = require('body-parser');
117
+ const crypto = require('crypto');
118
+ const squareConnect = require('square-connect');
119
+
120
+ const app = express();
121
+ const port = 3000;
122
+
123
+ // Set the Access Token
124
+ const accessToken = 'Access Token';
125
+
126
+ app.use(bodyParser.json());
127
+ app.use(bodyParser.urlencoded({ extended: false }));
128
+ app.use(express.static(__dirname));
129
+
130
+ // Set Square Connect credentials and environment
131
+ const defaultClient = squareConnect.ApiClient.instance;
132
+
133
+ // Configure OAuth2 access token for authorization: oauth2
134
+ const oauth2 = defaultClient.authentications['oauth2'];
135
+ oauth2.accessToken = accessToken;
136
+
137
+ // Set 'basePath' to switch between sandbox env and production env
138
+ // sandbox: https://connect.squareupsandbox.com
139
+ // production: https://connect.squareup.com
140
+ defaultClient.basePath = 'https://connect.squareup.com';
141
+
142
+ app.post('/process-payment', async (req, res) => {
143
+ const request_params = req.body;
144
+
145
+ // length of idempotency_key should be less than 45
146
+ const idempotency_key = crypto.randomBytes(22).toString('hex');
147
+
148
+ // Charge the customer's card
149
+ const payments_api = new squareConnect.PaymentsApi();
150
+ const request_body = {
151
+ source_id: request_params.nonce,
152
+ amount_money: {
153
+ amount: 100, // $1.00 charge
154
+ currency: 'JPY'
155
+ },
156
+ idempotency_key: idempotency_key
157
+ };
158
+
159
+ try {
160
+ const response = await payments_api.createPayment(request_body);
161
+ res.status(200).json({
162
+ 'title': 'Payment Successful',
163
+ 'result': response
164
+ });
165
+ } catch(error) {
166
+ res.status(500).json({
167
+ 'title': 'Payment Failure',
168
+ 'result': error.response.text
169
+ });
170
+ }
171
+ });
172
+
173
+ app.listen(
174
+ port,
175
+ () => console.log(`listening on - http://localhost:${port}`)
176
+ );
177
+ ```