PHP 微信小程序支付实现

1.想要实现微信支付首先得注册商户,个人是不行的。
2.上述完成之后就可以写代码了
官方文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1

代码部分

//当小程序那边点击支付首先创建订单 
public function createOrder(){
		$request = $this->request;
        $memberinfo = $this->getMemberInfo($request);
        //获取小程序传过来的数据
        $depositid = isset($_POST['depositid']) && !empty($_POST['depositid']) ? (int)$_POST['depositid'] : exit(json_encode(['status'=>-1,'tips'=>'购买商品不存在']));
        $ticket = isset($_POST['ticket']) && !empty($_POST['ticket']) ? trim($_POST['ticket']) : '';//优惠方式
        $is_use = isset($_POST['is_use']) && !empty($_POST['is_use']) ? trim($_POST['is_use']) : 0;//是否用
        $cardid = isset($_POST['cardid']) && !empty($_POST['cardid']) ? safe_replace(trim($_POST['cardid'])) : '';//优惠卡
        $reduceMoney = isset($_POST['amount']) && !empty($_POST['amount']) ? floatval($_POST['amount']) : 0;//优惠金额
        $quantity = isset($_POST['quantity']) && !empty($_POST['quantity']) ? (int)$_POST['quantity'] : 1;//数量
        $payment = isset($_POST['payment']) && !empty($_POST['payment']) ? (int)$_POST['payment'] : '小程序支付';//支付方式
        $money = floatval($depositInfo['price']*$quantity*100 - $reduceMoney*100)/100;//支付金额
        $trade_sn=$this->create_sn();//订单号生成
        $surplus = array(
            'userid'      => $memberinfo['userid'], //用户ID
            'ccid'        => '',
            'cardid'      => $cardid,//优惠卡卡号
            'username'    => $memberinfo['real_name'],//用户名
            'price'       => 1000,  //商品价格
            'money'       => trim($money),//实际支付价格
            'quantity'    => $quantity,//数量
            'telephone'   => $memberinfo['mobile'],//电话
            'contactname' => $memberinfo['real_name'].$depositInfo['name'].'支付', 
            'email'       => $memberinfo['email'],//邮箱
            'addtime'	  => $time,
            'ip'		  => ip(),
            'pay_type'	  => 'recharge',
            'pay_id'      => 3,
            'payment'     => $payment,//支付方式(默认小程序支付)
            'usernote'    => $memberinfo['real_name'].'['.$trade_sn.']',
            'trade_sn'	  => $trade_sn,
            'depositid'	  =>  $depositid,//商品ID
            'discount_type'=> $discountType,
            'discount'=>$ticketmoney//优惠金额
        );
        $accountid = DB::table('pay_account')->insertGetId($surplus);//入库返回插入ID,让小程序在调用orderPay接口的时候再次传递过来
        exit(json_encode(['status'=>1,'tips'=>'正常下单','id'=>$accountid]));
}
//微信小程序支付
public function orderPay(){
		//获取微信传递数据
		$request = $this->request;
		$openid = $request['openid'];
        $id = $request['id'];//订单id,上面创建订单的时候返回的订单ID
        //去订单表中获取这条记录
        $accountInfo = DB::table('pay_account')->where('id',$id)->first();
        //实际支付金额
        $fee = $accountInfo['money'];
        //这里埋个点,为以后做活动0元的商品做铺垫
        //免费订单做处理
        if($fee == 0){
            Log::info('payaccount:',['content'=>$accountInfo]);
            $affectNum = DB::table('pay_account')->where('id',$id)
                ->update(['status'=>'succ','paytime'=>time()]);//直接修改订单状态为成功
            if($affectNum){
                exit(json_encode(array('status'=>1,'tips'=>'Free Order'))); //免费订单
            }else{
                exit(json_encode(array('status'=>0,'tips'=>'错误订单,请联系顾问老师!')));
            }
        }
        //组装数据
        $appid =        'APPID';//如果是公众号 就是公众号的appid
        $body =         $accountInfo['contactname']; //商品描述
        $mch_id =       '微信支付分配的商户号';   //商户号
        $nonce_str =    $this->nonce_str();//随机字符串   方法下面贴出
        $notify_url =   'https://***************/asyncCall';//异步回调下面会给出
        $openid =       $openid;
        $out_trade_no = $accountInfo['trade_sn'];//订单号
        $spbill_create_ip = '终端ip';
        $total_fee =    $fee*100;//因为充值金额最小是1 而且单位为分 如果是充值1元所以这里需要*100
        $trade_type = 'JSAPI';//交易类型 默认
        //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
        $post['appid'] = $appid;
        $post['body'] = $body;
        $post['mch_id'] = $mch_id;
        $post['nonce_str'] = $nonce_str;//随机字符串
        $post['notify_url'] = $notify_url;
        $post['openid'] = $openid;
        $post['out_trade_no'] = $out_trade_no;
        $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
        $post['total_fee'] = $total_fee;//总金额 最低为一块钱 必须是整数
        $post['trade_type'] = $trade_type;
        $sign = $this->sign($post);//签名下面给出方法
        $post_xml = '<xml>
         <appid>'.$appid.'</appid>
         <body>'.$body.'</body>
         <mch_id>'.$mch_id.'</mch_id>
         <nonce_str>'.$nonce_str.'</nonce_str>
         <notify_url>'.$notify_url.'</notify_url>
         <openid>'.$openid.'</openid>
         <out_trade_no>'.$out_trade_no.'</out_trade_no>
         <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
         <total_fee>'.$total_fee.'</total_fee>
         <trade_type>'.$trade_type.'</trade_type>
         <sign>'.$sign.'</sign>
</xml>';
//统一接口prepay_id
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $xml = $this->http_request($url,$post_xml);//接口请求
        //Log::info('调用支付接口:',['content'=>$xml]);
        $array = $this->xml($xml);//全要大写
        if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){

            $time = time();
            //PREPAY_ID预支付交易会话标识(微信生成的预支付会话标识,用于后续接口调用中使用,该值有效期为2小时)
            if(!empty($array['PREPAY_ID']) && $array['PREPAY_ID'] != 'the formId is a mock one'){
                DB::table('weixin_formid')
                    ->insert(
                        ['miniapp_openid'=>$openid,
                            'id_type'=>2,
                            'id_val'=>$array['PREPAY_ID'],
                            'id_nums'=>3,
                            'expired_time'=>$time]
                    );
            }
            $tmp='';//临时数组用于签名
            $tmp['appId'] = $appid;
            $tmp['nonceStr'] = $nonce_str;
            $tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
            $tmp['signType'] = 'MD5';
            $tmp['timeStamp'] = "$time";
            //$tmp['timeStamp'] = SYS_TIME;

            $data['status'] = 1;
            $data['timeStamp'] = "$time";//时间戳
            $data['nonceStr'] = $nonce_str;//随机字符串
            $data['signType'] = 'MD5';//签名算法,暂支持 MD5
            $data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
            $data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
            $data['out_trade_no'] = $out_trade_no;
        }else{
			$data['status'] = 0;
            $data['tips'] = "错误";
            $data['RETURN_CODE'] = $array['RETURN_CODE'];
            $data['RETURN_MSG'] = $array['RETURN_MSG'];
		}
        echo json_encode($data);
}
//小程序支付同步回调
public function paySyncCall(){
		$request = $this->request;
        $id = $request['id'];//订单id
        $time = time();
        //获取订单记录
        $accountInfo =  DB::table('pay_account')->where('id',$id)->first();
        //如果存在当前记录就修改状态为succ
        if($accountInfo){
        	$affectNum = DB::table('pay_account')->where('id',$id)
                ->update(['status'=>'succ','paytime'=>$time]);
            exit(json_encode(array('status'=>1,'tips'=>'支付状态更改成功','userid'=>$accountInfo['userid'],'id'=>$accountInfo['id'],'is_send'=>$rs)));
        }else{
            exit(json_encode(array('status'=>-1,'tips'=>'订单不存在')));
        }
}
//支付异步回调
public function asyncCall(){
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];

        if (empty($xml) || $xml == null || $xml == '') {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            echo $str;
            exit('Notify 非法回调');
        }
        $data=json_decode(json_encode(simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA)),true);
        //Log::info('Async request原始数据:',$data);
        // 保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);
        //签名步骤一:按字典序排序参数
        ksort($data);
        $buff = "";
        foreach ($data as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $string = trim($buff, "&");
        //签名步骤二:在string后加入KEY
        $string = $string . "&key=192006250**********02edce69f6a2d";//key为商户平台设置的密钥key
        //签名步骤三:MD5加密
        $string = md5($string);
        //签名步骤四:所有字符转为大写
        $sign = strtoupper($string);
        if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS')) {
            $result = $data;
            //获取服务器返回的数据
            $order_sn = $data['out_trade_no'];			//订单单号
            $openid = $data['openid'];					//付款人openID
            $total_fee = $data['total_fee'];			//付款金额 /分钱
            $transaction_id = $data['transaction_id']; 	//微信支付流水号
            $accountInfo =  DB::table('pay_account')->where('trade_sn',$order_sn)->first();
            if($accountInfo['status'] != 'succ'){
                try{
                    DB::transaction(function () use ($accountInfo){
                        DB::table('pay_account')->where('trade_sn',$accountInfo['trade_sn'])
                            ->update(['status'=>'succ','paytime'=>time()]);
                    });
                }catch(\Exception $e){
                    Log::info('异步回调->更新订单状态出错:',['error'=>$e]);
                }
            }          
         }
        // 返回状态给微信服务器
        $str ='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $str;
        return $result;
}
//接口请求
function http_request($url,$data = null,$headers=array()){
        $curl = curl_init();
        if( count($headers) >= 1 ){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
}
//签名 $data要先排好顺序
private function sign($data){
        $stringA = '';
        foreach ($data as $key=>$value){
            if(!$value) continue;
            if($stringA) $stringA .= '&'.$key."=".$value;
            else $stringA = $key."=".$value;
		}
        $wx_key = '192006250**********02edce69f6a2d';//key为商户平台设置的密钥key
        $stringSignTemp = $stringA.'&key='.$wx_key;
        return strtoupper(md5($stringSignTemp));
}
//随机32位字符串
private function nonce_str(){
        $result = '';
        $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
        for ($i=0;$i<32;$i++){
            $result .= $str[rand(0,48)];
        }
        return $result;
}
//生成订单号
function create_sn(){
     	mt_srand((double )microtime() * 1000000);
        return date("YmdHis") . str_pad(mt_rand(1, 99999), 5, "0", STR_PAD_LEFT);
}
//验证用户token是否过期
public function getMemberInfo($request){
        //pc 请求
        if(!empty($request['pc_token']) && $request['pc_token'] == $this->pc_token && !empty($request['userid'])){
            $member = DB::table('member')->select('mobile', 'email', 'userid', 'real_name', 'referral_point', 'referral_who', 'unionId')
                ->where('userid',$request['userid'])->first();
            return $member;
        }

        $date = date('Y-m-d H:i:s',strtotime("-20000 minute"));

        if(!empty($request['token'])) {
            $data = DB::table('weixin_token')
                ->where('key', $request['token'])
                ->where('add_time', '>', $date)
                ->first();
        }
        if(!empty($data)){
            $tokenInfo  =  json_decode(stripslashes($data['val']),true);//删除反斜杠
            Log::info('tokenInfo data:',['content'=>$tokenInfo['userid']]);

            $member = DB::table('member')
                ->select('mobile', 'email', 'userid', 'real_name', 'referral_point', 'referral_who', 'unionId')
                ->where('userid',$tokenInfo['userid'])
                ->first();
            return  $member;
        }else{
            $this->jsonResult(['status'=>401,'tips'=>'token过期重新登录']);
        }
    }
基本上上面就是用PHP实现微信小程序支付的代码,手敲不易,有什么问题请大佬指点。谢谢
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值