支付宝H5支付、用户授权、个人信息获取(Phper)

支付宝H5支付、用户授权、个人信息获取(Phper)

最近要做一个H5的扫码支付,然后把遇到坑和解决方法记录下来,供有缘人来参考吧!
是tp3.2 所以引用第三方sdk的方法,请根据实际框架进行修改!!!

一、先说前端页面吧。用的是支付宝H5–jsapi
地址:http://myjsapi.alipay.com/jsapi/index.html
方法为:快捷支付 http://myjsapi.alipay.com/jsapi/native/trade-pay.html
直接上代码

  1. 初始化

    <script src="https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.inc.min.js"></script>
    	<script type="text/javascript">
    		function ready(callback) {
    			// 如果jsbridge已经注入则直接调用
    			if (window.AlipayJSBridge) {
    				callback && callback();
    			} else {
    				// 如果没有注入则监听注入的事件
    				document.addEventListener('AlipayJSBridgeReady', callback, false);
    			}
    		}
    
  2. 发送ajax请求后端(获取到快捷支付需要的参数:tradeNO)

    $.ajax({
    	  	type: 'post',
    	    url: "你的请求地址",
    	    data: 你的请求参数,
    	  	success: function(res) {
      		if(res.code ==10000){
    			alipay(res.trade_no,res.url)
    		}else{
    			alert(res.msg);
    			return;
    		}
    	})
    
  3. 创建支付宝订单
    调用的接口为 alipay.trade.create(统一收单交易创建接口)

    下面$data是一个数组,具体需要的参数请参考接口官方文档。

    class AlipayController extends Controller
    	{
    	    private $aop;
    	    protected function _initialize()
    	    {
    	        require './Application/Pay/Conf/aliConfig.php';
    	        vendor("Alipay.aop.AopClient"); //引入sdk
    	        $aop = new \AopClient();
    	        $aop->gatewayUrl = $config['gatewayUrl'];
    	        $aop->appId = $config['app_id'];
    	        $aop->rsaPrivateKey = $config['merchant_private_key'];
    	        $aop->alipayrsaPublicKey =  $config['alipay_public_key'];
    	        $aop->apiVersion = '1.0';
    	        $aop->postCharset=$config['charset'];
    	        $aop->format='json';
    	        $aop->signType=$config['sign_type'];
    	        $this->aop = $aop;
    	    }
    	   //创建订单
    	    public function create_pay($data)
    	    {
    	        vendor("Alipay.aop.request.AlipayTradeCreateRequest");
    	        $request = new \AlipayTradeCreateRequest();
    	        //回调地址(这个订单的支付结果会异步通知到这里)
    			$notify_url = “你的支付异步回调地址”;
    			$request->setNotifyUrl($notify_url);
    	        $request->setBizContent(json_encode($data));
    	        $result = $this->aop->execute($request);
    	        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    	        $res =  $result->$responseNode;
    	        $this->ajaxReturn($res,'JSON');
    	    }
    	 }
    

    aliConfig.php的内容

    $config = array (	
    	//应用ID,您的APPID。
    	'app_id' => "应用的appid",
    	//商户私钥,您的原始格式RSA私钥
    	'merchant_private_key' => "应用的私钥",
    	//编码格式
    	'charset' => "UTF-8",
    	//签名方式
    	'sign_type'=>"RSA2",
    	//支付宝网关
    	'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
    	//支付宝公钥
    	'alipay_public_key' => "应用的支付宝公钥"
    	);
    

    $data中的这个参数buyer_id的获取需要调用支付宝的其他接口
    获取用户授权和用户的基本信息

  4. buyer_id的获取(类似于微信的openid)

    public function get_user_info($callback){
            $my_url = urlencode($callback);
            $auth_code = $_REQUEST["auth_code"];//存放auth_code
            if (empty($auth_code)) {
                //state参数用于防止CSRF攻击,成功授权后回调时会原样带回
                $_SESSION['alipay_state'] = md5(uniqid(rand(), TRUE));
                //拼接请求授权的URL
                $url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" . $this->aop->appId . "&scope=auth_user&redirect_uri=" . $my_url . "&state=" . $_SESSION['alipay_state'];
                exit("<script> top.location.href='" . $url . "'</script>");
            }
           //Step2: 使用auth_code换取apauth_token
            if ($_REQUEST['state'] == $_SESSION['alipay_state'] || 1) {
                //根据返回的auth_code换取access_token
                vendor("Alipay.aop.request.AlipaySystemOauthTokenRequest");//调用sdk里面的AlipaySystemOauthTokenRequest类
                $request = new \AlipaySystemOauthTokenRequest();
                $request->setGrantType("authorization_code");
                $request->setCode($auth_code);
                $result = $this->aop->execute($request);
                $access_token = $result->alipay_system_oauth_token_response->access_token;
                //Step3: 用access_token获取用户信息
                vendor("Alipay.aop.request.AlipayUserInfoShareRequest");//调用sdk里面的AlipayUserInfoShareRequest类
                $request = new \AlipayUserInfoShareRequest();
                $result = $this->aop->execute($request, $access_token);
                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;
               if (!empty($resultCode) && $resultCode == 10000) {
               		$user_data = $result->$responseNode;
               		//$user_data就是获取到的个人信息
               }
             }
    
    buyer_id 的值为$user_data->user_id;
    
  5. 拿到支付宝创建的订单号之后前端界面就可以发起支付请求了
    trade_no:支付宝创建的订单号
    url:完成支付后的跳转地址

     function alipay(trade_no,url) {
    		AlipayJSBridge.call("tradePay", {
    			tradeNO: trade_no
    		}, function(result) {
    			if(result.resultCode == 6001){
    				var err_msg = "您取消了支付";
    			}else if(result.resultCode == 9000){
    				alert('支付成功!');
    				window.location.href =url;
    				return;
    			}else{
    				var err_msg = "支付出错";
    			}
    			alert(err_msg);
    			return;
    		});
    	}
    

    该笔订单支付的异步通知结果请在3中设置的回调地址里处理

  6. 订单支付回调处理(该方法也写在 AlipayController里面)

     //支付回调
    public function return_url(){
        $data = $_POST;
        //验签
        $restt = $this->aop->rsaCheckV1($data,'',$data['sign_type']);
        if ($restt === true){
            if($data['trade_status'] == 'TRADE_SUCCESS'){
                //支付成功后的逻辑处理
            }
            $result = 'success';
            exit($result);
        }
        //验签失败未做处理
    }
    

差不多就这么多了!本人菜鸟一枚,代码不美观,不规范,希望能给有缘人提供思路上的帮助!
Thank You!

发布了5 篇原创文章 · 获赞 4 · 访问量 538

猜你喜欢

转载自blog.csdn.net/wozhongmingyue/article/details/103523487