• Stars
    star
    412
  • Rank 104,736 (Top 3 %)
  • Language
    PHP
  • Created over 2 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Alipay global Third Party SDK with Authorization and Auto debit. Alipay 国际版 A+ 接口第三方 PHP SDK,实现了现金支付、用户授权、自动代扣和 RSA2 加密异步通知应答,示例完整,使用简单

Alipay Global SDK PHP

Alipay Global A+ SDK

This project is based on Alipay Global Offical PHP SDK
Since official SDK mainly shows how to access the alipay gateway and does not contain complete functions such as authorization and auto debit, I have added some logic and further realized the standard interface of Alipay Global A+

Attention!

0.0.3+: sendNotifyResponse sendNotifyResponseWithRSA are methods of $notify, eg:

$notify = $alipayGlobal->getNotify();
$notify->sendNotifyResponse(); // $alipayGlobal->sendNotifyResponse() is desprecated
$notify->sendNotifyResponseWithRSA(); // $alipayGlobal->sendNotifyResponseWithRSA() is desprecated
/* getNotifyResponse and getNotifyResponseWithRSA are added,
   so you can process it by yourself in memory frameworks like Webman */
$notifyResponseWithRSA =  $notify->getNotifyResponse();
$notifyResponseWithRSA =  $notify->getNotifyResponseWithRSA();

Demo

The use and functionality of the SDK have been shown with Examples in the project folder

Use

composer require mantoufan/alipay-global-sdk-php

How to use

Initialize

$alipayGlobal = new Mantoufan\AliPayGlobal(array(
    'client_id' => 'SANDBOX_5Y3A2N2YEB3002022', // Client ID
    'endpoint_area' => 'ASIA', // Optional: NORTH_AMERIA / ASIA / EUROPE
    'merchantPrivateKey' => '', // Merchant Private Key
    'alipayPublicKey' => '', // Alipay Public Key
    'is_sandbox' => true, // Whether to use the Sandbox environment
));

Required fields will be mark with *

Online payment - Payment - Pay (Cashier Payment)

API: ac/ams/payment_cashier
DEMO: pay/cashier

use Mantoufan\model\CustomerBelongsTo;
use Mantoufan\model\TerminalType;
try {
  $result = $alipayGlobal->payCashier(array(
      'customer_belongs_to' => CustomerBelongsTo::ALIPAY_CN, // * Users pay with Alipay Chinese wallet,Optional: ALIPAY_CN / ALIPAY_HK / TRUEMONEY / TNG / GCASH / DANA / KAKAOPAY / EASYPAISA / BKASH
      'notify_url' => '', // Asynchronous callback Url
      'return_url' => '', // Synchronize callback Url
      'amount' => array(
          'currency' => 'USD', // Currency of payment
          'value' => '1', // Amount of payment
      ),
      'order' => array(
          'id' => null, // Order No
          'desc' => 'Order Desc', // Order Description
          'extend_info' => array(
              'china_extra_trans_info' => array(
                  'business_type' => 'MEMBERSHIP', // Business Type of Order
              ),
          ),
      ),
      'payment_request_id' => null, // Cash payments could be null
      'settlement_strategy' => array(
          'currency' => 'USD', // Currency used for settlement
      ),
      'terminal_type' => TerminalType::WEB, // * Optional: WEB / WAP / APP
      'os_type' => null, // OS System Type
  ));
  header('Location: ' . $result->normalUrl); // Return URL of the alipay cashier
} catch (Exception $e) {
  echo $e->getMessage(); // Output Error
}

Online Payment - Authorization - Consult

API: ac/ams/authconsult
DEMO: auth/consult

use Mantoufan\tool\IdTool;
use Mantoufan\model\ScopeType;
use Mantoufan\model\TerminalType;
$auth_state = IdTool::CreateAuthState();
try {
    $result = $alipayGlobal->authConsult(array(
        'customer_belongs_to' => CustomerBelongsTo::ALIPAY_CN, // * Users pay with Alipay Chinese wallet,Optional: ALIPAY_CN / ALIPAY_HK / TRUEMONEY / TNG / GCASH / DANA / KAKAOPAY / EASYPAISA / BKASH
        'auth_client_id' => null, // Unique ID of the secondary merchant
        'auth_redirect_url' => '', // * URL that User is redirected to after User agrees to authorize
        'scopes' => array(ScopeType::AGREEMENT_PAY), // * Optional AGREEMENT_PAY / BASE_USER_INFO / USER_INFO / USER_LOGIN_ID / HASH_LOGIN_ID / SEND_OTP
        'auth_state' => $auth_state, // * It will be returned when User agrees to authorize needs to be guaranteed
        'terminal_type' => TerminalType::WEB, // * Optional: WEB / WAP / APP
        'os_type' => null, // OS System Type
    ));
    header('Location: ' . $result->normalUrl); // Return URL of User Authorization page With authCode
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online Payment - Authorization - ApplyToken - Using AuthCode

API: ac/ams/accesstokenapp
DEMO: auth/apply_token/auth_code

use Mantoufan\model\CustomerBelongsTo;
use Mantoufan\model\GrantType;
$auth_code = $_GET['authCode'] ?? '';
try {
    $result = $alipayGlobal->authApplyToken(array(
        'grant_type' => GrantType::AUTHORIZATION_CODE, // * Value should be AUTHORIZATION_CODE
        'customer_belongs_to' => CustomerBelongsTo::ALIPAY_CN, // * Users pay with Alipay Chinese wallet,Optional: ALIPAY_CN / ALIPAY_HK / TRUEMONEY / TNG / GCASH / DANA / KAKAOPAY / EASYPAISA / BKASH
        'auth_code' => $auth_code, // * AuthCode get from return URL of User Authorization page
        'refresh_token' => null, // Just leave null
    ));

    $access_token = $result->accessToken; // Access token is used for Aduto Debit
    $access_token_expiry_time = $result->accessTokenExpiryTime; // Access token expiry time
    $refresh_token = $result->refreshToken; // Refresh token is used for update access token
    $refresh_token_expiry_time = $result->refreshTokenExpiryTime; // Refresh token expiry time
    session_start(); // Start Session
    $_SESSION['access_token'] = $access_token; // Store Accesstoken in session
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online Payment - Authorization - ApplyToken - Using RefreshToken

API: ac/ams/accesstokenapp
DEMO: auth/apply_token/refresh_token

use Mantoufan\model\CustomerBelongsTo;
use Mantoufan\model\GrantType;
$refresh_token = $_GET['refreshToken'] ?? '';
try {
    $result = $alipayGlobal->authApplyToken(array(
        'grant_type' => GrantType::REFRESH_TOKEN, // * Value should be REFRESH_TOKEN
        'customer_belongs_to' => CustomerBelongsTo::ALIPAY_CN, // * Users pay with Alipay Chinese wallet,Optional: ALIPAY_CN / ALIPAY_HK / TRUEMONEY / TNG / GCASH / DANA / KAKAOPAY / EASYPAISA / BKASH
        'auth_code' => null, // Just leave null
        'refresh_token' => $refresh_token, // * RefreshToken get from authApplyToken Using AuthCode
    ));

    $access_token = $result->accessToken; // Access token is used for Aduto Debit
    $access_token_expiry_time = $result->accessTokenExpiryTime; // Access token expiry time
    $refresh_token = $result->refreshToken; // Refresh token is used for update access token
    $refresh_token_expiry_time = $result->refreshTokenExpiryTime; // Refresh token expiry time
    session_start(); // Start Session
    $_SESSION['access_token'] = $result->accessToken; // Store Accesstoken in session
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online payment - Payment - Pay (Auto Debit)

API: ac/ams/payment_agreement
DEMO: pay/agreement

try {
    session_start();
    $result = $alipayGlobal->payAgreement(array(
        'notify_url' => '', // Asynchronous callback Url
        'return_url' => '', // Synchronous callback Url
        'amount' => array(
            'currency' => 'USD', // Currency of payment
            'value' => '1', // Amount of payment
        ),
        'order' => array(
            'id' => null, // Order No
            'desc' => 'Order Desc', // Order Description
            'extend_info' => array(
                'china_extra_trans_info' => array(
                    'business_type' => 'MEMBERSHIP', // Business Type of Order
                ),
            ),
        ),
        'goods' => array(
            array(
                'id' => null, // Goods ID
                'name' => 'Goods Name', // Goods Name
                'category' => null, // Goods Category
                'brand' => null, // Goods Brand
                'unit_amount' => null, // Goods Charge Unit
                'quantity' => null, // Goods Quantity
                'sku_name' => null, // Goods SKU Name
            ),
        ),
        'merchant' => array( // Secondary merchant Info
            'MCC' => null,
            'name' => null,
            'display_name' => null,
            'address' => null,
            'register_date' => null,
            'store' => null,
            'type' => null,
        ),
        'buyer' => array( // Buyer Info
            'id' => null, // Buyer ID
            'name' => array(
                'first_name' => 'David', // * Buyer First Name
                'last_name' => 'Chen', // * Buyer Last Name
            ),
            'phone_no' => null, // Buyer Phone Number
            'email' => null, // Buyer Email
        ),
        'payment_request_id' => null, // Auto Debit payments could be null
        'payment_method' => array(
            'payment_method_type' => CustomerBelongsTo::ALIPAY_CN, // * Users pay with Alipay Chinese wallet,Optional: ALIPAY_CN / ALIPAY_HK / TRUEMONEY / TNG / GCASH / DANA / KAKAOPAY / EASYPAISA / BKASH
            'payment_method_id' => $_SESSION['access_token'], // * AccessToken returned by applyToken
        ),
        'settlement_strategy' => array(
            'currency' => 'USD', // Currency used for settlement
        ),
        'terminal_type' => TerminalType::WEB, // * Optional: WEB / WAP / APP
        'os_type' => null, // OS Type
    ));
    var_dump($result); // Output Result
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online payment - Payment - NotifyPayment

API: ac/ams/paymentrn_online
DEMO: notify

try {
    /* Get Asynchronous Payment Notifications */
    $notify = $alipayGlobal->getNotify();
    /* Default Value same as:
    $notify = $alipayGlobal->getNotify(array(
        'httpMethod' => $_SERVER['REQUEST_METHOD'],
        'path' => $_SERVER['REQUEST_URI'],
        'clientId' => $_SERVER['HTTP_CLIENT_ID'],
        'rsqTime' => $_SERVER['HTTP_REQUEST_TIME'],
        'rsqBody' => file_get_contents('php://input'),
        'signature' => $_SERVER['HTTP_SIGNATURE']
    ));*/
    /* Webman Example:
    $notify = $alipayGlobal->getNotify(array(
        'httpMethod' => $request->method(),
        'path' => $request->uri(),
        'clientId' => $request->header('client-id'),
        'rsqTime' => $request->header('request-time'),
        'rsqBody' => $request->rawBody(),
        'signature' => $request->header('signature')
    ));*/

    // Do something

    // Method 1: use header () and echo response
    $notify->sendNotifyResponseWithRSA(); // Tell Alipay Global the notice has been received and there is no need to send it again

    // Method 2: Or Get headers and body, process it by yourself
    $notifyResponseWithRSA =  $notify->getNotifyResponseWithRSA();
    // Webman Example:
    // response($notifyResponseWithRSA['body'], 200, $notifyResponseWithRSA['headers']);
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online Payment - Authorization - NotifyAuthorization

API: ac/ams/notifyauth
DEMO: notify/auth/auth_code

try {
    /* Get Asynchronous Payment Notifications */
    $notify = $alipayGlobal->getNotify();
    /* Default Value same as:
    $notify = $alipayGlobal->getNotify(array(
        'httpMethod' => $_SERVER['REQUEST_METHOD'],
        'path' => $_SERVER['REQUEST_URI'],
        'clientId' => $_SERVER['HTTP_CLIENT_ID'],
        'rsqTime' => $_SERVER['HTTP_REQUEST_TIME'],
        'rsqBody' => file_get_contents('php://input'),
        'signature' => $_SERVER['HTTP_SIGNATURE']
    ));*/
    /* Webman Example:
    $notify = $alipayGlobal->getNotify(array(
        'httpMethod' => $request->method(),
        'path' => $request->uri(),
        'clientId' => $request->header('client-id'),
        'rsqTime' => $request->header('request-time'),
        'rsqBody' => $request->rawBody(),
        'signature' => $request->header('signature')
    ));*/

    // Do something

    $rsqBody = $notify->getRsqBody(); // Get Response Body of Notification
    $authorization_notify_type = $reqBody->authorizationNotifyType; // Determine Notification Type
    if ($authorization_notify_type === 'AUTHCODE_CREATED') { // If Notification Type is sent AuthCode
        $_SESSION['auth_code'] = $reqBody->authCode; // Get AuthCode
    }

    // Method 1: use header () and echo response
    $notify->sendNotifyResponseWithRSA(); // Tell Alipay Global the notice has been received and there is no need to send it again

    // Method 2: Or Get headers and body, process it by yourself
    $notifyResponseWithRSA =  $notify->getNotifyResponseWithRSA();
    // Webman Example:
    // response($notifyResponseWithRSA['body'], 200, $notifyResponseWithRSA['headers']);
} catch (Exception $e) {
    echo $e->getMessage(); // Output Error
}

Online Payment - Refund - Refund

API: ac/ams/refund_online
DEMO: refund/refund_online

try {
    $result = $alipayGlobal->sendRefund(array(
        'paymentId' => '20181129190741010007000000XXXX', // Unique ID assigned by Alipay for the original payment to be refunded.
        'refundRequestId' => 'S7mMoYxQxWjJDWwm2NG4WxmNbM5z3GvSB6PEPvMeYP21PQUtrX9hXlgbQMajt2on', // Unique ID assigned by the merchant to identify a refund request.
        'refundAmount' => array(
            'currency' => 'USD', // Currency of refund
            'value' => '100', // Amount of refund
        )
    ));
    var_dump($result);
} catch (Exception $e) {
    echo $e->getMessage();
}

Return Url

DEMO: return

/** Return immediately after payment or authorization
 * After Payment, user will be redirected only
 * After Authorization, user will be redirected with authCode
 * Suggestion: The Return URL is only used as a reminder
 * It's beter to process business in asynchronous payment notification and asynchronous authorization notification
**/
echo 'Payment Or Authorization completed';

More Repositories

1

yzhanProxy

Web reverse proxy with automatic SSL, LFU caching, command-line configuration 支持自动配置 SSL 证书、LFU 缓存、用命令行配置的 Web 反向代理服务器
Go
295
star
2

yzhanDanmu

CSS-only bullet screen plugin. Any height, length, speed. Multiple non-overlapping strategies. High efficiency, minimal size (2kb). Channel algorithm patented. 纯 CSS 弹幕插件,任意高度、长度、速度弹幕铺满屏幕,多种不重叠策略,高效极简(2kb)。通道算法受专利权保护。
JavaScript
280
star
3

yzhanPay

简洁、高效的多用户、多语言、用插件扩展的聚合支付系统,已集成 Alipay China, Alipay Global 和 Paypal
PHP
234
star
4

yzhanJSInterpreter

A JavaScript Interpreter Using JS itself. JavaScript 解释器,包含词法分析、语法解析和执行。基于 LR 实现 eval
JavaScript
213
star
5

yzhanWeather

Pure CSS animation for sakura, rain, snow, firefly and butterfly effects, high performance without affecting SEO. 纯 CSS 动画实现樱花、雨、雪、萤火虫和蝴蝶飞舞背景效果,高性能且不影响 SEO
JavaScript
154
star
6

yzhanHTMLParser

A streaming HTML parser based on HTML Standard. 基于 HTML 标准的流式 HTML 解析器
HTML
108
star
7

mtfLive

MTF直播导航源码,将斗鱼、虎牙、触手、YY、龙珠、战旗、章鱼、电视直播按分类/关键词聚合,用户选择分类,可以观看到全网该关键词下正在直播的内容。
PHP
68
star
8

yzhanIP

Crawl, match, parse IP or IP range, check if IP or range is in another range. Support IPv4, IPv6, IP Interval, Wildcard and CIDR. Check if IP is Cloudflare node IP, Google bot IP. 爬取,正则匹配,解析 IP 和 IP 范围,检测 IP 或范围是否在另一个范围中。支持 IPv4,IPv6,区间、通配符或 CIDR 表示的 IP 范围。检测 IP 是否是 Cloudflare 节点或 Google 漫游器 IP
PHP
58
star
9

yZhanCrop

仿 PS 多图层的图片选择、缩放、旋转、裁剪、导出 JS 库 Crop images by dragging, zooming, tilting and rotating them.
JavaScript
56
star
10

yzhanBG

Use multiple videos, images, and weather as background, with mute, hide, text, and cherry blossom, rain, snow, firefly, and butterfly animations. 用多个视频、图片、天气作背景,支持静音、隐藏内容、文字,以及樱花、雨、雪、萤火虫和蝴蝶动画
JavaScript
55
star
11

yzhanNotify

Element and Global Notifications / Toasts with Pure / Vanilla / Native JavaScript. 使用原生 JavaScript 在视窗或元素的指定位置发送通知和提示。
CSS
41
star
12

yzhanCache

Simple, efficient cache for php. 简单、高效的 PHP 缓存类
PHP
38
star
13

yzhanGateway

Developing PHP SDK for any API. 为任何 API 快速开发 PHP SDK
PHP
38
star
14

mtfScrollList

MTF滚动列表插件,支持虚拟化无限滚动,上拉到顶,下拉到底加载更多,下拉刷新。可在原生JS、React和Vue(未来)中使用
JavaScript
36
star
15

yzhanImageViewer

给网站和H5应用增加 像微信朋友圈一样 的看图功能,可看大图,双击双指缩放,滑动切换图片,点击返回。A jQuery Plugin for viewing pictures like Wechat moments.
JavaScript
27
star
16

mtfCOM

mtf 通用组件库,包含多个 PHP 模块和 JavaScript 模块,其中以 mtf 或 yzhan 开头模块,为自有模块,其它为第三方模块。这些模块可独立或组合使用,无需为某一个功能而引入整个框架。
PHP
10
star
17

yzhanCluster

Sources of depolyment yamls and static files for yzhan
JavaScript
8
star
18

mtfSTGMaker

MTF射击游戏生成器,封装角色、装备、碰撞检测、资源预加载、键盘和触屏操控等底层实现,帮助您快速开发射击游戏
JavaScript
7
star
19

mzhanSub

M站字幕组翻译的字幕,包括每周五更新的《3D坦克周报》。不定期更新的《TankiX开发日志》和《可爱女生发型系列视频教程》
6
star
20

yzhanCodeSpace

This is a space for me to investigate Souce Code of Vue.js / React / Webpack / Rollup etc.
JavaScript
2
star
21

yzhanReactResponsiveContent

A powerful and flexible React component for creating responsive content with automatic media query generation. 为响应式内容自动生成媒体查询
TypeScript
2
star
22

yzhanAPI

MTF接口:二维码识别、图片倾斜校正、短链接生成、清晰度增强、答题卡识别和正版验证
PHP
2
star
23

yzhanModal

A jQuery plugin to show a modal dialog with support for iframes
JavaScript
1
star
24

shopxoplugin

shopXO plugin by xiaoyu
HTML
1
star
25

yzhanGoRun

Write once, run everywhere
Go
1
star
26

yZhanWeather

Y站天气库,动态生成雪、雨、光、樱花、蝴蝶和气泡效果,可作为H5活动页的装饰动画和背景。
1
star