生成移动端浏览器支付宝授权跳转地址

JS

var merchantAppId = '你的商户APPID';
var redirectUri = encodeURIComponent('https://你的域名/api/alipay/callback');
var state = encodeURIComponent('你的业务参数');

// 1. 真正的支付宝授权地址
var authUrl = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm'
    + '?app_id=' + merchantAppId
    + '&scope=auth_base'
    + '&redirect_uri=' + redirectUri
    + '&state=' + state;

// 2. 外层 scheme,注意这里 appId 固定是 20000067,不是你的商户 appid
var scheme = 'alipays://platformapi/startapp?appId=20000067&url=' + encodeURIComponent(authUrl);

// 3. 外部浏览器兜底短链
var openUrl = 'https://ds.alipay.com/?scheme=' + encodeURIComponent(scheme);

// 4. 跳转
location.href = openUrl;

PHP函数

function buildAlipayDsAuthUrl($redirectUri = '', $state = 'init')
{
    // 你的支付宝应用APPID(固定)
    $merchantAppId = '你的商户APPID';

    // 默认回调地址
    if ($redirectUri === '' || $redirectUri === null) {
        throw new \InvalidArgumentException("回调地址不能为空");
    }

    // 默认 state
    if ($state === '' || $state === null) {
        $state = 'init';
    }

    // 内层真实授权地址:这里用 auth_base 即可拿 user_id
    $authUrl = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm'
        . '?app_id=' . $merchantAppId
        . '&scope=auth_base'
        . '&redirect_uri=' . rawurlencode($redirectUri)
        . '&state=' . rawurlencode($state);

    // 外层支付宝唤起协议,appId 固定 20000067
    $scheme = 'alipays://platformapi/startapp?appId=20000067&url=' . rawurlencode($authUrl);

    // 最终输出 https://ds.alipay.com/xxxx
    return 'https://ds.alipay.com/?scheme=' . rawurlencode($scheme);
}
posted @ 2026-03-27 15:42  _迷途  阅读(6)  评论(0)    收藏  举报