小程序支付,前端,tp5接口,复制即可用

news/2024/7/20 4:24:59 标签: 小程序, php

如果复制你无法用,请看看小程序公众后台,功能-微信支付 是否绑定支付商户号

接口方法

php">    public function feer(){
        include_once("WeixinPay.php");
        $appid=''; //小程序appid
        $openid= $_GET['openid'];
        $mch_id=''; //微信支付商户支付号
        $key=''; //Api密钥
        $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);
//        return json_encode($return);
    }

写个类直接放入接口同个controller类目即可 WeixinPay.php

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' => '2018013106125348', //商户订单号
            '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' => 'https://www.weixin.qq.com/wxpay/notify.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 = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        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: api.url + 'feer', //请求接口的url
      method: 'GET', //请求方式
      data:{
        openid: app.globalData.openid,//获取用户openid  必须要获取到openid
        fee:100 //商品价格
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      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(res);
          },
          'complete': function (res) {
            console.log('complete');
          }
        });
      },
      fail: function (res) {
        console.log(res.data)
      }
    });

http://www.niftyadmin.cn/n/957989.html

相关文章

vant安装

选择了官网的 npm i vantnext -S命令 陈尼克建议的命令是 yarn add vant3.0.0-beta.8 -S也不知道哪个好&#xff0c;先这样了&#xff0c;官网安装的是3.0.9版

zuul动态配置路由规则,从DB读取

前面已经讲过zuul在application.yml里配置路由规则&#xff0c;将用户请求分发至不同微服务的例子。 zuul作为一个网关&#xff0c;是用户请求的入口&#xff0c;担当鉴权、转发的重任&#xff0c;理应保持高可用性和具备动态配置的能力。 我画了一个实际中可能使用的配置框架…

利用微信电脑最新版 反编译微信小程序

大家都知道编写一个微信小程序是非常漫长的&#xff0c;但是由于现阶段微信小程序存在反编译的可能&#xff0c;于是我去github上找到一个反编译工具(跳转)这个工具其实很早就出来了&#xff0c;但是这个工具需要提取微信小程序的wxapkg文件&#xff0c;就是微信小程序编译后的…

上传的图标和最后显示的图标为什么不一样呢,是正常的吗,最后显示的为什么会是个问号

前缀可能没有设置好 你看看你的前缀怎么设置的 加一个iconfont&#xff0c;iconfont xxx 我原来是 <i class"icon18qianyanjishu"></i>没有iconfont&#xff0c;结果显示出来是个问号&#xff0c;加了iconfont了以后&#xff0c;正常了。 <i class&q…

反编译小程序

• &#xff57;&#xff49;&#xff4e;&#xff0b;&#xff32;进入cmd,再切换路径到反编译脚本目录下   切换路径很简单,主要用"cd…"和"cd 文件夹"两种手段,百度一下你就知道  • 切换后&#xff0c;输入npm install回车执行   再依次安装以下依…

SpringBoot基础系列-使用日志

原创文章&#xff0c;转载请标注出处&#xff1a;《SpringBoot基础系列-使用日志》 一、概述 SpringBoot使用Common Logging进行日志操作&#xff0c;Common Logging是一个日志功能框架&#xff0c;没有具体的实现&#xff0c;具体的日志操作需要具体的日志框架来实现。 常用…

“实验10,记账本实战之导航栏“这里有问题了,晚上或者明天再继续

bug如下 ivyoneivyonedeMacBook-Pro daily-cost % npm run dev> vite-project0.0.0 dev /Users/ivyone/hami94/daily-cost > viteerror when starting dev server: Error: The following dependencies are imported but could not be resolved:lib-flexible/flexible (i…

mysql按关键符号截取字段

比如以下字段内容&#xff0c;我要截取以::::::为分割的部分内容 "banner_2 (1).png::::::/gcjx/e/extend/uploadImg/upload/upload_files/2020-07-02/9d2cba0773d47bad2cc8f8f36ee0a344.png::::::35231 banner_2.png::::::/gcjx/e/extend/uploadImg/upload/upload_files…