# Apple Pay & Google Pay

## 一、Checkout页面集成 <a href="#xeoq5" id="xeoq5"></a>

Checkout页面集成是Apple Pay 和 Google Pay最简单的集成方式，Asiabill托管支付页面会向用户提供Apple pay/Google pay的支付按钮选项。

如果商家已经对接过跳转支付模式，不需要进行二次开发，申请开通后即可使用；

<figure><img src="/files/HJCFd3L1OGj3JjP3eyGR" alt=""><figcaption></figcaption></figure>

### 1.checkout流程图 <a href="#c0qo5" id="c0qo5"></a>

<figure><img src="/files/Y3RNnpmkqybiBVp0uqFD" alt=""><figcaption></figcaption></figure>

### 2.商户开通步骤 <a href="#xrneh" id="xrneh"></a>

联系Asiabill客服进行开通

## 二、商户自主集成流程 <a href="#jbwtg" id="jbwtg"></a>

自主集成流程可自定义程度高，需要对接商家具有一定的技术开发能力；对接该流程能使支付按钮更契合商户网站，且无需跳转离开商家网站；

<figure><img src="/files/tefHUKrySWfwMb7wlRKR" alt=""><figcaption></figcaption></figure>

### 1.自主集成流程图 <a href="#ydz7l" id="ydz7l"></a>

<figure><img src="/files/vHyFrJbXPjnlL5gAE4fr" alt=""><figcaption></figcaption></figure>

### 2.对接步骤 <a href="#cjoa7" id="cjoa7"></a>

#### 1. 创建sessionToken <mark style="color:blue;">**`server`**</mark>

商户服务端调用 [/sessionToken接口](https://asiabill.gitbook.io/api-explorer/api-reference/jiao-yi/sessiontoken)创建本次交易的会话即 **sessionToken。**

{% hint style="info" %}
建议商户通过服务端调用 **/sessionToken** 接口通过该接口可以获取到 **sessionToken**，该参数会用于后续支付流程的处理，商户需要从 **server** 端传递到 **web** 端供SDK中的API使用，请妥善保存，避免 **signkey** 等信息暴露在浏览器客户端。
{% endhint %}

#### 2. 加载 js sdk，需要加载 AsiabillPayment.min.js 到商城页面中

```http
https://{paymentApiUrl}/static/v3/js/AsiabillPayment.min.js
```

[{paymentApiUrl}](https://asiabill.gitbook.io/api-explorer/#4-huan-jing-can-shu) 为对应环境的url，请从链接地址获取url

#### 3. 初始化sdk文件

```javascript
let ab = AsiabillPay(sessionToken);//sessionToken为第一步后端获取的sessionToken
```

#### 4. 增加以下的参数 fastPayment 对象

```json
let fastPayment ={
    "billingDetailRequire": false, //账单信息是否从按钮中获取，默认false，false自定义billingDetail内容，true系统自动获取		非必填
    "shippingDetailRequire": false, //收件人信息是否从按钮中获取，默认false，true则返回shippingDetail，false则不返回	          非必填
    "shippingEmail": "123@163.com", //shippingDetailRequire为false，必填
    "shippingPhone": "18888888888", //shippingDetailRequire为false，必填
    "shippingOptionsRequire": true, //是否需要更改运送方式 非必填
    "allowedCountryCodes": [
        "US",
        "HK",
        "AU",
        "CN"
    ], //Google pay 支持的收件地址国家，非必填，为空则默认支持所有国家
    "googleId": "gpay_container", //Google pay区域 id,			必填
    "gatewayNo": document.getElementById("gatewayNo_").value, //网关号,			必填
    "googleStyle": { //Google pay按钮样式，具体设置详见第三小节，样式设置，非必填
        "buttonType": "checkout", //按钮类型
        "buttonColor": "black", //按钮颜色，支持black和white
        "buttonLocale": "fr" //按钮显示语言
    },
    "billingDetail": { //当billingDetailRequire为false或者为空时，必填，字段名不可修改
        "address": { //地址
            "city": "", //所在的城市
            "country": "", //联系人的两个字母 ISO 3166 国家/地区代码
            "line1": "", //详细地址
            "postalCode": "", //邮政编码
            "state": "", //州
        },
        "firstName": "", //名字
        "lastName": "", //姓氏
        "phone": "", //电话号码
        "email": "", //邮箱
    },
    "merchantName": "", //收款人名称，必填
    "appleId": "apple-pay-button", //apple pay 区域 id,			必填
    "shippingOptions": [ //若shippingOptionsRequire为true，则此项必填，且字段名不可更改
        {
            "id": "shipping-001", //运送方式id
            "label": "$1.00: Free shipping", //运送标签
            "description": "Free Shipping delivered in 5 business days.", //运送方式描述
            "amount": "100" //运费
        }
    ]
}
```

#### 5. 在界面需要展示Google pay 或 Apple Pay按钮的区域新增元素（需给定一个id）

```html
<apple-pay-button buttonstyle="black" id="apple-pay-button" type="plain" locale="en-US"></apple-pay-button>
<div id="gpay_container"></div>
```

#### 6. 执行以下方法进行按钮初始化，成功后会根据用户环境展示相应的Google pay或Apple pay按钮

```javascript
ab.elementInit("fastPayment", fastPayment);
```

#### 7. 执行updateFastPayment（）方法，传入金额，币种及国家，然后点击按钮操作，之后可通过自定义事件getResultData获取Google pay和Apple pay返回的数据以及错误信息

```javascript
ab.updateFastPayment({
				currencyCode:"USD",
				totalPrice: “100”,
				countryCode:"HK"
		}).then((res)=>{})
```

#### 8.监听自定义事件getShippingCountry，获取用户修改后的收件人国家，商户可自定义根据收件人国家更新物流运输方式

```javascript
window.addEventListener("getShippingCountry", e => {
  console.log(`getShippingCountry`, e);
  let res = e.detail;
  if(res.shippingCountryCode!=""){
    let shippingOptionsList=[
      {
        "id": "shipping-004",//运送方式id
        "label": "aaaaa",//运送标签
        "description": "Free Shipping delivered in 5 business days.",//运送方式描述
        "amount":"500"//运费
      },{
        "id": "shipping-005",//运送方式id
        "label": "bbbbb",//运送标签
        "description": "Free Shipping delivered in 5 business days.",//运送方式描述
        "amount":"600"//运费
      },{
        "id": "shipping-006",//运送方式id
        "label": "ccccc",//运送标签
        "description": "Free Shipping delivered in 5 business days.",//运送方式描述
        "amount":"700"//运费
      },
    ]
    //重新定义运送方式后，执行updateShippingOptions方法进行更新运送方式列表
    ab.updateShippingOptions(shippingOptionsList).then((res)=>{
      console.log("updateShippingOptions",res);
    })
  }
});
```

{% hint style="info" %}
当商家需要根据收件人国家来变更运输方式时，建议初始化对象里面 shippingOptions 默认一个免费运输方式；当初始化完成时会触发 getShippingCountry 监听事件，再根据获取到的信息来变更运输方式
{% endhint %}

#### 9. 点击按钮操作完成后，可通过getResultData()方法获取Google pay和Apple pay返回的数据，包括shippingDetail、billingDetail、paymentMethodId、shippingOptionsId、orderAmount

```javascript
window.addEventListener("getResultData",e => {
				let res3=e.detail
				console.log("resultGoogle",res3);
			})
```

返回报文结构如下

```json
res={
  "code": "0000", 
  "msg": "Successful", 
  "data": {
    "shippingDetail":{//收件人信息
      "address":{//地址
        "city":shippingAddress.locality,//所在的城市
        "country": shippingAddress.countryCode,//联系人的两个字母 ISO 3166 国家/地区代码
        "line1": shippingAddress.address1 + shippingAddress.address2 + shippingAddress.address3,//详细地址
        "postalCode": shippingAddress.postalCode,//邮政编码
        "state": shippingAddress.administrativeArea,//收件人的州
      },
      "firstName":  shippingAddress.name.substring(0,shippingIndex),//名字
      "lastName":  shippingAddress.name.substring(shippingIndex+1),//姓氏
      "phone": shippingAddress.phoneNumber,//电话号码
      "email":paymentData.email,//邮箱
    },
    "paymentMethodId":scriptParam.paymentMethodId,//支付方式id
    "shippingOptionsId":paymentData.shippingOptionData.id,//运送方式id
    "billingDetail":{//账单信息
      "address":{//地址
        "city":billingAddress.locality,//所在的城市
        "country": billingAddress.countryCode,//联系人的两个字母 ISO 3166 国家/地区代码
        "line1": billingAddress.address1 + billingAddress.address2 + billingAddress.address3,//详细地址
        "postalCode": billingAddress.postalCode,//邮政编码
        "state": billingAddress.administrativeArea,//联系人的州
      },
      "firstName":  billingAddress.name.substring(0,billingIndex),//名字
      "lastName":  billingAddress.name.substring(billingIndex+1),//姓氏
      "phone": billingAddress.phoneNumber,//电话号码
      "email":paymentData.email,//邮箱
    },
    "orderAmount":totalPrice,//付款总金额
  }
}
```

#### 10. 发起扣款 <mark style="color:blue;">**`server`**</mark>

商户可通过服务端调用[/confirmCharge](https://asiabill.gitbook.io/api-explorer/api-reference/jiao-yi/confirm-charge)发起扣款业务。

{% hint style="info" %}
customerPaymentMethodId 和 shipping 收件人信息使用前面步骤SDK获取到的值
{% endhint %}

#### 11. 进行扣款操作后，执行以下方法，参数为[/confirmCharge](https://asiabill.gitbook.io/api-explorer/api-reference/jiao-yi/confirm-charge)接口返回的 orderStatus 参数（建议，如果接口调用失败的情况，建议传入 pending 状态）

```javascript
ab.getConfirmStatus(code)
```

### 3.样式设置 <a href="#hlejn" id="hlejn"></a>

#### Google Pay <a href="#tjw23" id="tjw23"></a>

初始化时Google Pay样式参数

| 参数名称         | 描述   | 可传入值                                               |
| ------------ | ---- | -------------------------------------------------- |
| buttonType   | 按钮类型 | book、buy、checkout、donate、order、pay、plain、subscribe |
| buttonColor  | 按钮颜色 | black、white                                        |
| buttonLocale | 按钮语言 | 语言简称小写，例如：中文 zh，英文 en                              |

按钮类型展示如下：

|  ![](/files/PzGfTng812Xct5P3lC2d)book  |    ![](/files/nbDaZA8djPle2iMmBPx6)buy    | ![](/files/ruXlRuM3CH237ynStvSq)checkout |
| :------------------------------------: | :---------------------------------------: | :--------------------------------------: |
| ![](/files/c2lSubq3tqmK74Fz2gJa)donate |   ![](/files/BetvO0GOO4rqIdiwCu5L)order   |    ![](/files/yYChq4LjaIeyuPgD9ASn)pay   |
|  ![](/files/u2SkQOzGlEkQMl3wumJI)plain | ![](/files/FxAmGK00l8McabKQx2Lv)subscribe |                                          |

按钮大小控制：

```css
#gpay_container{
       width:180px;
       height: 30px;
}
```

#### Apple Pay <a href="#d1fae" id="d1fae"></a>

在Apple Pay标签中的三个参数

| 参数名称        | 描述   | 可传入值                                                                                                                    |
| ----------- | ---- | ----------------------------------------------------------------------------------------------------------------------- |
| buttonstyle | 按钮颜色 | black、white-outline、white                                                                                               |
| type        | 按钮类型 | plain、add-money、book、buy、check-out、continue、contribute、donate、order、pay、reload、rent、set-up、subscribe、support、tip、top-up |
| locale      | 按钮语言 | 按照ISO语言格式标准，例如：en-US，zh-CN                                                                                              |

按钮类型展示如下：

|    ![](/files/QvG9d2jRSbjiA2ydARyV)plain   | ![](/files/FrjXwBhVc0yjgCfpTy6m)add-money |   ![](/files/SCgP0wz3JuQpa8QxuKLN)book   |
| :----------------------------------------: | :---------------------------------------: | :--------------------------------------: |
|     ![](/files/ZFq4BNdfLNl0esEHrWwA)buy    | ![](/files/EqebOhteqi4Yah7ijyo7)check-out | ![](/files/EppoJaeViuxfokuPsH8q)continue |
| ![](/files/CWXTPmp78KCHFiKhZsIR)contribute |   ![](/files/OLSgcPId7nQ7PTptXFW9)donate  |   ![](/files/uVwnrr2hRXkciSsxnFih)order  |
|     ![](/files/md9UVqEddhNXuVaU4I3I)pay    |   ![](/files/18j7969ya8wSWFTyXXWM)reload  |   ![](/files/lgLo5Rcr1i0pHcZuALVu)rent   |
|   ![](/files/VYk7TvEw6Tr4Mzos5GxW)set-up   | ![](/files/ABvQFGIr7fJ0rKxGo1Ed)subscribe |  ![](/files/KQys3eZ14JnYktQ5J93d)support |
|     ![](/files/2G2T87LAWr5Ll80PG1Fx)tip    |   ![](/files/kGdvhRbgVLhCkyXvtUis)top-up  |                                          |

按钮样式可由CSS控制：

```css
<style>
apple-pay-button {
  --apple-pay-button-width: 150px;
  --apple-pay-button-height: 30px;
  --apple-pay-button-border-radius: 3px;
  --apple-pay-button-padding: 0px 0px;
  --apple-pay-button-box-sizing: border-box;
}
</style>
```

### 4.商户开通步骤 <a href="#nhhl3" id="nhhl3"></a>

1. 联系客服，提供商户网站交易域名，获取到服务器域名验证文件
2. 把域名验证文件放在服务器 https\://\[DOMAIN\_NAME]/.well-known/apple-developer-merchantid-domain-association 目录下，DOMAIN\_NAME 为提供给客服的交易域名
3. 通知Asiabill发送校验域名请求
4. 告知商家域名验证结果
5. 商家进行技术接口集成

### 5.测试账号信息

商户号：12230

&#x20;网关号：12230001

&#x20;signkey：12345678

{% hint style="info" %}
Google Pay 需加入[测试组群](https://developers.google.com/pay/api/android/guides/resources/test-card-suite?hl=zh-cn)后，才能进行测试支付
{% endhint %}

{% hint style="info" %}
Apple Pay 测试设备账号需联系 Asiabill 开发人员获取，测试卡号请参照[Apple Pay](https://developer.apple.com/apple-pay/sandbox-testing/)文档
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://asiabill.gitbook.io/docs/zhi-fu/zai-xian-zhi-fu/apple-pay-and-google-pay.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
