官方网站:https://developer.authorize.net/
开发者文档:https://developer.authorize.net/api/reference/index.html
一、注册沙箱账号进行调试
注册成功之后会弹出你的沙箱账号信息
API LOGIN ID
48h4xxxxxePS
TRANSACTION KEY
4S9xxxxxxxxxx8Aq
KEY
Simon
其中 API LOGIN ID 跟 TRANSACTION KEY 是需要程序使用的,保存下来
如果秘钥忘记了,可以去账户里面重置
ACCOUNT -> Settings -> API Credentials & Keys
里面可以看到Login Id
其中的秘钥生成有两种类型 New Transaction Key 跟 New Signature Key
第一种是直接交易使用,第二种是托管表单使用
composer安装SDK
composer require authorizenet/authorizenet
github上有案例可以参考
地址:https://github.com/AuthorizeNet/sample-code-php
使用信用卡支付的方式
前端页面表单提交传递 信用卡号,到期时间,安全码三个参数
判断支付成功之后直接修改数据表的状态
/**
* 信用卡支付
* $pay = new AuthorizePay();
* $result = $pay->chargeCreditCard(1.45);
* @param $cardData
* @param $AddressData
* @param $userData
* @param $orderData
* @return bool|string
*/
public function chargeCreditCard($cardData,$AddressData,$userData,$orderData){
$refId = 'ref'.time();
//创建信用卡账户
$creditCard = new CreditCardType();
$creditCard->setCardNumber($cardData['cardno']); //信用卡号
$creditCard->setExpirationDate($cardData['deadtime']); //信用卡到期时间
$creditCard->setCardCode($cardData['cardcode']); //卡代码
//创建支付对象
$paymentOne = new PaymentType();
$paymentOne->setCreditCard($creditCard);
//创建订单信息
$order = new OrderType();
//$order->setInvoiceNumber("10101"); //发票编号
$order->setDescription("Grfresh Order ".date("d/m/Y H:i:s",time())); //订单说明
//设置账单地址,收货地址
$customerAddress = new CustomerAddressType();
$customerAddress->setFirstName($AddressData['alias']);
$customerAddress->setLastName($AddressData['consignee']);
$customerAddress->setCompany($AddressData['alias']);
$customerAddress->setAddress($AddressData['address']);
$customerAddress->setCity($AddressData['city_name']);
$customerAddress->setState($AddressData['province_name']);
$customerAddress->setZip($AddressData['zip_code']);
$customerAddress->setCountry($AddressData['country']);
/*
addeess:1 Cromwell CT,
city:Princeton
state: NJ
zipcode: 08540
country: USA
*/
//设置用户信息
$customerData = new CustomerDataType();
$customerData->setType("individual");
$customerData->setId($userData['id'].'_'.time()); //用户id
$customerData->setEmail($userData['user_email']); //用户邮箱
//为事物设置值
/*$duplicateWindowSetting = new SettingType();
$duplicateWindowSetting->setSettingName("duplicateWindow");
$duplicateWindowSetting->setSettingValue("60");*/
//设置商家的自定义字段
/* $merchantDefinedField = new UserFieldType();
$merchantDefinedField->setName("customerLoyaltyNum");
$merchantDefinedField->setValue("1128836273");*/
//创建request对象
$transactionRequestType = new TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction"); //交易类型
$transactionRequestType->setAmount($orderData['total_amount']);
$transactionRequestType->setOrder($order);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setBillTo($customerAddress);
$transactionRequestType->setCustomer($customerData);
//$transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
//$transactionRequestType->addToUserFields($merchantDefinedField);
//组装完整的事物请求
$request = new CreateTransactionRequest();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
//var_dump($request);echo "<br><br>";
//获取响应
$controller = new CreateTransactionController($request);
//var_dump($controller);echo "<br><br>";
$response = $controller->executeWithApiResponse($this->url);//ANetEnvironment::PRODUCTION
//var_dump($response);
if ($response != null) {
if($response->getTransactionResponse() == null){
return "No response returned ";
}
// Check to see if the API request was successfully received and acted upon
if ($response->getTransactionResponse()->getErrors() == null && $response->getMessages()->getResultCode() == "Ok") {
return true;
} else {
//这里是支付失败的回调
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
return $tresponse->getErrors()[0]->getErrorText();
} else {
return $response->getMessages()->getMessage()[0]->getText();
}
}
} else {
return "No response returned ";
}
}
使用托管表单的方式支付
下面地址讲的很清楚,结合官方文档对照看
参考地址:https://segmentfault.com/a/1190000010599644
整合了一些方法
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/9/15
* Time: 15:34
*/
namespace lib;
use net\authorize\api\constants\ANetEnvironment;
use net\authorize\api\contract\v1\CreateCustomerProfileRequest;
use net\authorize\api\contract\v1\CreateTransactionRequest;
use net\authorize\api\contract\v1\CreditCardType;
use net\authorize\api\contract\v1\CustomerAddressType;
use net\authorize\api\contract\v1\CustomerDataType;
use net\authorize\api\contract\v1\CustomerProfilePaymentType;
use net\authorize\api\contract\v1\CustomerProfileType;
use net\authorize\api\contract\v1\GetCustomerProfileRequest;
use net\authorize\api\contract\v1\GetHostedProfilePageRequest;
use net\authorize\api\contract\v1\MerchantAuthenticationType;
use net\authorize\api\contract\v1\OrderType;
use net\authorize\api\contract\v1\PaymentProfileType;
use net\authorize\api\contract\v1\PaymentType;
use net\authorize\api\contract\v1\SettingType;
use net\authorize\api\contract\v1\TransactionRequestType;
use net\authorize\api\contract\v1\UserFieldType;
use net\authorize\api\controller\CreateCustomerProfileController;
use net\authorize\api\controller\CreateTransactionController;
use net\authorize\api\controller\GetCustomerProfileController;
use net\authorize\api\controller\GetHostedProfilePageController;
class AuthorizePay
{
public $test_url = "https://apitest.authorize.net/xml/v1/request.api"; //沙箱地址
public $url = "https://api.authorize.net/xml/v1/request.api"; //生产地址
public $login_id = null; //MERCHANT_LOGIN_ID
public $key = null; //MERCHANT_TRANSACTION_KEY
public $merchantAuthentication = null;
public function __construct()
{
$this->login_id = "63xxxxxEt";
$this->key = "6FhLxxxxxxxx5TDy";
$this->merchantAuthentication = $this->createMerchant();
}
/**
* 信用卡支付
* $pay = new AuthorizePay();
* $result = $pay->chargeCreditCard(1.45);
* @param $cardData
* @param $AddressData
* @param $userData
* @param $orderData
* @return bool|string
*/
public function chargeCreditCard($cardData,$AddressData,$userData,$orderData){
$refId = 'ref'.time();
//创建信用卡账户
$creditCard = new CreditCardType();
$creditCard->setCardNumber($cardData['cardno']); //信用卡号
$creditCard->setExpirationDate($cardData['deadtime']); //信用卡到期时间
$creditCard->setCardCode($cardData['cardcode']); //卡代码
//创建支付对象
$paymentOne = new PaymentType();
$paymentOne->setCreditCard($creditCard);
//创建订单信息
$order = new OrderType();
//$order->setInvoiceNumber("10101"); //发票编号
$order->setDescription("Grfresh Order ".date("d/m/Y H:i:s",time())); //订单说明
//设置账单地址,收货地址
$customerAddress = new CustomerAddressType();
$customerAddress->setFirstName($AddressData['alias']);
$customerAddress->setLastName($AddressData['consignee']);
$customerAddress->setCompany($AddressData['alias']);
$customerAddress->setAddress($AddressData['address']);
$customerAddress->setCity($AddressData['city_name']);
$customerAddress->setState($AddressData['province_name']);
$customerAddress->setZip($AddressData['zip_code']);
$customerAddress->setCountry($AddressData['country']);
/*
addeess:1 Cromwell CT,
city:Princeton
state: NJ
zipcode: 08540
country: USA
*/
//设置用户信息
$customerData = new CustomerDataType();
$customerData->setType("individual");
$customerData->setId($userData['id'].'_'.time()); //用户id
$customerData->setEmail($userData['user_email']); //用户邮箱
//为事物设置值
/*$duplicateWindowSetting = new SettingType();
$duplicateWindowSetting->setSettingName("duplicateWindow");
$duplicateWindowSetting->setSettingValue("60");*/
//设置商家的自定义字段
/* $merchantDefinedField = new UserFieldType();
$merchantDefinedField->setName("customerLoyaltyNum");
$merchantDefinedField->setValue("1128836273");*/
//创建request对象
$transactionRequestType = new TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction"); //交易类型
$transactionRequestType->setAmount($orderData['total_amount']);
$transactionRequestType->setOrder($order);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setBillTo($customerAddress);
$transactionRequestType->setCustomer($customerData);
//$transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
//$transactionRequestType->addToUserFields($merchantDefinedField);
//组装完整的事物请求
$request = new CreateTransactionRequest();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
//var_dump($request);echo "<br><br>";
//获取响应
$controller = new CreateTransactionController($request);
//var_dump($controller);echo "<br><br>";
$response = $controller->executeWithApiResponse($this->url);//ANetEnvironment::PRODUCTION
//var_dump($response);
if ($response != null) {
if($response->getTransactionResponse() == null){
return "No response returned ";
}
// Check to see if the API request was successfully received and acted upon
if ($response->getTransactionResponse()->getErrors() == null && $response->getMessages()->getResultCode() == "Ok") {
return true;
} else {
//这里是支付失败的回调
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
return $tresponse->getErrors()[0]->getErrorText();
} else {
return $response->getMessages()->getMessage()[0]->getText();
}
}
} else {
return "No response returned ";
}
}
/**
* 创建一个身份验证对象
*/
public function createMerchant(){
$merchantAuthentication = new MerchantAuthenticationType();
$merchantAuthentication->setName($this->login_id);
$merchantAuthentication->setTransactionKey($this->key);
return $merchantAuthentication;
}
/**
* 用户申请CustomerProfileID
* @param $user
* @return string
*/
public function getCustomerProfileId($user){
$customerProfile = new CustomerProfileType();
$customerProfile->setDescription($user['description']);
$customerProfile->setMerchantCustomerId($user['customer_id']);
$customerProfile->setEmail($user['email']);
$request = new CreateCustomerProfileRequest();
$refId = 'ref' . time();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setRefId($refId);
$request->setProfile($customerProfile);
$controller = new CreateCustomerProfileController($request);
$response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX);
return $response->getCustomerProfileId();
}
/**
* 获取用户的支付信息
* @param $profileId
* @return \net\authorize\api\contract\v1\AnetApiResponseType
*/
public function getCustomProfileInfo($profileId){
$request = new GetCustomerProfileRequest();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setCustomerProfileId($profileId);
$controller = new GetCustomerProfileController($request);
$response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX);
return $response;
}
/**
* 创建发起支付
* @return
*/
public function createPayTransaction(){
$customer = $this->getCustomProfileInfo(session('profileId'));
$payment = $customer->getProfile()->getPaymentProfiles();
$paymentProfileId = $payment[0]->getCustomerPaymentProfileId();
$profileToCharge = new CustomerProfilePaymentType();
$profileToCharge->setCustomerProfileId(session('profileId'));
$paymentProfile = new PaymentProfileType();
$paymentProfile->setPaymentProfileId($paymentProfileId);
$profileToCharge->setPaymentProfile($paymentProfile);
$transactionRequestType = new TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount(1); // 支付的价格
$transactionRequestType->setProfile($profileToCharge);
$request = new CreateTransactionRequest();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setTransactionRequest( $transactionRequestType);
$controller = new CreateTransactionController($request);
$response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX);
//判断是否支付成功,成功返回order_sn ,失败返回信息;
if($response->getMessages()->getResultCode() == 'Ok'){
return ['code'=>1,'data'=>$customer->getProfile()->getMerchantCustomerId()];
}else{
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
return ['code'=>0,'msg'=> $tresponse->getErrors()[0]->getErrorText()];
} else {
return ['code'=>0,'msg'=> $response->getMessages()->getMessage()[0]->getText()];
}
}
//return $response;
}
/**
* 获取网页表单的授权token
* @param $customerProfileID
* @param $url string 接收处理相应的页面
* @return mixed
*/
public function getFormToken($customerProfileID,$url){
$setting = new SettingType();
$setting->setSettingName("hostedProfileIFrameCommunicatorUrl");
$setting->setSettingValue($url);
$request = new GetHostedProfilePageRequest();
$request->setMerchantAuthentication($this->merchantAuthentication);
$request->setCustomerProfileId($customerProfileID);
$request->addToHostedProfileSettings($setting);
$controller = new GetHostedProfilePageController($request);
$response = $controller->executeWithApiResponse(ANetEnvironment::PRODUCTION);
/*if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
{
echo $response->getToken()."\n";
}
else
{
echo "ERROR : Failed to get hosted profile page\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
}*/
return $response->getToken();
}
}