欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序支付PHP代码

程序员文章站 2023-11-17 18:12:46
本文实例为大家分享了微信小程序支付php具体代码,供大家参考,具体内容如下 服务器端获取 openid getopenid.php

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

服务器端获取 openid

getopenid.php

<?php
 header('content-type: application/json; charset=utf-8');
 $appid="";//填写小程序appid
 $secret="";//填写小程序secret
 $jscode="";
 if(isset($_get['js_code'])){
  $jscode=$_get['js_code'];
  $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid
  ."&secret=".$secret."&js_code=".$jscode."&grant_type=authorization_code";
  $curl = curl_init();
  curl_setopt($curl, curlopt_url, $url);
  curl_setopt($curl, curlopt_ssl_verifypeer, false);
  curl_setopt($curl, curlopt_returntransfer, 1);
  curl_setopt($curl, curlopt_header, 0);
  $data = curl_exec($curl);
  $array=json_decode($data,true);

  curl_close($curl);
  $openid=isset($array['openid'])?$array['openid']:$array['errcode'];
  if($openid=="40029"){
   $response["result"] = 0;
   $response["msg"] = "invalid code";
   $response["openid"] = $openid;
   echo json_encode($response);
  }else{
   $response["result"] = 1;
   $response["msg"] = "user exist";
   $response["openid"] = $openid;
   echo json_encode($response);
  }
 }

小程序存储openid
在app.js中

getuserinfo:function(cb){
 var that = this
 if(this.globaldata.userinfo){
  typeof cb == "function" && cb(this.globaldata.userinfo)
 }else{
  wx.login({
  success: function (res) {
   if (res.code) {
   var code = res.code;
   wx.getuserinfo({
    success: function (res2) {
    console.log(res2);
    that.globaldata.userinfo = res2.userinfo;
    typeof cb == "function" && cb(that.globaldata.userinfo)
    var encrypteddata = encodeuricomponent(res2.encrypteddata);//一定要把加密串转成uri编码
    var iv = res2.iv;
    //请求自己的服务器
    //login(code, encrypteddata, iv);
    wx.showtoast({
     title: '正在登录...',
     icon: 'loading',
     duration: 10000
    });
    //请求服务器
    wx.request({
     url: api_url,//getopenid.php
     data: {
     js_code: code,
     },
     method: 'get',
     header: {
     'content-type': 'application/json'
     }, // 设置请求的 header
     success: function (res) {
     // success
     wx.hidetoast();
     console.log("json:" + res.data);
     if (res.data.result=="1"){//获取openid成功
      wx.setstorage({//存储openid
      key: "openid",
      data: res.data.openid
      })
     }else{
      wx.showtoast({
      title: 'openid获取失败',
      icon: 'none',
      duration: 2000
      })
     }
     console.log('服务器返回' + res.data.result);
     console.log('服务器返回' + res.data.msg);
     console.log('服务器返回' + res.data.openid);
     },
     fail: function () {
     // fail
     // wx.hidetoast();
     },
     complete: function () {
     // complete
     }
    })
    }
   })
   } else {
   console.log('获取用户登录态失败!' + res.errmsg)
   }
  }
  })
 }
 }

在登陆界面获取openid

var app = getapp()
onload: function () {
 console.log('onload')
 var that = this
 //调用应用实例的方法获取全局数据
 app.getuserinfo(function(userinfo){//获取用户信息 
  //更新数据
  that.setdata({
  userinfo:userinfo
  })
 })
}

通过以上步骤已经获取到openid

支付方法小程序

pay() {
 var that = this;
 if (this.data.totalprice == 0) {
  return;
 }
 wx.getstorage({//获取存储在本地的openid
  key: 'openid',
  success: function (res) {
  console.log(res.data)
  that.setdata({
   openid:res.data,
  })
  var cararray = that.data.cararray;
  var str="";
  for (var i = 0; i < cararray.length; i++) {
   str=str+ cararray[i].num+"个" + cararray[i].name+" ";
  }
  wx.request({
   url: 'pay.php',//支付接口
   data: {
   openid: res.data,//openid
   total_fee: that.data.totalprice,//总金额
   body: str,//商品描述
   },
   method:'get',
   success:function(res){
   console.log(res.data['timestamp'])
   if(res.data){
    wx.requestpayment({
    'timestamp': res.data['timestamp'],
    'noncestr': res.data['noncestr'],
    'package': res.data['package'],
    'signtype': 'md5',
    'paysign': res.data['paysign'],
    'success': function (res) {
     wx.showtoast({
     title: '支付成功',
     icon: 'succes',
     duration: 1000,
     mask: true
     })
     //支付成功后在数据库减去购买商品的数量
     var cararray = that.data.cararray;
     for (var i = 0; i < cararray.length; i++) {
     that.setdata({
      jiesuan_num: cararray[i].num,
      jiesuan_id: cararray[i].goods_id,
     })
     degood(that);
     }
    },
    'fail': function (res) {
     wx.showtoast({
     title: '支付失败',
     icon: 'none',
     duration: 1000,
     mask: true
     })
    }
    })
   }
   }
  })
  }
 })
 },

pay.php

<?php
 include 'weixinpay.php'; 
 $appid=''; //小程序appid
 $openid= $_get['openid']; 
 $mch_id=''; //商户id
 $key=''; //商户key
 $out_trade_no = $mch_id. time(); 
 $total_fee = $_get['total_fee']; 
 $body= $_get['body'];
 if(empty($total_fee)){ 
  $body = $body; 
  $total_fee = floatval(99*100); 
 }else{ 
  $body = $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;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。