PHP使用支付宝SDK一点心得


PHP版的支付宝SDK有2个版本:

通用版

项目如果没有使用命名空间可以使用这个版本。

示例代码:

$aop = new AopClient ();
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = 'your app_id';
$aop->rsaPrivateKey = '请填写开发者私钥去头去尾去回车,一行字符串';
$aop->alipayrsaPublicKey='请填写支付宝公钥,一行字符串';
$aop->apiVersion = '1.0';
$aop->signType = 'RSA2';
$aop->postCharset='GBK';
$aop->format='json';
$request = new AlipayUserInfoShareRequest ();
$result = $aop->execute ( $request , $accessToken ); 

$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
$resultCode = $result->$responseNode->code;
if(!empty($resultCode)&&$resultCode == 10000){
echo "成功";
} else {
echo "失败";
}

Easy版

项目如果使用了命名空间可以使用这个版本,最大的好处,不需要手动引入类文件。

安装方法:

composer require alipaysdk/easysdk

示例代码:

require 'vendor/autoload.php';
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;

//1. 设置参数(全局只需设置一次)
Factory::setOptions(getOptions());

try {
    //2. 发起API调用(以支付能力下的统一收单交易创建接口为例)
    $result = Factory::payment()->common()->create("iPhone6 16G", "20200326235526001", "88.88", "2088002656718920");
    $responseChecker = new ResponseChecker();
    //3. 处理响应或异常
    if ($responseChecker->success($result)) {
        echo "调用成功". PHP_EOL;
    } else {
        echo "调用失败,原因:". $result->msg.",".$result->subMsg.PHP_EOL;
    }
} catch (Exception $e) {
    echo "调用失败,". $e->getMessage(). PHP_EOL;;
}

function getOptions()
{
    $options = new Config();
    $options->protocol = 'https';
    $options->gatewayHost = 'openapi.alipay.com';
    $options->signType = 'RSA2';
    
    $options->appId = '<-- 请填写您的AppId,例如:2019022663440152 -->';
    
    // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
    $options->merchantPrivateKey = '<-- 请填写您的应用私钥,例如:MIIEvQIBADANB ... ... -->';
    
    $options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径,例如:/foo/alipayCertPublicKey_RSA2.crt -->';
    $options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径,例如:/foo/alipayRootCert.crt" -->';
    $options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径,例如:/foo/appCertPublicKey_2019051064521003.crt -->';
    
    //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
    // $options->alipayPublicKey = '<-- 请填写您的支付宝公钥,例如:MIIBIjANBg... -->';

    //可设置异步通知接收服务地址(可选)
    $options->notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址,例如:https://www.test.com/callback -->";

    return $options;
}

这个版本唯一的缺点就是,有很多没有代码示例,需要自己理解使用。

示例代码一:提供了现成的方法调用

alipay.system.oauth.token(换取授权访问令牌)

// 初始化
Factory::setOptions(getOptions());
// 获取access token
try {
    $result = Factory::base()->oauth()->getToken($authCode);
    $responseChecker = new ResponseChecker();
    if ($responseChecker->success($result)) {
        $resultArr = json_decode($result->httpBody, true);
        print_r($resultArr);
    } else {
      echo "调用失败,原因:". $result->msg.",".$result->subMsg.PHP_EOL;
    } catch (Exception $e) {
        echo "调用失败,". $e->getMessage(). PHP_EOL;
    }
}

示例代码二:没有提供了现成的方法调用,则需要使用Factory::util()->generic()->execute()方法去调用

alipay.user.info.share(支付宝会员授权信息查询接口)

$result = Factory::util()->generic()->execute('alipay.user.info.share',[
        'auth_token' => ''
    ],
    []
);

第一个参数:OpenAPI的名称,例如:alipay.user.info.share

第二个参数:没有包装在`biz_content`下的请求参数数组。

第三个参数:包装在`biz_content`下的请求参数数组。

返回结果说明:

print_r($result);

打印结果

Alipay\EasySDK\Util\Generic\Models\AlipayOpenApiGenericResponse Object
(
    [_name:protected] => Array
        (
            [httpBody] => http_body
            [code] => code
            [msg] => msg
            [subCode] => sub_code
            [subMsg] => sub_msg
        )

    [_required:protected] => Array
        (
        )

    [httpBody] => {"alipay_user_info_share_response":{"code":"10000","msg":"Success","age":"64","avatar":"https:\/\/tfs.alipayobjects.com\/images\/partner\/https:\/\/mdn.alipayobjects.com\/sandboxsys\/afts\/img\/AibKQZxFsLUAAAAAAAAAAAAADgSLAQBr\/original","cert_no":"561901196007233740","cert_type":"0","city":"资阳市","country_code":"CN","deliver_addresses":[{"address_code":"512000","default_deliver_address":"F","deliver_city":"资阳市","deliver_province":"四川省"}],"display_name":"pafmms5825@sandbox.com","email":"pafmms5825@sandbox.com","firm_agent_person_cert_type":"10","firm_legal_person_cert_type":"10","firm_type":"CO","inst_or_corp":"N","is_adult":"T","is_blocked":"F","is_certified":"T","is_student_certified":"F","license_no":"561901196007233740","member_grade":"unknown","mobile":"10900000001","nick_name":"沙箱账号","province":"四川省","user_name":"pafmms5825@sandbox.com","user_status":"T","user_type":"1","open_id":"01348t5fKqEymiasr00b6695ly2-8Ry6a0hfAKxT16WLVEc"},"sign":"g4UFAc6T1f/z5nfGUV9ahVH4TQetaCywFy+YXTDVijxMZzPKy/2QET6P2IsGZEe/YvaG6vDH9C03bVp/jmTDBoiA4T8nUxPBiX13zyMT4IXSxXAUMjpNIuJ4GkAFzSmwVdQh4+oyfM3lYkFOYBQHBu/Mf+rm6zxbDUm2PP/rivtFa2ZJ4Cqjp/mCg1hDbWfhryDCYztkyKQxJ8nU/q+u11cVt30ft+mEqGnof5vqMnSGkFry53TSdcoUoDy6SxLBM1o7h6rhBoRo2w6Ak7e1ss14qUx3zxx67biJhnu3SM3CfCEvPHV4b72M832lZlPrXOD9sr9fS2K3C7Yc2GHSqw=="}
    [code] => 10000
    [msg] => Success
    [subCode] => 
    [subMsg] => 
)

返回结果参数说明:

httpBody:网关返回的HTTP响应,是一个JSON格式的字符串,开发者可按需从中解析出响应参数。

code:网关返回码。

msg:网关返回码描述。

subCode:业务返回码,参见具体的API接口文档。

subMsg:业务返回码描述,参见具体的API接口文档。