# Payment

## SecurePay

<mark style="color:green;">`POST`</mark> `https://api.2pay.co/online/v1/secure-pay`

This API provides a fast and secure way for order payments

#### Request Body

| Name                                          | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| merchantNo<mark style="color:red;">\*</mark>  | String | ID of a merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| verifySign <mark style="color:red;">\*</mark> | String | The merchants should verify the signature to ensure the response is from the server and not modified by any others.                                                                                                                                                                                                                                                                                                                                   |
| currency<mark style="color:red;">\*</mark>    | String | Currency supported by 2Pay is **"USD"**.                                                                                                                                                                                                                                                                                                                                                                                                              |
| amount <mark style="color:red;">\*</mark>     | Number | Amount of a transaction.                                                                                                                                                                                                                                                                                                                                                                                                                              |
| vendor<mark style="color:red;">\*</mark>      | String | <p>Payment methods.</p><p>Potential values："<strong>alipay</strong>", "<strong>wechatpay</strong>", "<strong>paypal</strong>", "<strong>venmo</strong>", "<strong>unionpay</strong>", "<strong>creditcard</strong>", "<strong>truemoney</strong>", "<strong>alipay\_hk</strong>", "<strong>tng</strong>", "<strong>gcash</strong>", "<strong>dana</strong>", "<strong>kakaopay</strong>", "<strong>bkash</strong>", "<strong>easypaisa</strong>".</p> |
| reference<mark style="color:red;">\*</mark>   | String | The reference number of a trasaction in the merchant services system.                                                                                                                                                                                                                                                                                                                                                                                 |
| terminal<mark style="color:red;">\*</mark>    | String | Potential values: **"ONLINE"**, **"WAP"**, **"YIP"**，**"MWEB"**(for Wechat H5 payment).                                                                                                                                                                                                                                                                                                                                                               |
| ipnUrl<mark style="color:red;">\*</mark>      | String | <p>Asynchronous callback Url. </p><p>The IPN Url should be secure and reliable.</p>                                                                                                                                                                                                                                                                                                                                                                   |
| callbackUrl<mark style="color:red;">\*</mark> | String | <p>Synchronously return a http url via a callback url. </p><p>This callback url is used to recieve notifications and messages of an event.</p><p>The callback url should follow the macro rules. For example, xxxcallback\_url?trans\_no={amount}\&amount={amount}. 2Pay will automatically replace the values of parameters in curly brackets ("{ }").</p>                                                                                           |
| description                                   | String | Description of a transaction on a bill / invoice.                                                                                                                                                                                                                                                                                                                                                                                                     |
| timeout                                       | String | <p>The interval for a transaction to be expired. (measured in minutes)</p><p>Default value: 120</p>                                                                                                                                                                                                                                                                                                                                                   |
| goodsInfo                                     | String | <p>The product information (stores in an array) written in JSON format. </p><p>For example, \[{"goods\_name":"name1", "quantity":"quantity1"}, {"goods\_name":"name2", "quantity":"quantity2"}]</p><p>Do not support special characters. </p>                                                                                                                                                                                                         |

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "ret_code": "000100",
    "ret_msg": "prepay success",
    "result": {
        "amount": "1",
        "currency": "USD",
        "transactionNo": "558901a15-1c3f-427a-b838-83049b4efc47",
        "reference": "b6984c78-w8201-kqcak81jk",
        "cashierUrl": "https://api.2pay.co/app/url",
        "settleCurrency": "USD"
    }
}
```

{% endtab %}

{% tab title="400: Bad Request " %}

```javascript
{
    "ret_code": "000000",
    "ret_msg": ""
}
```

{% endtab %}
{% endtabs %}

### Response

| **Parameter** | **Type** | **Description**                            |
| ------------- | -------- | ------------------------------------------ |
| result        | Object   | [#result-object](#result-object "mention") |
| ret\_msg      | String   | Return response message.                   |
| ret\_code     | String   | Return response status code.               |

### Result Object

| **Parameter**  | **Type** | **Description**                                                                                                                     |
| -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| amount         | String   | <p>The amount of a transaction. </p><p>This parameter will be returned when the transaction currency is <strong>"USD"</strong>.</p> |
| currency       | String   | <p>Transaction currency.</p><p>Currency supported by 2Pay is: <strong>"USD"</strong>.</p>                                           |
| transactionNo  | String   | The transaction ID of 2Pay system.                                                                                                  |
| reference      | String   | The reference number of a trasaction in the merchant services system.                                                               |
| cashierUrl     | String   | The Url using by cashiers.                                                                                                          |
| settleCurrency | String   | <p>Currency code from ISO 4217. </p><p>Potential value: <strong>"USD"</strong>.</p>                                                 |

{% tabs %}
{% tab title="cURL" %}

```shell
curl --location --request POST 'https://api.2pay.co/online/v1/secure-pay' \
--header 'Content-Type: application/json' \
--data-raw '{
    "merchantNo": "M165937487",
    "vendor": "alipay",
    "reference": "b6984c78-8201-kqcak81jk",
    "amount": "1",
    "currency": "USD",
    "description": "your description",
    "terminal": "IOS",
    "callbackUrl": "https://{paidUrl}",
    "ipnUrl": "https://alipay.com/notify",
    "goodsInfo": "[{'\''goods_name'\'':'\''Plan'\'','\''quantity'\'':'\''1'\''}]",
    "timeout": "120",
    "verifySign": "{{verifySign}}"
}'
```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
import request from 'request'
import CryptoJS from 'crypto-js'
const token = 'yjmsy9vwjkajsnwqqt4psc2o8y3rr5q'
const baseUrl = 'https://api.2pay.co'
const params = {
  merchantNo: 'M16593129121867',
  vendor: 'alipay',
  reference: '2991223db-4cdc-ba0f-7e15bfc9beb2',
  amount: '1.0000',
  currency: 'USD',
  description: 'Contact mail:',
  terminal: 'ONLINE',
  callbackUrl: 'https://pay.domain.com/paid.html',
  ipnUrl: 'https://pay.domain.com/2pay/notify',
  goodsInfo: '',
  timeout: '120'
}


function buildAndSignParams(params) {
  let sortArray = [];
  Object.keys(params).sort().forEach(k => {
      if (k == 'verifySign') {
          return
      }
    if(params[k] || params[k] === false) {
      sortArray.push(`${k}=${params[k]}`)
    }
  });
  sortArray.push(CryptoJS.MD5(token).toString());
  console.log('MD5 Token', CryptoJS.MD5(token).toString())
  const tempStr = sortArray.join('&');
  console.log('temStr:', tempStr)
  const verifySign = CryptoJS.MD5(tempStr).toString();
  console.log('verifySign', verifySign)
  return {
    ...params,
    verifySign
  }

}

const json = await request.post({
  url: BaseUrl + 'online/v1/secure-pay',
  form: buildAndSignParams(params)
});
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
    function securepay()
    {
        $url = 'https://api.2pay.co/online/v1/secure-pay';
        $token = '5cbfb079f15b150122261c8537086d77a';
        $params = [
              merchantNo => 'M16593129121867',
              vendor => 'alipay',
              reference => '2991223db-4cdc-ba0f-7e15bfc9beb2',
              amount => '1.0000',
              currency => 'USD',
              description => 'Contact mail:',
              terminal => 'ONLINE',
              callbackUrl => 'https://pay.domain.com/paid.html',
              ipnUrl => 'https://pay.domain.com/2pay/notify',
              goodsInfo => '',
              timeout => '120'
        ];
        ksort($params, SORT_STRING);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $params['verifySign'] = md5($str . md5($token));
        echo 'verifySign:', $params['verifySign'];
        echo "\n";
        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params),
        ));
        $result = curl_exec($ch);
        curl_exec($ch);
        echo $result;
        echo "\n";
        return json_decode($result, true);
    }
    securepay();
?>
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	pay "github.com/2pay-co/golang-sdk"
	"github.com/gogf/gf/v2/os/gtime"
)

func main() {

	t := pay.New("MerchantNo", "Token")
	param := pay.SecurePay{
		Currency:    "USD",
		Amount:      "10",
		Vendor:      "alipay",
		Reference:   gtime.Datetime(),
		Terminal:    "ONLINE",
		IpnURL:      "https://google.com",
		CallbackURL: "https://google.com",
		Note:        "test order",
		Description: "test order",
		Timeout:     "120",
		GoodsInfo: []pay.GoodsInfo{
			{
				"test goods 1", "1",
			},
			{
				"test goods 2", "1",
			},
		},
	}

	resp, err := t.SecurePay(&param)
	fmt.Println(resp, err)
}
```

{% endtab %}

{% tab title="Java" %}

```java
TwoPayConfig config = new TwoPayConfig();
config.setEnv(EnviromentEnums.SANDBOX.getValue())
        .setMerchantNo("M1659370481867")
        .setToken("yjmsy9v5o2kam2sjsct4psc2o8y3rr5q");
TwoPayClient client = new TwoPayV100Client(InitTwoPayConfig.initMerchantConfig()); 		

TwoPayClient client = new TwoPayV100Client(InitTwoPayConfig.initMerchantConfig());
		
		JSONArray goods = new JSONArray();
		JSONObject item = new JSONObject();
		item.put("goods_name","name1");
		item.put("quantity", "1");
		goods.add(item);
		OnlineSecurepayRequest request = new OnlineSecurepayRequest();
		request.setAmount("0.01")
				.setCurrency("USD")
				.setVendor("alipay")
				.setTerminal("WAP")
				.setReference(System.nanoTime()+"")
				.setIpnUrl("http://xxxxxx/ttest/test")
				.setCallbackUrl("http://xxxxx/ttest/test")
				.setDescription("testDescription")
				.setGoodsInfo(goods.toString());
		OnlineSecurepayResponse response = client.execute(request);
		System.out.println(JSONObject.fromObject(response));

		RefundRequest rfd = new RefundRequest();
		rfd.setamount("1000000");
		rfd.setReference("6ce3653f-5365-4bcd-b596-e9007b683bec");
		RefundResponse rfs = client.execute(rfd);
		System.out.println(JSONObject.fromObject(rfs))
```

{% endtab %}
{% endtabs %}
