Alipay business account transfer to personal account

Preparation:

1: An enterprise Alipay account that has been registered for 90 days and has been authenticated with its real name.

2: You have successfully signed the contract and added the ability to transfer money to Alipay.

3: Possess the development ability of professional technicians or have a professional development team, and be able to understand official documents well.

4: There is an Alipay personal account that has been verified by real name, which is convenient for testing.

Alipay official reference documents:

Transfer to Alipay Account Product Introduction|Webpage & Mobile App Alipay Documentation Center https://opendocs.alipay.com/open/309/106235 Below, we will implement the transfer function step by step.

1: Use Alipay account to log in to the Alipay development platform, find the console --> My application --> Web page & mobile application (as shown in the figure)

If there is no application, create an application first, and the creation steps are ignored here. For details, please refer to the official documentation.

2: Click on the application to enter the application details.

Check whether the transfer to Alipay account has been added in the ability list , if not, you need to click the Add ability button to add. (as pictured)

Note: The APPID in the upper left corner of the picture needs to be temporarily recorded, and it will be used in the following code.

 Three: Configure the development settings.

Click the application information in the application details, as shown in the figure:

Notice:

1. The Alipay gateway address should be temporarily written down, it will be used in the following code.

2. Although it is optional for the application gateway to receive notifications asynchronously, in order to avoid unforeseen circumstances such as sudden network disconnection, power outages and other abnormal situations that cause synchronization information to be unable to be processed in time, it is best to configure the asynchronous notification here, and the order status The processing should also be placed in the asynchronous logical judgment, not when the result is returned synchronously.

3. The interface signing method must use the public key certificate method, as shown in the figure:

The CSR file used in the figure needs to download the Alipay Open Platform Development Assistant, and then generate it. For specific operations, please refer to step 4.

Four: Obtain the application public key, application private key, and CSR file.

Reference documents:

Generate and configure keys| Open Platform Alipay Documentation Center https://opendocs.alipay.com/common/02kdnc 1. Click the installation package in the picture below to install according to your computer system.

 2. Generate an application public key and an application private key.

3. Click to open the key file path to see the application private key and application public key files just generated. As shown in the picture:

Note that the public key and private key here will be used later in the code.

 

4. Click to open the file location, and you can see the obtained CSR file.

 5. Go back to the interface signing method page, first obtain the mobile phone verification code, then check the agreement agreement, and upload the csr file you just obtained. As shown in the picture:

6. After the upload is successful, Alipay will automatically generate the application public key certificate, Alipay public key certificate, and Alipay root certificate, as shown in the figure:

Click the corresponding download button to save locally for future use. The certificate file downloaded here is to be used in a formal environment.

Note: These three certificates will be used later in the code.

 Five: Download the SDK file.

Webpage & Mobile Application Learning Path | Webpage & Mobile Application Alipay Documentation Center https://opendocs.alipay.com/open/54/103419/ You can choose to download according to your own development language. 

After the download is complete, put the sdk file into the appropriate location of the project. Let's take the php version as an example, put it in the sdk folder, and name it alipay_dakuan.

 Six: Obtain the certificate file in the sandbox test environment. [If you don't need sandbox testing, please ignore this step]

1. Find the sandbox under My Apps --> Web & Mobile Apps, and click to enter. As shown in the picture:

 2. Obtain the APPID in the sandbox environment and save it for later use. [The appid here is different from the appid obtained in step 2]

Select the system default key for interface signing method.

[The advantage is that you can directly download the application public key certificate, Alipay root certificate, and Alipay public key certificate in the sandbox environment. If you choose a custom key, you need to obtain the Alipay public key, Alipay private key and csr through the Alipay open platform development assistant. file and upload the csr file to obtain three certificates, which saves one step.

Turn on certificate mode.

Copy and save the Alipay gateway address in the sandbox environment, which will be used in the following code.

 The asynchronous notification application gateway address also needs to be set [the asynchronous callback method was not used in the sandbox environment during the test here, and I don’t know why].

Click View after the certificate mode, as shown below:

 

 Copy and save the application private key, which will be used later in the code.

Click the download certificate in the figure to download the application public key certificate, Alipay public key certificate, and Alipay root certificate in the sandbox environment to the local storage, which will be used in the following code. [Note: The three certificates downloaded here are certificates in the sandbox environment, do not mix with the certificates in the official environment downloaded in steps 4 and 6 before]

In the code environment, create a sandbox folder [the text is named at will, because it is a certificate in the sandbox environment, so it is named sandbox, see the word meaning], and put the three sandbox environment certificates into this folder.

As shown below:

Click Sandbox account: View merchant account and buyer account, which will be used in the following code.

Pay attention to the balance at this time. After the code test is normal, the balance here will change.

Seven: Configure the official environment certificate:

Create a new formal folder under the project sdk/alipay_dakuan folder, and put the three certificates in the formal environment downloaded above in this folder.

 Eight: code test:

1. In the case of Alipay open platform user login, visit the following URL

https://opensupport.alipay.com/support/codelab/detail/488/552?ant_source=opendoc Ant Technical Support Center is committed to providing developers with various capabilities and industry solutions for small programs. You can find developers here Various capabilities, help and services needed by service providers and channel providers https://opensupport.alipay.com/support/codelab/detail/488/552?ant_source=opendoc Click Next to view the preparations for your own development Is everything in place? If the system prompts that some information is not configured, please refer to the previous steps to process the configuration and the obtained information.

2. When you click on step ④ to configure the development environment, choose according to your own project development language needs.

3. In step ⑤, select the required access interface tab, click the transfer Alipay account column, and you can see the introduction of the key input parameters and key output parameters required by the interface on the right side. Click the code example on the right side, we can See the code corresponding to the selected programming language, the code here is what we will use.

 Because the initial package structure of the sdk we downloaded is like this, the path used when referencing the sdk in the sample code is aop/...

When we decompress the sdk package file, put the files in aop into the project, and the path of the folder is changed to sdk/alipay_dakuan [introduced above], so the reference path used in our project needs to follow the actual path to modify.

Referring to the following documents, we can know that the API interface for transfer to Alipay account request is alipay.fund.trans.uni.transfer

Then, when we instantiate the request class, we should write it as AlipayFundTransUniTransferRequest [Here is just a knowledge point to remind you, this is the same way to generate request classes when other methods in this sdk are called]

Overview|Webpage & Mobile App Alipay Documentation Center https://opendocs.alipay.com/open/02np93

 Create a test file and process the above code [Both the official environment certificate and the sandbox environment certificate are integrated in the project, which is convenient for two aspects of testing]

public function test(){
        
        //API_ROOT 是框架常量,可以根据自己实际项目文件路径改为以/开头的根路径
    	require_once API_ROOT.'/../sdk/alipay_dakuan/AopCertClient.php';
    	require_once API_ROOT.'/../sdk/alipay_dakuan/request/AlipayFundTransUniTransferRequest.php';

    	$is_sandbox=1; //沙盒环境 1/正式环境开关 0

    	// 初始化
		$aop = new AopCertClient;


		//沙盒环境下
		if($is_sandbox){
			//沙盒支付宝网关地址
			$gateway_url="https://openapi.alipaydev.com/gateway.do";
			//沙盒appid
			$appid="2021**********00"; //【替换为自己的沙箱appid】
			//沙盒应用私钥
			$private_key='MIIEv**********ERWc='; //替换为自己沙盒环境下的应用私钥
			//沙盒应用公钥证书路径,下载后保存位置的绝对路径
			$appCertPath = API_ROOT.'/../sdk/alipay_dakuan/sandbox/appCertPublicKey_2021000118693500.crt'; //【上面讲解中有截图,可对照,替换为自己的文件名】
			//沙盒支付宝公钥证书路径,下载后保存位置的绝对路径 
			$alipayCertPath = API_ROOT.'/../sdk/alipay_dakuan/sandbox/alipayCertPublicKey_RSA2.crt'; //【上面讲解中有截图,可对照,替换为自己的文件名】
			//沙盒支付宝根证书路径,下载后保存位置的绝对路径
			$rootCertPath = API_ROOT.'/../sdk/alipay_dakuan/sandbox/alipayRootCert.crt'; //【上面讲解中有截图,可对照,替换为自己的文件名】

		}else{ //正式环境下

			//正式支付宝网关地址
			$gateway_url="https://openapi.alipay.com/gateway.do";
			//正式appid
			$appid="20180*********34"; //【替换为自己的应用appid】
			//正式应用私钥
			$private_key='MIIEvA********smclBNQ=='; //替换为自己正式环境下的应用私钥【这里的私钥最好以文件形式存储,不要写死在代码中防止泄露造成经济损失】
			//正式应用公钥证书路径,下载后保存位置的绝对路径
			$appCertPath = API_ROOT.'/../sdk/alipay_dakuan/formal/appCertPublicKey_2018012602080134.crt'; //【替换为自己正式环境下载的应用公钥证书在项目中的路径】
			//正式支付宝公钥证书路径,下载后保存位置的绝对路径
			$alipayCertPath = API_ROOT.'/../sdk/alipay_dakuan/formal/alipayCertPublicKey_RSA2.crt'; //【替换为自己正式环境下载的支付宝公钥证书在项目中的路径】
			//正式支付宝根证书路径,下载后保存位置的绝对路径
			$rootCertPath = API_ROOT.'/../sdk/alipay_dakuan/formal/alipayRootCert.crt'; //【替换为自己正式环境下载的支付宝根证书在项目中的路径】
		}

		$aop -> gatewayUrl=$gateway_url;

		// 应用id,如何获取请参考:https://opensupport.alipay.com/support/helpcenter/190/201602493024
		$aop -> appId = $appid; 

		// 密钥格式为pkcs8,如何获取私钥请参考:https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport 
		$aop -> rsaPrivateKey = $private_key; 
		

		// 设置签名类型 
		$aop -> signType= "RSA2";

		// 设置请求格式,固定值json
		$aop -> format = "json";

		// 设置编码格式
		$aop -> charset= "utf-8";

		// 调用getPublicKey从支付宝公钥证书中提取公钥
		$aop -> alipayrsaPublicKey = $aop -> getPublicKey($alipayCertPath);

		// 是否校验自动下载的支付宝公钥证书,如果开启校验要保证支付宝根证书在有效期内
		$aop -> isCheckAlipayPublicCert = true;

		// 调用getCertSN获取证书序列号
		$aop -> appCertSN = $aop -> getCertSN($appCertPath);

		// 调用getRootCertSN获取支付宝根证书序列号
		$aop -> alipayRootCertSN = $aop -> getRootCertSN($rootCertPath);

		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.fund.trans.uni.transfer(单笔转账接口) 
		$request = new AlipayFundTransUniTransferRequest();
        
        //按照入参列表说明进行配置
		$param=[
			'out_biz_no'=>date("YmdHis",time()).rand(1000,9999),
			'trans_amount'=>'0.1',
			'product_code'=>'TRANS_ACCOUNT_NO_PWD',
			'biz_scene'=>'DIRECT_TRANSFER',
			'payee_info'=>[
				'identity_type'=>'ALIPAY_LOGON_ID',
				'identity'=>'wox*****@sandbox.com', //沙盒买家账号[替换为自己的沙盒买家账号]
				'name'=>'wox*****', //沙盒买家名称
			],
			'order_title'=>'沙盒转账测试',
			'remark'=>'沙盒单笔转账',
			'business_params'=>[
				'payer_show_name'=>'沙盒卖家wspxxs1061' //沙盒卖家名称
			]
		];

		if(!$is_sandbox){

			$param['payee_info']=[
				'identity_type'=>'ALIPAY_LOGON_ID',
				'identity'=>'158******88', //正式买家账号【替换为自己的】
				'name'=>'张三', //正式买家名称【替换为自己的】
			];
			$param['order_title']='正式转账测试';
			$param['remark']='正式单笔转账';
			$param['business_params']=[
				'payer_show_name'=>'***公司' //正式卖家名称【替换为自己的】
			];
		}

		$request -> setBizContent(json_encode($param));

		$result = $aop -> execute($request);

		$res=json_encode($result, JSON_UNESCAPED_UNICODE);

        $arr=json_decode($res,true);
        
        $code=$arr['alipay_fund_trans_uni_transfer_response']['code']; //通用状态码 10000表示成功
		$msg=$arr['alipay_fund_trans_uni_transfer_response']['msg'];
		$status=$arr['alipay_fund_trans_uni_transfer_response']['status']; //接口状态码
		$out_biz_no=$arr['alipay_fund_trans_uni_transfer_response']['out_biz_no']; //系统唯一订单号
		$order_id=$arr['alipay_fund_trans_uni_transfer_response']['order_id']; //支付宝订单号
        
        //转账成功
        if($code==10000 && $status=='SUCCESS'){

            //******成功后续业务逻辑区域[根据自己业务需求自行处理]*******
                ……
                ……
            //******后续业务逻辑区域*******
        }else{
            //******失败后续业务逻辑区域[根据自己业务需求自行处理]*******
                ……
                ……
            //******后续业务逻辑区域*******
        }		
        

		/*上面已经将参数列表按数组的方式重新整理,所以这里要注释掉
        $request -> setBizContent("{".

		      // 商户端的唯一订单号,对于同一笔转账请求,商户需保证该订单号唯一
		      "\"out_biz_no\":\"2020062900001\",".

		      // 转账金额,TRANS_ACCOUNT_NO_PWD产品取值最低0.1 
		      "\"trans_amount\":\"0.1\",".

		      // 产品码,单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD 
		      "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",".

		      // 场景码,单笔无密转账到支付宝账户固定为:DIRECT_TRANSFER  
		      "\"biz_scene\":\"DIRECT_TRANSFER\",".

		      // 转账业务的标题,用于在支付宝用户的账单里显示 
		      "\"order_title\":\"转账标题\",".

		      // 收款方信息     
		      "\"payee_info\":{".

		            // 参与方的唯一标识,收款支付宝账号或者支付宝吧账号唯一会员ID 
		            "\"identity\":\"2088******\",".

		            // 参与方的标识类型:ALIPAY_USER_ID 支付宝的会员ID 
		            "\"identity_type\":\"ALIPAY_USER_ID\",".

		            // 参与方真实姓名,如果非空,将校验收款支付宝账号姓名一致性。当identity_type=ALIPAY_LOGON_ID时,本字段必填 
		            "\"name\":\"张三\"".
		      "},".

		      // 业务备注 
		      "\"remark\":\"单笔转账\"".

		"}");*/

		

    }

 When we run the sandbox test code, the synchronous return result is printed as follows:

 Refresh the sandbox account page, you can see that the merchant account has decreased by 0.1 yuan, and the buyer's account has increased by 0.1 yuan, indicating that the transfer was successful.

Bills paid in a formal setting:

 When paying in a formal environment, the returned synchronization information is as follows:

The official environment has two more parameters than the sandbox environment:

pay_fund_order_id、 trans_date

If the Alipay account balance is insufficient , the returned information is as follows:

Return error code reference document:

Frequently Asked Questions|Webpage & Mobile App Alipay Documentation Center https://opendocs.alipay.com/open/309/rz82w5

Public error code reference document:

Public error code| Open Platform Alipay Documentation Center https://opendocs.alipay.com/common/02km9f Business error code reference document:

Funding API | API Alipay Documentation Center https://opendocs.alipay.com/apis/api_28#%E4%B8%9A%E5%8A%A1%E9%94%99%E8%AF%AF%E7%A0% 81

The parameters returned by the asynchronous callback notification:

 Note: If you want to verify the signature of the returned synchronous parameters and asynchronous parameters, do not use the Alipay Open Platform Development Assistant, because you will encounter many inexplicable prompt errors.

The asynchronous notification signature verification method is as follows:

Reference documents:

https://opensupport.alipay.com/support/helpcenter/192/201602471954?ant_source=manual&recommend=ab2418594aa12994227b51f38a16d735#anchor__9 Ant Technical Support Center is committed to providing developers with various capabilities and industry solutions for small programs, which can be found here Various capabilities, help and services needed by developers, service providers and channel providers https://opensupport.alipay.com/support/helpcenter/192/201602471954?ant_source=manual&recommend=ab2418594aa12994227b51f38a16d735#anchor__9

public function testsign(){
    	//API_ROOT 是框架常量,可以根据自己实际项目文件路径改为以/开头的根路径
    	require_once API_ROOT.'/../sdk/alipay_dakuan/AopCertClient.php';
    	
    	$aop = new AopCertClient();

		//证书路径【根据自己项目实际路径修改】
		$alipayCertPath = API_ROOT.'/../sdk/alipay_dakuan/formal/alipayCertPublicKey_RSA2.crt';
		//支付宝公钥赋值
		$aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
		//编码格式
		$aop->postCharset="UTF-8";
		// 回调的待验签字符串,需要替换为自己获取的参数【回调的是个数组,为了方便演示,此处将数组转为了json】
		$_POST='{"charset":"UTF-8","biz_content":"{\"pay_date\":\"2022-01-12 15:42:40\",\"biz_scene\":\"DIRECT_TRANSFER\",\"action_type\":\"FINISH\",\"pay_fund_order_id\":\"20220112110070001506340040637445\",\"origin_interface\":\"alipay.fund.trans.uni.transfer\",\"out_biz_no\":\"202201121542399130\",\"trans_amount\":\"0.10\",\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",\"order_id\":\"20220112110070000006340017448668\",\"status\":\"SUCCESS\"}","utc_timestamp":"1641973360744","sign":"AfIvONPS\/1V1uM+QwkYr4su3U3gFBss\/iH2nhhI9ttqKl3R1WZ5jIf7ia\/omo60orzK5TVayK3L5nmfOHYMr4UVhb7cFS8uNM5WtvOarTyPbDfSqd2zq088hx0+Kvnl5r+PSHhci4eyJx6iB4Fvzv3YVF+qcl9jqYkzx\/E91TulBt20pDhA6M2decqcdiw+CG9qOK+cByqOv9ihKfEgmccYMvJQX+P5w+rgp72NJFGKpCXlO6sI9PggKPlIjXlORl6v0ayV6lvrVWJMxeywThTo8X4CRZX2UCxl0sx5A8vSyrc1yTc4KrkgtUuzCwTSvRhXh4nkUXEXbEDoe6nS4zg==","app_id":"2018**********34","version":"1.1","sign_type":"RSA2","notify_id":"2022011200222154240095431456806399","msg_method":"alipay.fund.trans.order.changed"}';

		//签名方式
		$sign_type="RSA2";

		//把字符串转为数组
		$data = json_decode($_POST,true);

		//验签代码
		$flag = $aop->rsaCheckV1($data, null, $sign_type);

		if ($flag){
		  echo "success";
		}else {
		     echo "fail";
		}
    }

 For synchronous signature verification, refer to the document:

Data verification| Open Platform Alipay Documentation Center https://opendocs.alipay.com/common/02mse7#%E5%85%AC%E9%92%A5%E8%AF%81%E4%B9%A6%E6% 96%B9%E5%BC%8F You can choose to use the sdk public key certificate to verify the signature or verify the signature by yourself, because the sdk will actively verify the signature when calling the transfer API. If the returned synchronous data is normal, it means that the data is not valid. question. Synchronized data signature verification is not organized here, if you are interested, you can refer to the document to handle it yourself.

The above is the use process and precautions of the Alipay single transfer interface, and the get out of class is over.

Guess you like

Origin blog.csdn.net/salestina/article/details/122434331