精华内容
下载资源
问答
  • 小程序支付 PHP

    2019-11-18 09:25:06
    小程序支付完整demo 拿去直接可以用 须准备好小程序appid 和商户mch_id 回调地址你们随意,想用的话就用不想用填个业务域名就行了 /****小程序支付/ public function wxpay() { // $param = input('param.'); // if...

    小程序支付完整demo 拿去直接可以用 须准备好小程序appid 和商户mch_id 回调地址你们随意,想用的话就用不想用填个业务域名就行了

    /****小程序支付/

    public function wxpay()
    {
    	// $param = input('param.');
    	// if(!$param['user_id']){
    	// 	return json_encode(array('error_code'=>10001,'msg'=>'请求失败'));
    	// }
    	$config = C('wxxcx');
    	$data['appid'] = $config['appid'];
    	$data['body'] = '商品支付';
    	$data['mch_id'] = $config['mch_id'];
    	$data['nonce_str'] = $this->createNoncestr();
    	$data['notify_url'] = 'www.donglongshangcheng.com';
    	$data['out_trade_no'] = rand(100000,999999);
    	$data['openid'] = 'o-0S-4ldkCKhdwqcspBejBwd8-Uo';
    	$data['spbill_create_ip'] = $_SERVER['SERVER_ADDR'];
    	$data['total_fee'] = 1;
    	$data['trade_type'] = 'JSAPI';
    	$data['sign'] = $this->getSign($data);
    	$xml = $this->arrayToXml($data);
    	$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    	$response = $this->postXmlCurl($xml,$url);
    	$response = $this->xmlToArray($response);
    	if($response['return_code'] == 'FAIL' || $response['result_code'] == 'FAIL'){
    		return json_encode(array('error_code'=>10001,'msg'=>'支付失败'));
    	}
    	//调起支付数据签名字段
        $timeStamp = time();
        $nonce_pay = $this->createNoncestr();
        $package = $response['prepay_id'];
        $signType = "MD5";
        $stringPay = "appId=".$config['appid']."&nonceStr=".$nonce_pay."&package=prepay_id=".$package."&signType=".$signType."&timeStamp=".$timeStamp."&key=".$config['mch_secrect'];
        $paySign = strtoupper(md5($stringPay));
        $rpay['timeStamp'] = (string)$timeStamp;
        $rpay['nonceStr'] = $nonce_pay;
        $rpay['package'] = "prepay_id=".$package;
        $rpay['signType'] = $signType;
        $rpay['paySign'] = $paySign;
        return json_encode(array('error_code'=>10000,'msg'=>'请求成功','data'=>$rpay));
    }
    
    	/*
     * 生成随机字符串方法
     */
    protected function createNoncestr($length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ ) {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    	/*
     *排序并格式化参数方法,签名时需要使用
     */
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    
    	/*
    * 对要发送到微信统一下单接口的数据进行签名
    */
    protected function getSign($Obj){
        foreach ($Obj as $k => $v){
            $param[$k] = $v;
        }
        //签名步骤一:按字典序排序参数
        ksort($param);
        $String = $this->formatBizQueryParaMap($param, false);
        //签名步骤二:在string后加入KEY
        $String = $String."&key=".C('wxxcx.mch_secrect');
        //签名步骤三:MD5加密
        $String = md5($String);
        //签名步骤四:所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }
    
    	//发送xml请求方法
    private static function postXmlCurl($xml, $url, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
        set_time_limit(0);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new WxPayException("curl出错,错误码:$error");
        }
    }
    
    	//数组转字符串方法
    protected function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    
    }
    
    //将xml字符串转换为数组
    
    protected static function xmlToArray($xml){
    
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    
        return $array_data;
    
    }
    
    展开全文
  • 小程序支付php

    2017-07-07 12:02:54
    小程序访问地址: payfee.php: include 'WeixinPay.php'; $appid=''; $openid= $_GET['id']; $mch_id=''; $key=''; $out_trade_no = $mch_id. time(); $total_fee = $_GET['fee']; if(empty($total_...

    小程序访问地址:

    payfee.php:


    include 'WeixinPay.php';
    $appid='';
    $openid= $_GET['id'];
    $mch_id='';
    $key='';
    $out_trade_no = $mch_id. time();
    $total_fee = $_GET['fee'];
    if(empty($total_fee)) //押金
    {
        $body = "充值押金";
        $total_fee = floatval(99*100);
    }
     else {
         $body = "充值余额";
         $total_fee = floatval($total_fee*100);
     }
    $weixinpay = new WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee);
    $return=$weixinpay->pay();
    
    echo json_encode($return);

    WeixinPay.php:

    <?php
    
    
    /*
     * 小程序微信支付
     */
    
    
    class WeixinPay {
    
    
        protected $appid;
        protected $mch_id;
        protected $key;
        protected $openid;
        protected $out_trade_no;
        protected $body;
        protected $total_fee;
                function __construct($appid, $openid, $mch_id, $key,$out_trade_no,$body,$total_fee) {
            $this->appid = $appid;
            $this->openid = $openid;
            $this->mch_id = $mch_id;
            $this->key = $key;
            $this->out_trade_no = $out_trade_no;
            $this->body = $body;
            $this->total_fee = $total_fee;
        }
    
    
        public function pay() {
            //统一下单接口
            $return = $this->weixinapp();
            return $return;
        }
    
    
        //统一下单接口
        private function unifiedorder() {
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
            $parameters = array(
                'appid' => $this->appid, //小程序ID
                'mch_id' => $this->mch_id, //商户号
                'nonce_str' => $this->createNoncestr(), //随机字符串
    //            'body' => 'test', //商品描述
                'body' => $this->body,
    //            'out_trade_no' => '2015450806125348', //商户订单号
                'out_trade_no'=> $this->out_trade_no,
    //            'total_fee' => floatval(0.01 * 100), //总金额 单位 分
                'total_fee' => $this->total_fee,
    //            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
                'spbill_create_ip' => '192.168.0.161', //终端IP
                'notify_url' => 'http://www.weixin.qq.com/wxpay/pay.php', //通知地址  确保外网能正常访问
                'openid' => $this->openid, //用户id
                'trade_type' => 'JSAPI'//交易类型
            );
            //统一下单签名
            $parameters['sign'] = $this->getSign($parameters);
            $xmlData = $this->arrayToXml($parameters);
            $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
            return $return;
        }
    
    
        private static function postXmlCurl($xml, $url, $second = 30) 
        {
            $ch = curl_init();
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $second);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
            //设置header
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            //要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //post提交方式
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    
    
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
            curl_setopt($ch, CURLOPT_TIMEOUT, 40);
            set_time_limit(0);
    
    
            //运行curl
            $data = curl_exec($ch);
            //返回结果
            if ($data) {
                curl_close($ch);
                return $data;
            } else {
                $error = curl_errno($ch);
                curl_close($ch);
                throw new WxPayException("curl出错,错误码:$error");
            }
        }
        
        
        
        //数组转换成xml
        private function arrayToXml($arr) {
            $xml = "<root>";
            foreach ($arr as $key => $val) {
                if (is_array($val)) {
                    $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
                } else {
                    $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
                }
            }
            $xml .= "</root>";
            return $xml;
        }
    
    
        //xml转换成数组
        private function xmlToArray($xml) {
    
    
            //禁止引用外部xml实体 
    
    
            libxml_disable_entity_loader(true);
    
    
            $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    
    
            $val = json_decode(json_encode($xmlstring), true);
    
    
            return $val;
        }
    
    
        //微信小程序接口
        private function weixinapp() {
            //统一下单接口
            $unifiedorder = $this->unifiedorder();
    //        print_r($unifiedorder);
            $parameters = array(
                'appId' => $this->appid, //小程序ID
                'timeStamp' => '' . time() . '', //时间戳
                'nonceStr' => $this->createNoncestr(), //随机串
                'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
                'signType' => 'MD5'//签名方式
            );
            //签名
            $parameters['paySign'] = $this->getSign($parameters);
            return $parameters;
        }
    
    
        //作用:产生随机字符串,不长于32位
        private function createNoncestr($length = 32) {
            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            return $str;
        }
    
    
        //作用:生成签名
        private function getSign($Obj) {
            foreach ($Obj as $k => $v) {
                $Parameters[$k] = $v;
            }
            //签名步骤一:按字典序排序参数
            ksort($Parameters);
            $String = $this->formatBizQueryParaMap($Parameters, false);
            //签名步骤二:在string后加入KEY
            $String = $String . "&key=" . $this->key;
            //签名步骤三:MD5加密
            $String = md5($String);
            //签名步骤四:所有字符转为大写
            $result_ = strtoupper($String);
            return $result_;
        }
    
    
        ///作用:格式化参数,签名过程需要使用
        private function formatBizQueryParaMap($paraMap, $urlencode) {
            $buff = "";
            ksort($paraMap);
            foreach ($paraMap as $k => $v) {
                if ($urlencode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
            $reqPar;
            if (strlen($buff) > 0) {
                $reqPar = substr($buff, 0, strlen($buff) - 1);
            }
            return $reqPar;
        }
    
    
    }


    小程序页面处理:

    wx.request({
    url:'https://www.yourhost.com/weixin/WeiActivity/payfee.php',//改成你自己的链接
    header:{
    'Content-Type':'application/x-www-form-urlencoded'
    },
    method:'POST',
    success:function(res){
    console.log(res.data);
    console.log('调起支付');
    wx.requestPayment({
    'timeStamp': res.data.timeStamp,
    'nonceStr': res.data.nonceStr,
    'package': res.data.package,
    'signType':'MD5',
    'paySign': res.data.paySign,
    'success':function(res){
    console.log('success');
    wx.showToast({
    title:'支付成功',
    icon:'success',
    duration:3000
    });
    },
    'fail':function(res){
    console.log('fail');
    },
    'complete':function(res){
    console.log('complete');
    }
    });
    },
    fail:function(res){
    console.log(res.data)
    }
    });

    回调url:notify.php

    $postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数
    if (empty($postXml)) {
        return false;
    }
    
    //将xml格式转换成数组
    function xmlToArray($xml) {
    
        //禁止引用外部xml实体 
        libxml_disable_entity_loader(true);
    
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    
        $val = json_decode(json_encode($xmlstring), true);
    
        return $val;
    }
    
    $attr = xmlToArray($postXml);
    
    $total_fee = $attr[total_fee];
    $open_id = $attr[openid];
    $out_trade_no = $attr[out_trade_no];
    $time = $attr[time_end];
    展开全文
  • 本文实例为大家分享了微信小程序支付PHP具体代码,供大家参考,具体内容如下 服务器端获取 openid Getopenid.php <?php header('Content-type: application/json; charset=UTF-8'); $APPID=;//填写小程序...
  • php实现小程序支付完整版来源:中文源码网浏览: 次日期:2019年11月5日【下载文档:php实现小程序支付完整版.txt】(友情提示:右键点上行txt文档名->目标另存为)php实现小程序支付完整版本文实例为大家分享了php...

    php实现小程序支付完整版

    来源:中文源码网    浏览: 次    日期:2019年11月5日

    【下载文档:  php实现小程序支付完整版.txt 】

    (友情提示:右键点上行txt文档名->目标另存为)

    php实现小程序支付完整版本文实例为大家分享了php实现小程序支付的具体代码,供大家参考,具体内容如下

    环境: tp3.2 + 小程序 微信支付功能开通Step1: 下载PHP 支付SDK(下载地址) 放到Library\Vendor下,取名Wxpay 修改WxPay.Config.php 里的appid appsecret key MCHIDStep2: 小程序 js 代码: var url = getApp().globalData.httpServer + 'api/buy/pay';

    var userId = getApp().globalData.userId;

    var totalMoney = this.data.totalMoney;

    var cart = this.data.goods;

    var param = {

    cart: JSON.stringify(cart),

    cartamount: totalMoney,

    userid: userId,

    payment: this.data.payment,

    addressid: defaultAddress.id

    };

    var that = this;

    util.http(url, param, function (ret) {

    if (ret.data.code == 1) {

    if (that.data.payment == 'balance') { // 余额支付

    that.afterPaySuccess(ret.data.data);

    } else { // 微信支付

    wx.requestPayment({

    timeStamp: ret.data.data.timeStamp,

    nonceStr: ret.data.data.nonceStr,

    package: ret.data.data.package,

    signType: ret.data.data.signType,

    paySign: ret.data.data.paySign,

    'success': function (res) {

    that.afterPaySuccess(ret.data.data.orderid);

    },

    'fail': function (res) {

    console.log(res);

    }

    })

    }

    } else {

    util.showTip(ret.data.msg, '提交订单失败');

    }

    });/**

    * 网络请求

    */

    function http(url, params, callback) {

    wx.request({

    url: url,

    data: params,

    success: function (res) {

    callback(res);

    },

    fail: function (err) {

    console.log(err);

    }

    });

    }

    Step3: 接口代码: public function pay()

    {

    $cart = I('cart', '', 'trim');

    $cartAmount = I('cartamount');

    $addressId = I('addressid', 0, 'intval');

    $payment = I('payment', '', 'trim');

    $userId = $this->userid;

    $cart = json_decode($cart, true);

    if (empty($cart)) {

    $result['msg'] = '购物车获取失败';

    $result['code'] = 0;

    $this->ajaxReturn($result);

    }

    $totalMoney = 0;

    foreach ($cart as $goods) {

    $money = $goods['price']; // price

    $selectCount = $goods['selectcount']; // price

    $itemAmount = number_format($money * $selectCount, 2, '.', '');

    $totalMoney += $itemAmount;

    }

    // 检查总金额是否一致

    if ($totalMoney != $cartAmount) {

    $result['msg'] = '总金额不匹配:' . $totalMoney;

    $result['code'] = 0;

    $this->ajaxReturn($result);

    }

    // 获取用户地址

    $address = M('MemberAddress')->where('userid=' . $userId . " and id=" . $addressId)->find();

    if (empty($address)) {

    $result['msg'] = '用户地址不存在';

    $result['code'] = 0;

    $this->ajaxReturn($result);

    }

    // 用户信息

    $user = M('Member')->where("id=" . $userId)->find();

    if ($payment == 'balance') {

    if ($user['amount'] < $cartAmount) {

    $result['msg'] = '余额不足';

    $result['code'] = 0;

    $this->ajaxReturn($result);

    }

    }

    // 生成订单

    $order['ordersn'] = $this->genOrdersn($user['id']);

    $order['price'] = $cartAmount;

    $order['addressid'] = $address['id'];

    $order['addressinfo'] = serialize($address); //json_encode($address);

    $order['longitude'] = $address['longitude'];

    $order['latitude'] = $address['latitude'];

    $order['addtime'] = time();

    $order['status'] = 0;

    $order['userid'] = $user['id'];

    $order['paytype'] = $payment;

    $order['paysn'] = '';

    $order['paytime'] = time();

    $orderId = M("Order")->add($order);

    if ($orderId == 0) {

    $result['msg'] = '创建订单失败';

    $result['code'] = 0;

    $this->ajaxReturn($result);

    }

    foreach ($cart as $goods) {

    $orderGoods['orderid'] = $orderId;

    $orderGoods['goodsid'] = $goods['id'];

    $orderGoods['title'] = $goods['title'];

    $orderGoods['price'] = $goods['price'];

    $orderGoods['attr'] = $goods['attr'];

    $orderGoods['pic'] = $goods['pic'];

    $orderGoods['num'] = $goods['selectcount'];

    M("OrderGoods")->add($orderGoods);

    }

    if ($payment == 'balance') {

    // 余额支付

    $this->balancePay($cartAmount, $user['wxopenid'], $orderId);

    } else if ($payment == 'weixin') {

    // 微信支付

    $this->weixinPay($cartAmount, $user['wxopenid'], $orderId, $order['ordersn']);

    }

    } /**

    * 微信支付

    * @author 大脸猫脸大

    * @param $cart

    * @param $cartAmount

    * @param $address

    * @param $user

    */

    private function weixinPay($cartAmount, $openId, $orderId, $orderSn)

    {

    import("Vendor.Wxpay.lib.WxPay#Api", "", ".php");

    //订单号

    $money = $cartAmount * 100;

    $openid = $openId;

    $input = new \WxPayUnifiedOrder();

    $input->SetBody("迪克-商品");

    $input->SetOut_trade_no("$orderSn");

    $input->SetTotal_fee("$money");

    $input->SetNotify_url("http://" . $_SERVER['HTTP_HOST'] . "/api/buy/payNotify");

    $input->SetTrade_type("JSAPI");

    $input->SetOpenid($openid);

    $unifiedOrder = \WxPayApi::unifiedOrder($input);

    if ($unifiedOrder['result_code'] == 'SUCCESS' && $unifiedOrder['return_code'] == 'SUCCESS') {

    $time = time();

    $data['timeStamp'] = "$time"; //时间戳

    $data['nonceStr'] = $unifiedOrder['nonce_str']; //随机字符串

    $data['signType'] = 'MD5'; //签名算法,暂支持 MD5

    $data['package'] = 'prepay_id=' . $unifiedOrder['prepay_id']; //统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*

    $data['paySign'] = $this->genPaySign($unifiedOrder, $time);// 之前以为是$unifiedOrder['sign']; 后来发现是调用的这种方法. 签名方案参见微信公众号支付帮助文档;

    $data['out_trade_no'] = $orderSn;

    $data['orderid'] = $orderId;

    $return['code'] = 1;

    $return['data'] = $data;

    } else {

    Log::write(var_export($unifiedOrder, true), Log::ERR, '', C('LOG_PATH')."wx_pay_".date('y_m_d').'.log');

    $return['code'] = 0;

    $return['msg'] = '微信支付失败';// $unifiedOrder['RETURN_MSG'];

    }

    $this->ajaxReturn($return);

    }

    /* 生成支付签名*/

    private function genPaySign($unifiedOrder, $time)

    {

    $appId = \WxPayConfig::APPID;

    $nonceStr = $unifiedOrder['nonce_str'];

    $package = 'prepay_id=' . $unifiedOrder['prepay_id'];

    $signType = "MD5";

    $timeStamp = $time;

    $key = \WxPayConfig::KEY; $sign = md5(sprintf("appId=%s&nonceStr=%s&package=%s&signType=%s&timeStamp=%s&key=%s", $appId, $nonceStr, $package, $signType, $timeStamp, $key));

    } /**

    * 支付回调

    * @author:大脸猫脸大

    */

    public function payNotify()

    {

    import("Vendor.Wxpay.lib.WxPay#Data", "", ".php");

    $xml = $GLOBALS['HTTP_RAW_POST_DATA'];

    $val = \WxPayResults::Init($xml);

    if ($val['result_code'] == 'SUCCESS' && $val['return_code'] == 'SUCCESS') {

    $orderSn = $val['out_trade_no'];

    $transactionId = $val['transaction_id'];

    $data = array('paytype' => 'weixin', 'status' => '1', 'paytime' => time(), 'paysn' => $transactionId);

    M("Order")->where("ordersn='$orderSn'")->setField($data);

    exit('');

    }else {

    Log::write(var_export($val, true), Log::ERR, '', C('LOG_PATH')."wx_pay_notify_".date('y_m_d').'.log');

    exit('');

    }

    }payNotify 回调方法里一定要注意返回

    复制代码 代码如下:如果不处理,你会发现payNotify 会被执行很多次参见:官方文档总结一下: 注意二点,1.签名的问题 2. 回调方法的返回处理。欢迎大家指正。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。

    亲,试试微信扫码分享本页! *^_^*

    展开全文
  • 微信小程序支付的简易封装类!,在其他请求类里面直接调用此类即可触发支付namespaceapp\common\library;classwxPay{//微信支付微信用户的openid要付款的金额支付的类型名称商品名下单订单号publicfunctionwechatPay($...

    微信小程序支付的 简易封装类!, 在其他请求类里面直接调用此类即可触发支付

    03bd79f55ed2eb819a678261ceb80ad0.png

    namespace app\common\library;

    class wxPay

    {

    //微信支付                 微信用户的openid   要付款的金额     支付的类型名称  商品名   下单订单号

    public function wechatPay($user_openid = '', $ro_pay_price = '', $body_name = '', $order_number = ''){

    $fee = $ro_pay_price; //举例充值0.01

    $appid = '';//如果是公众号 就是公众号的appid

    $body = $body_name;  // 举例: 服务预约

    $mch_id = '15111111111';   // 您的商户账号

    $nonce_str = $this->nonce_str(); //随机字符串

    $notify_url = 'https://wxxcx.xxx.xxx';  // 回调的url【自己填写】

    $openid = $user_openid;  // 用户openid  传参

    $out_trade_no = $order_number;//商户订单号

    $spbill_create_ip = '565.65695.5656.55;   // 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 = '

    '.$appid.'

    '.$mch_id.'

    '.$nonce_str.'

    '.$notify_url.'

    '.$openid.'

    '.$out_trade_no.'

    '.$spbill_create_ip.'

    '.$total_fee.'

    '.$trade_type.'

    '.$sign.'

     ';

    //统一接口prepay_id

    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

    $xml = $this->http_request($url, $post_xml);

    $array = $this->xml($xml); //全要大写

    if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){

    $time = time();

    $tmp='';//临时数组用于签名

    $tmp['appId'] = $appid;

    $tmp['nonceStr'] = $nonce_str;

    $tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];

    $tmp['signType'] = 'MD5';

    $tmp['timeStamp'] = "$time";

    $data['statu'] = 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['statu'] = 0;

    $data['text'] = "错误";

    $data['RETURN_CODE'] = $array['RETURN_CODE'];

    $data['RETURN_MSG'] = $array['RETURN_MSG'];

    }

    return json_encode($data);

    }

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

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

    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;

    }

    }

    展开全文
  • 实现小程序支付功能的方法:首先进行前端请求支付,并在后端请求微信服务器;然后后端接受微信服务器并返回数据;接着前端发起支付;最后后端接受微信服务器回调即可。【相关学习推荐:实现小程序支付功能的方法:1....
  • 微信小程序支付 php后台

    万次阅读 2019-08-26 10:41:12
    微信小程序支付,一贯的风格,代码复制粘贴就好使,想明白原理,自己看开发文档去 一、前端代码: 1.先写一个可以点击支付的按钮 <view class="chongzhi_button" bindtap="pay">支付</view> 2.开始js...
  • 购买过来的,比较有用,测试可用,可以下载小程序支付
  • 开始js代码pay:function(){//下订单并唤起微信支付varprice='0.01';//支付金额varopenid='';//这里传用户openid,怎么获取用户的openid这里就不详细的说了varthat=this;wx.request({url:'这里写后端接口地址',data:{...
  • 微信小程序支付PHP实例

    万次阅读 2017-09-04 23:03:04
    本文提供了微信小程序支付的一个示例
  • 微信小程序支付php后台对接

    千次阅读 2018-01-04 10:14:33
    微信小程序支付
  • 微信小程序支付PHP

    2018-02-22 15:07:53
    服务器端获取 openid Getopenid.php &lt;?php header('Content-type: application/json;...//填写小程序appid $SECRET="";//填写小程序secret $JSCODE=""; if(isset($_GET['js_cod...
  • 微信小程序支付 php后台对接完整代码

    万次阅读 多人点赞 2018-06-11 12:02:08
    小程序在调起微信支付之前需要5个参数,这时候就需要携带code向后台请求,然后后台根据code获取openid 再进行服务器之间的。。。。   一、准备工作 1、小程序注册,要以公司的以身份去注册一个小程序,才有微信...
  • } } 封装好的微信支付php namespace app\ miniapp\ controller; class wxPay { //微信支付 微信用户的openid 要付款的金额 支付的类型名称 商品名 下单订单号 public function wechatPay($user_...
  • 在微信小程序中接入了支付功能,顺便记录下 微信支付文档https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1 $config = array(  'app_id'=&gt;'xxx', 'secret'=&gt;"xxxxx", ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,145
精华内容 458
关键字:

小程序支付php