### Example of API Response JSON Structure
Source: https://sdk.qfapi.com/docs/preparation/introduction
This snippet illustrates a typical JSON response structure returned by the API. In this specific example, the response is a single string, likely representing a unique identifier or a hash.
```JSON
{
"B3B251B202801388BE4AC8E5537B81B1"
}
```
--------------------------------
### Initiate QFPay Payment Request (PHP)
Source: https://sdk.qfapi.com/docs/online-shop/alipay/alipay-service-window-h5
This PHP example demonstrates how to construct a payment request, generate a random trade number, sort the payload fields, create an MD5 signature, and prepare the cURL request for the QFPay payment API. It highlights the use of `urlencode` for parameters and `curl_init` for the HTTP request, showing the setup for a payment transaction.
```php
urlencode($mchid),
'pay_type' => urlencode($pay_type),
'out_trade_no' => urlencode(GetRandStr(20)),
'txcurrcd' => urlencode('HKD'),
'txamt' => urlencode(2200),
'txdtm' => $now_time
);
ksort($fields); //字典排序A-Z升序方式
print_r($fields);
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&' ;
}
$fields_string = substr($fields_string , 0 , strlen($fields_string) - 1);
$sign = strtoupper(md5($fields_string . $app_key));
//// Header ////
$header = array();
$header[] = 'X-QF-APPCODE: ' . $app_code;
$header[] = 'X-QF-SIGN: ' . $sign;
//Post Data
$ch = curl_init();
```
--------------------------------
### HTML/JavaScript Example for QFPay Checkout Signature Generation
Source: https://sdk.qfapi.com/docs/online-shop/checkout
This client-side HTML and JavaScript snippet demonstrates how to construct the QFPay checkout URL, including the generation of the authentication signature. It outlines the process of parameter stringification, sorting, and SHA256 hashing using external libraries, ultimately setting the `href` attribute for a link that redirects to the QFPay hosted checkout page. This example is designed to be run directly in a web browser.
```HTML
checkout
QFPay Online Checkout
```
--------------------------------
### Example QFPay API Response Parameters
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
An example JSON structure for response parameters returned by QFPay APIs, including transaction details, timestamps, and payment intent identifiers. This structure indicates a successful transaction with relevant payment information.
```JSON
{
"respcd": "0000",
"txamt": "123",
"txcurrcd": "123",
"sysdtm": "2022-11-14 16:15:16",
"out_trade_no": "501871840",
"payment_intent": "38aec7cef8564f309ea2265a454b8ca5",
"intent_expiry": "2022-11-15 12:34:34"
}
```
--------------------------------
### QFPay Checkout API GET Request Parameters
Source: https://sdk.qfapi.com/docs/online-shop/checkout
Details the necessary and optional parameters for initiating a new checkout request via the QFPay API, including data types, mandatory status, and example values for each attribute.
```APIDOC
Endpoint: https:test-openapi-hk.qfapi.com/checkstand/#/?..
Method: GET
Description: The following body parameters are necessary to create a new checkout request;
Parameters:
- appcode:
Type: String(64)
Mandatory: Yes
Description: API credentials assigned by QFPay, e.g. A6A49A********************5032
- sign_type:
Type: String(256)
Mandatory: Yes
Description: SHA256 or MD5, SHA256 is recommended, e.g. sha256
- sign:
Type: String(128)
Mandatory: Yes
Description: Request signature for authentication e.g. 3b020a6349646684ebeeb0ec2cd3d1fb
- paysource:
Type: String(12)
Mandatory: Yes
Description: Must end in _checkout e.g. remotepay_checkout
- txamt:
Type: Int(11)
Mandatory: Yes
Description: Payment amount in unit cents e.g. 1099. Suggest value > 200 to avoid risk control
- txcurrcd:
Type: String(3)
Mandatory: Yes
Description: Currency code e.g. HKD
- out_trade_no:
Type: String(128)
Mandatory: Yes
Description: Unique external transaction number e.g. 202005270001
- txdtm:
Type: String(32)
Mandatory: Yes
Description: Order time e.g. 2020-06-24 20:04:37, Format: YYYY-MM-DD hh:mm:ss
- return_url:
Type: String(256)
Mandatory: Yes
Description: Redirect URL after payment has been successful e.g. https://xxx.com/return/success
- failed_url:
Type: String(256)
Mandatory: Yes
Description: Redirect URL after payment has failed e.g. https://xxx.com/return/failed
- notify_url:
Type: String(256)
Mandatory: Yes
Description: Asynchronous notification URL e.g. https://xxx.com/notify/success
- mchntid:
Type: String(16)
Mandatory: No
Description: QFPay Merchant Identifier for Agents e.g. PAKjVHJmQe
- goods_name:
Type: String(64)
Mandatory: No
Description: No special characters, no more than 20 letters or Chinese characters (app payment parameters must be passed). If you want to display the merchant name on the clearing file, this parameter must be empty.
- udid:
Type: String(40)
Mandatory: No
Description: Unique device ID e.g. 0001
- expired_time:
Type: String(3)
Mandatory: No
Description: QRC expiration time. Unit in minutes, minimum 5 minutes, maximum 120 minutes, only WeChat Pay, Alipay and Alipay_hk support this parameter
- checkout_expired_time:
Type: String(3)
Mandatory: No
Description: client side expiration time , unit in millisecond e.g. 1715686118000, the checkout page will be redirect to fail url when time is up
- limit_pay:
Type: String(3)
Mandatory: No
Description: Prohibit credit card use, the parameter value is specified as no_credit, which prohibits the use of credit card payments, only WeChat Pay supports this feature.
- lang:
Type: String(5)
Mandatory: No
Description: UI Language, possible values:
- zh-hk (Hong Kong Traditional Chinese)
- zh-cn (Simplified Chinese)
- en (English)
The checkout page will use default language of browser if do not pass this parameter in checkout request. If pass this parameter in checkout request, do not include this parameter in generating signature.
- cancel_url:
Type: String(256)
Mandatory: No
Description: Redirect URL after clicking "Back to XXX Store" button in checkout page e.g. https://xxx.com/return/checkout
```
--------------------------------
### Python API Client Setup and Signature Generation
Source: https://sdk.qfapi.com/docs/common-api/reversal-cancel
This Python code snippet demonstrates the initial setup for interacting with the API. It includes defining environment variables for client credentials (app_code, client_key), generating dynamic values like the current timestamp and a random string for request parameters, and implementing a utility function `make_req_sign` to compute the MD5 signature required for authenticating API requests. This signature generation ensures data integrity and authenticity.
```Python
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, hashlib
import requests
from hashids import Hashids
import datetime
import string
import random
# Enter Client Credentials
environment = 'https://test-openapi-hk.qfapi.com'
app_code = '3F504C39125E4886AB4741**********'
client_key = '5744993FBC034DBBB995FA**********'
# Create parameter values for data payload
current_time = datetime.datetime.now().replace(microsecond=0)
random_string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=32))
print(current_time)
# Create signature
def make_req_sign(data, key):
keys = list(data.keys())
keys.sort()
p = []
for k in keys:
v = data[k]
p.append('%s=%s'%(k,v))
unsign_str = ('&'.join(p) + key).encode("utf-8")
print(unsign_str)
s = hashlib.md5(unsign_str).hexdigest()
return s.upper()
```
--------------------------------
### Process Standard Payment with QFPay SDK
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
Demonstrates the `payment.pay` method for initiating standard payments. It includes the API specification detailing parameters like `goods_name`, `paysource`, and optional tokenization parameters, alongside a JavaScript example of its usage.
```APIDOC
parameters:
params1,mandatory,Object,
{goods_name: '', paysource: 'payment_element'}
goods_name: goods name,optional;
paysource: fixed, value:payment_element, mandatory
params2, mandatory, string, payment intent value from API
extra special parameters in 'params1':
customer_id: params1 optional parameter,QFPay generated customer Id
token_expiry: params1 optional parameter, Token expiry date
token_reason: params1 optional parameter, Reason for token creation
token_reference: params1 optional parameter, Reference for token
no need pass above special parameters if use payment function only
if would like to collect card information for tokenization purpose, then need pass above parameters
return: No
purpose:set payment parameters
```
```JavaScript
payment.pay({
goods_name: 'goods',
paysource: 'payment_element'
}, 'SDF8980SFFSDF890SDF')
```
--------------------------------
### GET WeChat OAuth Code Request URL Example
Source: https://sdk.qfapi.com/docs/online-shop/wechat/wechat-pay-jsapi
This snippet illustrates the structure of the GET request URL used to initiate the WeChat OAuth process with the QFPay API. It includes placeholders for `app_code`, `sign`, and `redirect_uri`.
```HTTP Request
GET WeChat oauth_code request:
{
https://test-openapi-hk.qfapi.com/tool/v1/get_weixin_oauth_code?app_code=5D81D64E602043F7AF51CEXXXXXXXXXX&sign=F4D8FB00894F213993B33116BC1B4E10&redirect_uri=https://sdk.qfapi.com
}
```
--------------------------------
### PHP Qfpay Payment Request Setup
Source: https://sdk.qfapi.com/docs/in-store/MPM
This PHP snippet demonstrates the initial setup for a Qfpay payment request. It includes a helper function to generate random strings for `out_trade_no`, defines API credentials, sets transaction parameters, and shows how to sort the payload fields alphabetically for signature generation. The signature calculation and API call are not fully present in this snippet.
```php
urlencode($mchid),
'pay_type' => urlencode($pay_type),
'out_trade_no' => urlencode(GetRandStr(20)),
'txcurrcd' => urlencode('HKD'),
'txamt' => urlencode(2200),
'txdtm' => $now_time
);
ksort($fields); //Ascending dictionary sorting A-Z
print_r($fields);
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&' ;
}
$fields_string = substr($fields_string , 0 , strlen($fields_string) - 1);
```
--------------------------------
### Python Example for Refund API Integration
Source: https://sdk.qfapi.com/docs/common-api/refunds
This Python code snippet demonstrates how to set up client credentials, generate dynamic parameter values, and create a request signature for interacting with the refund API. It includes imports for network requests, hashing, and datetime operations.
```Python
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, hashlib
import requests
from hashids import Hashids
import datetime
import string
import random
# Enter Client Credentials
environment = 'https://test-openapi-hk.qfapi.com'
app_code = 'D5589D2A1F2E42A9A60C37**********'
client_key = '0E32A59A8B454940A2FF39**********'
# Create parameter values for data payload
current_time = datetime.datetime.now().replace(microsecond=0)
random_string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=32))
# Create signature
def make_req_sign(data, key):
keys = list(data.keys())
keys.sort()
p = []
for k in keys:
v = data[k]
p.append('%s=%s'%(k,v))
unsign_str = ('&'.join(p) + key).encode("utf-8")
s = hashlib.md5(unsign_str).hexdigest()
return s.upper()
```
--------------------------------
### Python QFPay Payment Request Example
Source: https://sdk.qfapi.com/docs/preparation/introduction
Demonstrates how to construct a payment request payload and send it to the QFPay API using Python's requests library. It includes details for transaction amount, currency, payment type, and signature generation using a placeholder `make_req_sign` function.
```python
txamt = '10' # In USD,EUR,etc. Cent. Suggest value > 200 to avoid risk control.
txcurrcd = 'HKD'
pay_type = '800101' # Alipay CPM = 800108 , MPM = 800101
auth_code='283854702356157409' #CPM only
out_trade_no = random_string
txdtm = current_time
goods_name = 'test1'
auth_code = '280438849930815813'
key = client_key
mchid = 'ZaMVg*****' # ID is provided during merchant onboarding
#data ={'txamt': txamt, 'txcurrcd': txcurrcd, 'pay_type': pay_type, 'out_trade_no': out_trade_no, 'txdtm': txdtm, 'goods_name': goods_name, 'udid': udid, 'auth_code': auth_code, 'mchid': mchid}
data ={'txamt': txamt, 'txcurrcd': txcurrcd, 'pay_type': pay_type, 'out_trade_no': out_trade_no, 'txdtm': txdtm, 'goods_name': goods_name, 'mchid': mchid}
r = requests.post(environment+"/trade/v1/payment",data=data,headers={'X-QF-APPCODE':app_code,'X-QF-SIGN':make_req_sign(data, key)})
print(make_req_sign(data, key))
```
--------------------------------
### Transaction Enquiry API HTTP Request Example
Source: https://sdk.qfapi.com/docs/common-api/transaction-enquiry
This snippet illustrates the required HTTP headers and an example request body for making a POST request to the `/trade/v1/query` endpoint. It shows how to include `Content-Type`, `X-QF-APPCODE`, and `X-QF-SIGN` in the header, and various query parameters like `mchid`, `syssn`, `start_time`, and `end_time` in the body.
```APIDOC
Request Header:
{
Content-Type: application/x-www-form-urlencoded;
X-QF-APPCODE: D5589D2A1F2E42A9A60C37**********
X-QF-SIGN: 6FB43AC29175B4602FF95F8332028F19
}
Request Body:
{
mchid=ZaMVg*****&syssn=20191227000200020061752831&start_time=2019-12-27 00:00:00&end_time=2019-12-27 23:59:59
}
```
--------------------------------
### Python Asynchronous Notification Signature Verification Setup
Source: https://sdk.qfapi.com/docs/common-api/asynchronous-notification
This Python code snippet provides the initial setup for verifying asynchronous notifications from QFPay. It imports the `hashlib` and `json` libraries and defines a placeholder `client_key` which is crucial for the MD5 signature verification process as described in the 'Signature Verification' section.
```Python
import hashlib
import json
# Client Credentials
client_key = "3ABB1BFFE2E0497BB9270978B0BXXXXX"
```
--------------------------------
### Example API Response Structure (JSON)
Source: https://sdk.qfapi.com/docs/in-store/MPM
This JSON snippet provides an example of a successful API response, likely from a payment or transaction processing system. It includes fields such as `surcharge_fee`, `qrcode`, `pay_type`, transaction details (`txdtm`, `out_trade_no`), and response codes (`respcd`, `respmsg`). This structure helps developers understand the data returned by the API.
```JSON
{
"surcharge_fee": 0,
"qrcode": "https://qr.alipay.com/bax03190uxd47wbekffy6033",
"pay_type": "800101",
"surcharge_rate": 0,
"resperr": "success",
"txdtm": "2020-04-23 11:09:24",
"out_trade_no": "364ZK6BAJGYHMU3TUX0X7MGIGQL4O8KI",
"syssn": "20200423066200020000976054",
"sysdtm": "2020-04-23 11:09:27",
"txcurrcd": "EUR",
"respmsg": "",
"chnlsn2": "",
"cardcd": "",
"udid": "qiantai2",
"txamt": "1",
"respcd": "0000",
"chnlsn": ""
}
```
--------------------------------
### Sample API Response Format
Source: https://sdk.qfapi.com/docs/online-shop/qfpay-recurring-payment
An example of a successful API response, specifically for a subscription query, demonstrating the common response structure with 'respcd', 'resperr', 'respmsg', and the 'data' field containing a list of subscription objects.
```JSON
{
"resperr": "success",
"respcd": "0000",
"respmsg": "success",
"data": [
{
"total_billing_cycles": 3,
"last_billing_time": "2024-11-21T11:12:06Z",
"is_available": 1,
"userid": 2510351,
"last_billing_status": "SUCCESS",
"state": "ACTIVE",
"products": [
{ "product_id": "prod_8efecd0bd******b9aa1ec5ec01", "quantity": 1 }
],
"retry_attempts": 0,
"completed_iteration": 1,
"token_id": "tk_9ac510017*******69b614e8f7ee",
"subscription_id": "sub_e120378de*******da066f690da75",
"customer_id": "cust_5ba1539f*******c9bda11d12c854e36",
"next_billing_time": "2024-11-21T11:13:06Z"
}
]
}
```
--------------------------------
### Process Wallet Payments with QFPay SDK
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
Illustrates the `payment.walletPay` method for handling wallet-based transactions. This snippet provides the API documentation for its parameters, including `lang`, `goods_name`, `paysource`, `out_trade_no`, `txamt`, `txcurrcd`, and `support_pay_type`, along with a JavaScript usage example.
```APIDOC
parameters:
params1, mandatory, Object, { lang: 'zh-cn', goods_name: '', paysource: 'payment_element', paysource: "payment_element_checkout", out_trade_no: intentParams.out_trade_no, txamt: intentParams.txamt, txcurrcd: intentParams.txcurrcd}
lang: language, optional, zh-cn:simplify chinese, zh-hk traditional chinese, en: english
goodsname: goods name, optional,
paysource: fix value, payment_element_checkout,mandatory
out_trade_no: merchant order id, mandatory
txamt: transaction amount in cents, mandatory. Suggest value > 200 to avoid risk control
txcurrcd: transaction currency, mandatory
support_pay_type: customize display of activited payment methods, optional, show all activated methods if not pass this parameter, detail parameter values please refer to the folllwoing description
params2, mandatory, string, payment intent value from
extra special parameters in 'params1':
customer_id: params1 optional parameter,QFPay generated customer Id
token_expiry: params1 optional parameter, Token expiry date
token_reason: params1 optional parameter, Reason for token creation
token_reference: params1 optional parameter, Reference for token
no need pass above special parameters if use payment function only
if would like to collect card information for tokenization purpose, then need pass above parameters
return: No
purpose:set payment parameters
params1 support_pay_type parameter value list
'Alipay' // 'Alipay CN',
'WeChat' // 'Wechat',
'UnionPay' // 'UnionPay and QuickPass',
'AlipayHK' // 'Alipay HK',
'FPS' // 'FPS',
'VisaMasterCardPayment' // 'Visa/MasterCard'
'PayMe' // 'PayMe'
'ApplePay' // 'ApplePay'
'VisaMasterCardPreAuth' // 'Visa/MasterCard Pre-Authorization'
```
```JavaScript
payment.walletPay({
goods_info: 'goods_info',
goods_name: "goods_name",
paysource: "payment_element_checkout",
out_trade_no: intentParams.out_trade_no,
txamt: intentParams.txamt,
txcurrcd: intentParams.txcurrcd,
}, 'SDF8980SFFSDF890SDF')
```
--------------------------------
### Example JSON Response for QFPay Payment API
Source: https://sdk.qfapi.com/docs/preparation/paycode
Illustrates the typical JSON structure returned by the QFPay payment API upon a successful transaction. It includes various transaction details such as transaction time, QR code, payment type, amounts, and system identifiers.
```json
{
"txdtm": "2019-12-25 14:21:28",
"qrcode": "https://qr.alipay.com/bax01781r3pu4fjaqazt4091",
"pay_type": "800101",
"resperr": "success",
"out_trade_no": "01234567890123",
"syssn": "20191225000200020060996533",
"sysdtm": "2019-12-25 14:22:37",
"paydtm": "2019-12-25 14:22:37",
"txcurrcd": "EUR",
"respmsg": "",
"cardcd": "",
"udid": "qiantai2",
"txamt": "10",
"respcd": "0000",
"chnlsn": ""
}
```
--------------------------------
### Initialize and Process Credit Card Payments with QFPay Element SDK
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
This example demonstrates how to initialize the QFPay SDK, set up a payment object, and generate a credit card form. It shows the steps to configure payment parameters, create the UI component, and trigger the submission to receive a payment response.
```JavaScript
// initialize qfpay object
const qfpay = QFpay.config()
// initialize payment object
const payment = qfpay.payment()
// set payment related parameters
payment.pay({
goods_name: "goods",
paysource: "payment_element"
}, "e487a02e3e1143e482db765ccec63d58")
// initialize element object and generate card form
const elements = qfpay.element()
elements.createEnhance({
selector: "#container"
})
// trigger card form submission and receive payment response
const response = qfpay.confirmPayment({
return_url: 'https://xxx.xxx.com'
})
```
--------------------------------
### GET WeChat OpenID Request URL Example
Source: https://sdk.qfapi.com/docs/online-shop/wechat/wechat-pay-jsapi
This snippet provides an example of the HTTP GET request URL used to obtain the WeChat OpenID from the QFPay API. It demonstrates how the previously acquired `code` is passed as a query parameter.
```HTTP Request
HTTP Request:
{
https://test-openapi-hk.qfapi.com/tool/v1/get_weixin_openid?code=011QipnO1yMIla1VJdoO1FUrnO1Qipnv
}
```
--------------------------------
### QFPay API Environments Base URLs
Source: https://sdk.qfapi.com/docs/preparation/introduction
This section provides the base URLs for accessing different QFPay API environments, including Sandbox for credit card simulations, Live Testing, and the Production environment.
```APIDOC
Environment Name | Prod. URL
---|---
Sandbox (Only for credit card simulations) | https://openapi-int.qfapi.com
Live Testing Environment | https://test-openapi-hk.qfapi.com
Production | https://openapi-hk.qfapi.com
```
--------------------------------
### QFPay API Request Body Example
Source: https://sdk.qfapi.com/docs/online-shop/wechat/wechat-in-app-payments
Illustrates an example of the data structure sent in the request body for a QFPay transaction. Note that the example provided is a key-value string, not a valid JSON object, despite being presented within JSON-like delimiters.
```text
goods_info=test_app&goods_name=qfpay&out_trade_no=O5DNgEgL1XpvbvQSfPhN&pay_type=800210&txamt=10&txcurrcd=HKD&txdtm=2019-09-13 04:53:03&udid=AA
```
--------------------------------
### Initialize QFPay Payment Object
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
Demonstrates the necessary steps to initialize both the QFPay global object and the payment object, which is a prerequisite for performing payment operations.
```javascript
const qfpay = QFpay.config()
const payment = qfpay.payment()
```
--------------------------------
### Initiate QFPay Payment Request (Java)
Source: https://sdk.qfapi.com/docs/online-shop/alipay/alipay-service-window-h5
This Java example illustrates how to build a payment request map, generate a timestamp, sign the request using MD5, and send a POST request to the QFPay payment API. It utilizes `SimpleDateFormat` for date formatting and `HashMap` for payload construction, demonstrating a complete payment flow.
```java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TestMain {
public static void main(String args[]){
String appcode="D5589D2A1F2E42A9A60C37*********";
String key="0E32A59A8B454940A2FF39*********";
String mchid="ZaMVg*****";
String pay_type="801107";
String out_trade_no= "01234567890123";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date=df.format(new Date());
String txdtm=date;
String txamt="10";
String txcurrcd="EUR";
Map unsortMap = new HashMap<>();
unsortMap.put("mchid", mchid);
unsortMap.put("pay_type", pay_type);
unsortMap.put("out_trade_no", out_trade_no);
unsortMap.put("txdtm", txdtm);
unsortMap.put("txamt", txamt);
unsortMap.put("txcurrcd", txcurrcd);
//unsortMap.put("product_name", product_name);
//unsortMap.put("valid_time", "300");
String data=QFPayUtils.getDataString(unsortMap);
System.out.println("Data:\n"+data+key);
String md5Sum=QFPayUtils.getMd5Value(data+key);
System.out.println("Md5 Value:\n"+md5Sum);
String url="https://test-openapi-hk.qfapi.com";
String resp= Requests.sendPostRequest(url+"/trade/v1/payment", data, appcode,key);
System.out.println(resp);
}
}
```
--------------------------------
### Encrypted API Request Payload Example
Source: https://sdk.qfapi.com/docs/in-store/pos-api/ECR
An example JSON payload demonstrating the structure when encryption is enabled. In this scenario, the `content` field contains an encrypted string, and the `digest` is calculated based on this encrypted payload.
```JSON
{
"content": "{func_type: 3002}",
"digest":"79fd145311d54d03e4e685d50f15dd7f"
}
```
--------------------------------
### Subscription State Change Notification Example Payload
Source: https://sdk.qfapi.com/docs/online-shop/qfpay-recurring-payment
Illustrates the JSON structure of a notification payload sent when a subscription's state changes. This example shows a 'COMPLETED' state change with its associated system timestamp and identifiers.
```json
{
"state": "COMPLETED",
"sysdtm": "2024-04-24 15:19:39",
"notify_type": "subscription",
"subscription_id": "sub_e51bb914919*****f6b0fe36d"
}
```
--------------------------------
### Initiate Qfpay Refund API Request
Source: https://sdk.qfapi.com/docs/common-api/refunds
This section provides examples for initiating a refund request via the Qfpay API. It outlines the necessary steps including preparing the request payload with parameters like transaction amount (txamt), original transaction number (syssn), and a unique outbound trade number (out_trade_no), generating the MD5 signature based on sorted parameters and the application key, and sending the POST request to the /trade/v1/refund endpoint. Ensure to replace placeholder credentials with your actual API keys and merchant ID.
```Python
txamt = '10' #Partial or full refund amount
syssn = '20191227000200020061752831' #Original transaction number
out_trade_no = random_string
txdtm = current_time
key = client_key
mchid = 'ZaMVg*****'
#data ={'txamt': txamt, 'syssn': syssn, 'out_trade_no': out_trade_no, 'txdtm': txdtm, 'udid': udid, 'mchid': mchid}
data ={'mchid': mchid, 'txamt': txamt, 'syssn': syssn, 'out_trade_no': out_trade_no, 'txdtm': txdtm}
r = requests.post(environment+"/trade/v1/refund",data=data,headers={'X-QF-APPCODE':app_code,'X-QF-SIGN':make_req_sign(data, key)})
print(r.json())
```
```Java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Refund {
public static void main(String args[]){
String appcode="D5589D2A1F2E42A9A60C37**********";
String key="0E32A59A8B454940A2FF39**********";
String mchid="ZaMVg*****"; // Only Agents must provide the mchid
String out_trade_no= "22333444455555";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date=df.format(new Date());
String txdtm=date;
String txamt="15";
String syssn="20191227000300020061662295";
//如果是国内钱台,产品名称对应的字段是goods_name,不是product_name.
//String product_name="Test Name";
Map unsortMap = new HashMap<>();
unsortMap.put("mchid", mchid);
unsortMap.put("txamt", txamt);
unsortMap.put("syssn", syssn);
unsortMap.put("out_trade_no", out_trade_no);
unsortMap.put("txdtm", txdtm);
String data=QFPayUtils.getDataString(unsortMap);
System.out.println("Data:\n"+data+key);
String md5Sum=QFPayUtils.getMd5Value(data+key);
System.out.println("Md5 Value:\n"+md5Sum);
//如果是国内钱台,网址是:https://test-openapi-hk.qfapi.com.
String url="https://test-openapi-hk.qfapi.com";
String resp= Requests.sendPostRequest(url+"/trade/v1/refund", data, appcode,key);
System.out.println(resp);
}
}
```
```JavaScript
// Enter Client Credentials
const environment = 'https://test-openapi-hk.qfapi.com'
const app_code = 'D5589D2A1F2E42A9A60C37**********'
const client_key = '0E32A59A8B454940A2FF3***********'
// Generate Timestamp
var dateTime = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
console.log(dateTime)
// Body Payload
const key = client_key
var tradenumber = String(Math.round(Math.random() * 1000000000))
console.log(tradenumber)
var payload = {
'syssn': '20191231000300020063521806',
'txamt': '10',
'out_trade_no': tradenumber,
'txdtm': dateTime,
'mchid': 'ZaMVg*****'
};
// Signature Generation
const ordered = {};
Object.keys(payload).sort().forEach(function(key) {
ordered[key] = payload[key] });
console.log(ordered)
var str = [];
for (var p in ordered)
if (ordered.hasOwnProperty(p)) {
str.push((p) + "=" + (ordered[p]));
}
var string = str.join("&")+client_key;
console.log(string)
const crypto = require('crypto')
var hashed = crypto.createHash('md5').update(string).digest('hex')
console.log(hashed)
// API Request
var request = require("request");
request({
uri: environment+"/trade/v1/refund",
headers: {
'X-QF-APPCODE': app_code,
'X-QF-SIGN': hashed
},
method: "POST",
form: payload,
},
function(error, response, body) {
console.log(body);
});
```
```PHP
urlencode($mchid),
'syssn' => urlencode($syssn),
'out_trade_no' => urlencode(GetRandStr(20)),
'txamt' => urlencode(2200),
'txdtm' => $now_time
);
ksort($fields); //Sort parameters in ascending order from A to Z
print_r($fields);
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&' ;
}
$fields_string = substr($fields_string , 0 , strlen($fields_string) - 1);
$sign = strtoupper(md5($fields_string . $app_key));
//// Header ////
$header = array();
$header[] = 'X-QF-APPCODE: ' . $app_code;
$header[] = 'X-QF-SIGN: ' . $sign;
//Post Data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $api_type);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
```
--------------------------------
### Import QFPay Element SDK JavaScript Library
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
This snippet provides the necessary
// live test environment
// production environment
```
--------------------------------
### Subscription Payment Result Notification Example Payload
Source: https://sdk.qfapi.com/docs/online-shop/qfpay-recurring-payment
Shows the JSON structure of a notification payload for a subscription order payment result. This example provides a detailed view of a successful payment, including transaction details, card information, and associated identifiers.
```json
{
"txcurrcd": "HKD",
"reason": "AUTHORISED",
"cardcd": "",
"subscription_order_id": "sub_ord_a360f06eb*****ad6aff24c3a",
"product_id": "prod_8c838c17ddb043b9***11f1a85c30",
"txdtm": "2024-04-24 15:19:37",
"txamt": "300",
"card_scheme": "VISA_DEBIT-SSL",
"syssn": "20240424180500020000015704",
"respcd": "0000",
"subscription_id": "sub_e51bb914919***31d800f6b0fe36d",
"customer_id": "cust_a9c0bcf2717f4***786a10e5f8f2",
"notify_type": "subscription_payment",
"current_iteration": "1"
}
```
--------------------------------
### ECR Integration Refund/Void Request Payload Example
Source: https://sdk.qfapi.com/docs/in-store/pos-api/ECR
This JSON example illustrates the structure of a request payload for initiating a refund or void operation. It includes the `func_type` for the operation, the `orderId` of the transaction to be refunded, and optional parameters like `refund_amount` for partial refunds and `allow_modify_flag`.
```JSON
{
"content": {
"allow_modify_flag":1,
"func_type": 1002,
"orderId": "order_id",
"refund_amount": "0.05",
"moveToBack": 1
},
"digest": "9C8E9FB05C7C24B6CA04EBFA1263EF41"
}
```
--------------------------------
### API Request General Specifications
Source: https://sdk.qfapi.com/docs/preparation/introduction
This section outlines the general characteristics and requirements for making API requests, including the character encoding, supported HTTP methods (POST/GET), and the expected content type for the request body.
```APIDOC
API Request Specifications:
Character: UTF-8
Method: POST/ GET (Depends on individual API function)
Content-type: application/x-www-form-urlencoded
```
--------------------------------
### ECR Integration Payment Request Payload Example
Source: https://sdk.qfapi.com/docs/in-store/pos-api/ECR
This JSON example demonstrates a typical request payload for initiating a payment transaction. It includes mandatory fields like `amt`, `channel`, and `func_type`, along with optional parameters such as `camera_id`, `wait_card_timeout`, and `scan_type` for specific payment scenarios.
```JSON
{
"content": {
"amt": 100,
"camera_id":0,
"channel": "card_payment",
"func_type": 1001,
"moveToBack": 1,
"out_trade_no": "456799999999",
"wait_card_timeout":120,
"scan_type": "SCAN_PAY"
},
"digest":"76b9186077cdc2bc5d78ae921309811d"
}
```
--------------------------------
### PHP QFPay Payment Payload Preparation
Source: https://sdk.qfapi.com/docs/preparation/introduction
Shows how to prepare a payment request payload in PHP for the QFPay API. It includes a utility function to generate a random string for `out_trade_no`, sets transaction details, and demonstrates sorting parameters in ascending order for signature generation.
```php
urlencode($mchid),
'pay_type' => urlencode($pay_type),
'out_trade_no' => urlencode(GetRandStr(20)),
'txcurrcd' => urlencode('HKD'),
'txamt' => urlencode(2200),
'txdtm' => $now_time
);
ksort($fields); //Sort parameters in ascending order from A to Z
print_r($fields);
```
--------------------------------
### Asynchronous Transaction Notifications API Definition and Example
Source: https://sdk.qfapi.com/docs/online-shop/online-pre-authorisation
This section outlines the types of asynchronous notifications sent by the system upon completion of various transaction actions (payment, unfreeze, refund). It specifies the `notify_type` values for each action and provides a comprehensive example of the JSON payload received for such notifications.
```APIDOC
Notification Types:
Payment Captured: notify_type = "payment"
Unfreeze funds: notify_type = "unfreeze"
Refund: notify_type = "refund"
```
```JSON
{
"status": "1",
"pay_type": "800101",
"sysdtm": "2020-05-14 12:32:56",
"paydtm": "2020-05-14 12:33:56",
"goods_name": "",
"txcurrcd": "HKD",
"txdtm": "2020-05-14 12:32:56",
"mchid": "",
"txamt": "10",
"exchange_rate": "",
"chnlsn2": "",
"out_trade_no": "YEPE7WTW46NVU30JW5N90H7DHD94N56B",
"syssn": "20200514000300020093755455",
"cash_fee_type": "",
"cancel": "0",
"respcd": "0000",
"goods_info": "",
"cash_fee": "0",
"notify_type": "payment",
"chnlsn": "",
"cardcd": ""
}
```
--------------------------------
### Python Payment API Signature Generation and Setup
Source: https://sdk.qfapi.com/docs/preparation/paycode
This Python code snippet illustrates how to configure client credentials and generate the `X-QF-SIGN` required for authenticating API requests. It includes necessary imports for URL handling, HTTP requests, date/time operations, and hashing. The `make_req_sign` function demonstrates the process of sorting parameters, concatenating them with the client key, and computing an MD5 hash to produce the final signature.
```Python
#coding=utf8
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, hashlib
import requests
import datetime
import string
# Enter Client Credentials
environment = 'https://test-openapi-hk.qfapi.com'
app_code = 'D5589D2A1F2E42A9A60C37*********'
client_key = '0E32A59A8B454940A2FF39**********'
# Create parameter values for data payload
current_time = datetime.datetime.now().replace(microsecond=0)
print(current_time)
# Create signature
def make_req_sign(data, key):
keys = list(data.keys())
keys.sort()
p = []
for k in keys:
v = data[k]
p.append('%s=%s'%(k,v))
unsign_str = ('&'.join(p) + key).encode("utf-8")
s = hashlib.md5(unsign_str).hexdigest()
return s.upper()
```
--------------------------------
### Example JSON Response from QFPay Refund API
Source: https://sdk.qfapi.com/docs/common-api/refunds
This JSON object illustrates the typical structure and data returned by the QFPay refund API after a successful transaction. It includes various transaction identifiers, timestamps, amounts, and status codes, providing a clear example of the expected API response format.
```json
{
"orig_syssn": "20191227000200020061752831",
"sysdtm": "2019-12-27 11:11:23",
"paydtm": "2019-12-27 11:11:26",
"txdtm": "2019-12-27 11:10:38",
"udid": "qiantai2",
"txcurrcd": "EUR",
"txamt": "10",
"resperr": "success",
"respmsg": "",
"out_trade_no": "RGNOEIVU9JZLNP9GGYXWXCW7OEMI720F",
"syssn": "20191227000300020061652643",
"respcd": "0000",
"chnlsn": "2019122722001411461404119764",
"cardcd": ""
}
```
--------------------------------
### WeChat Pay H5 Response Parameters and Pay URL Example
Source: https://sdk.qfapi.com/docs/online-shop/wechat/wechat-pay-h5
This section describes the response parameters for WeChat Pay H5, specifically highlighting the `pay_url` attribute. It provides an example of a `pay_url` and explains how to append a `redirect_url` for post-payment redirection, ensuring the user returns to a specified page.
```APIDOC
Response Parameters:
Public response parameters: Refer to Public Payment Section
pay_url: Yes, String
Example pay_url:
https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096
Note on redirect_url:
In normal process after payment, the user will return to the page where payment is initiated. If you want user to return to the specified page, you can insert redirect_url parameter to returned payment URL. For example, if you want user to jump to https://www.wechatpay.com.cn, it can be processed as follows:
(Implicitly, append &redirect_url=https://www.wechatpay.com.cn to the pay_url)
```
--------------------------------
### MPM API Request Header and Body Examples
Source: https://sdk.qfapi.com/docs/in-store/MPM
Illustrative examples of the HTTP request header and body payload for an MPM payment transaction. The header specifies content type and custom authentication tokens, while the body contains transaction details like amount, currency, and unique identifiers.
```APIDOC
Request Header:
{
Content-Type: application/x-www-form-urlencoded;
charset=UTF-8,
Content-Length: 218,
Chunked: false,
X-QF-APPCODE: A6A49A66B4C********94EA95032,
X-QF-SIGN: 3b020a6349646684ebeeb0ec2cd3d1fb
}
Request Body:
{
expired_time=10&goods_name=qfpay&limit_pay=no_credit&mchid=R1zQrTdJnn&out_trade_no=Native20190722145741431794b8d1&pay_type=800201&txamt=20&txcurrcd=HKD&txdtm=2019-07-22 14:57:42&udid=AA
}
```
--------------------------------
### Initialize QFPay Element Object for UI Components
Source: https://sdk.qfapi.com/docs/online-shop/paymentelement
Demonstrates the initialization of the QFPay Element object, essential for rendering UI components. A critical note is included regarding the avoidance of `` tag nesting for the Element container.
```JavaScript
const qfpay = QFpay.config()
const elements = qfpay.element()
```