tp5微信app支付

微信支付服务端(支付类的封装)

支付时实例化该类,调用pay方法即可(需要传参数)

文中需要改动参数值为 $appid $mch_id 还有sign方法中的 key 改成自己的秘钥 $stringSignTemp = $stringA.’&key=’.‘66666666666666664564654444412’; //申请支付后有给予一个商户账号和密码,登陆后自己设置key
关于php更多好文--------->www.zhangxuu.com

<?php
namespace app\api\controller;

use think\Db;

class WxPay{
    public function pay($body_name='',$order_number='',$fee='') {
     
        $appid = '123456789'; //应用的appid
        $mch_id = '155999999'; // 您的商户账号
        $nonce_str = $this -> nonce_str(); //随机字符串
        $body = $body_name; // 举例: 服务预约
        $out_trade_no = $order_number; //商户订单号
        $total_fee = $fee*100;
        $spbill_create_ip = '122.114.62.70'; // IP白名单
        $notify_url = 'http://app.ggg.com/api/Notify/Wx_notify'; // 回调的url【自己填写,如若回调不成功请注意查看服务器是否开启防盗链,回调地址用http】
        $trade_type = 'APP'; //交易类型 默认

            //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错

            $post['appid'] = $appid;
            $post['body'] = $body;
            $post['mch_id'] = $mch_id;
            $post['nonce_str'] = $nonce_str; //随机字符串
            $post['notify_url'] = $notify_url;
            $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><![CDATA[$appid]]></appid>
                           <body><![CDATA[$body]]></body>
                           <mch_id><![CDATA[$mch_id]]></mch_id>
                           <nonce_str><![CDATA[$nonce_str]]></nonce_str>
                           <notify_url><![CDATA[$notify_url]]></notify_url>
                           <out_trade_no><![CDATA[$out_trade_no]]></out_trade_no>
                           <spbill_create_ip><![CDATA[$spbill_create_ip]]></spbill_create_ip>
                           <total_fee><![CDATA[$total_fee]]></total_fee>
                           <trade_type><![CDATA[$trade_type]]></trade_type>
                           <sign><![CDATA[$sign]]></sign>
                        </xml>";

            //统一接口prepay_id

            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
            $xml = $this -> http_request($url, $post_xml);

            $array = $this -> xml($xml); //全要大写
//            dump($array);die;
            if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
                $time = time();
                $tmp = []; //临时数组用于签名
                $tmp['appid'] = $appid;
                $tmp['noncestr'] = $nonce_str;
                $tmp['package'] = 'Sign=WXPay';
                $tmp["partnerid"] = $mch_id;
                $tmp['prepayid'] = $array['PREPAY_ID'];
                $tmp['timestamp'] = "$time";

                $data['appid'] = $appid;
                $data['noncestr'] = $nonce_str; //随机字符串
//                $data['package'] = 'prepay_id='.$array['PREPAY_ID']; //统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
                $data['package'] = "Sign=WXPay";
                $data['partnerid']= $mch_id;
                $data['prepayid'] = $array['PREPAY_ID'];
                $data['timestamp'] = "$time"; //时间戳
                $data['sign'] = $this ->sign($tmp);//签名

            } else {
                $data['status'] = 0;
                $data['text'] = "错误";
                $data['RETURN_CODE'] = $array['RETURN_CODE'];
                $data['RETURN_MSG'] = $array['RETURN_MSG'];
            }
            return json_encode($data);
        }

    public function sign($data,$wx_key)
    {
    //签名 $data要先排好顺序
        $stringA = '';
        ksort($data);
        foreach($data as $key => $value) {
            if (!$value) continue;
            if ($stringA)
                $stringA.= '&'.$key."=".$value;
            else
                $stringA = $key."=".$value;
            }

        $stringSignTemp = $stringA.'&key='.'66666666666666664564654444412'; //申请支付后有给予一个商户账号和密码,登陆后自己设置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;
    }

    //curl请求啊
    public 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;
    }

    //获取xml
    private function xml($xml) {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = "";
        foreach($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }
}

关于php更多好文--------->www.zhangxuu.com

以下是基于TP5框架的微信APP支付功能示例: 1. 首先,在TP5框架的config目录下新建wxpay.php文件,用于存放微信支付相关的配置信息。 ```php <?php return [ // 应用ID 'app_id' => '', // 商户号 'mch_id' => '', // API密钥 'api_key' => '', // 异步通知地址 'notify_url' => '', // 交易类型 'trade_type' => 'APP', // 签名类型 'sign_type' => 'MD5', ]; ``` 2. 在TP5框架的extend目录下新建WxPay文件夹,并在该文件夹下新建WxPayApi.php文件,用于封装微信支付相关的接口。 ```php <?php namespace WxPay; use think\facade\Log; /** * 微信支付API */ class WxPayApi { /** * 统一下单接口 * * @param array $data * @return array */ public static function unifiedOrder($data) { $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $data['appid'] = config('wxpay.app_id'); $data['mch_id'] = config('wxpay.mch_id'); $data['nonce_str'] = self::getNonceStr(); $data['sign_type'] = config('wxpay.sign_type'); $data['sign'] = self::makeSign($data); $xml = self::toXml($data); $response = self::postXmlCurl($xml, $url, true, 6); $result = self::fromXml($response); if ($result['return_code'] == 'FAIL') { Log::error('统一下单失败:' . $result['return_msg']); return ['errcode' => 1, 'errmsg' => $result['return_msg']]; } if ($result['result_code'] == 'FAIL') { Log::error('统一下单失败:' . $result['err_code_des']); return ['errcode' => 1, 'errmsg' => $result['err_code_des']]; } $data = [ 'appid' => config('wxpay.app_id'), 'partnerid' => config('wxpay.mch_id'), 'prepayid' => $result['prepay_id'], 'package' => 'Sign=WXPay', 'noncestr' => self::getNonceStr(), 'timestamp' => time(), ]; $data['sign_type'] = config('wxpay.sign_type'); $data['sign'] = self::makeSign($data); return $data; } /** * 生成签名 * * @param array $data * @return string */ public static function makeSign($data) { ksort($data); $string = self::toUrlParams($data); $string = $string . '&key=' . config('wxpay.api_key'); if (config('wxpay.sign_type') == 'MD5') { $string = md5($string); } elseif (config('wxpay.sign_type') == 'HMAC-SHA256') { $string = hash_hmac('sha256', $string, config('wxpay.api_key')); } return strtoupper($string); } /** * 将数组转换为XML格式 * * @param array $data * @return string */ public static function toXml($data) { $xml = '<xml>'; foreach ($data as $key => $val) { if (is_numeric($val)) { $xml .= '<' . $key . '>' . $val . '</' . $key . '>'; } else { $xml .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>'; } } $xml .= '</xml>'; return $xml; } /** * 将XML转换为数组 * * @param string $xml * @return array */ public static function fromXml($xml) { libxml_disable_entity_loader(true); $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } /** * 生成随机字符串 * * @param int $length * @return string */ public static function getNonceStr($length = 32) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $nonceStr = ''; for ($i = 0; $i < $length; $i++) { $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $nonceStr; } /** * 将数组转换为URL参数 * * @param array $data * @return string */ public static function toUrlParams($data) { $buff = ''; foreach ($data as $k => $v) { if ($k != 'sign' && $v != '' && !is_array($v)) { $buff .= $k . '=' . $v . '&'; } } $buff = trim($buff, '&'); return $buff; } /** * 发送POST请求 * * @param string $xml * @param string $url * @param bool $useCert * @param int $timeout * @return bool|string */ public static function postXmlCurl($xml, $url, $useCert = false, $timeout = 30) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0'); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($useCert) { curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); curl_setopt($ch, CURLOPT_SSLCERT, '/path/to/your/cert.pem'); curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM'); curl_setopt($ch, CURLOPT_SSLKEY, '/path/to/your/key.pem'); } curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $result = curl_exec($ch); curl_close($ch); return $result; } } ``` 3. 在控制器中调用WxPayApi类的unifiedOrder方法,实现微信支付功能。 ```php <?php namespace app\index\controller; use think\Controller; use WxPay\WxPayApi; class Index extends Controller { public function index() { $data = [ 'body' => '测试商品', 'out_trade_no' => date('YmdHis') . mt_rand(10000, 99999), 'total_fee' => 1, 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], ]; $result = WxPayApi::unifiedOrder($data); if ($result['errcode']) { return $result['errmsg']; } return json($result); } } ``` 以上是基于TP5框架的微信APP支付功能示例,具体实现可以根据自己的需要进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值