SoFunction
Updated on 2025-04-04

WeChat applet payment PHP code

This article shares the specific code of WeChat mini-program payment PHP for your reference. The specific content is as follows

Get openid on the server side

<?php
 header('Content-type: application/json; charset=UTF-8');
 $APPID="";//Fill in the applet appid $SECRET="";//Fill in the mini program secret $JSCODE="";
 if(isset($_GET['js_code'])){
  $JSCODE=$_GET['js_code'];
  $url="/sns/jscode2session?app&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);
  }
 }

Mini program storage openid
In

getUserInfo:function(cb){
 var that = this
 if(){
  typeof cb == "function" && cb()
 }else{
  ({
  success: function (res) {
   if () {
   var code = ;
   ({
    success: function (res2) {
    (res2);
     = ;
    typeof cb == "function" && cb()
    var encryptedData = encodeURIComponent();//Be sure to convert the encryption string into URI encoding    var iv = ;
    //Request your own server    //Login(code, encryptedData, iv);
    ({
     title: 'Logining...',
     icon: 'loading',
     duration: 10000
    });
    //Request the server    ({
     url: API_URL,//
     data: {
     js_code: code,
     },
     method: 'GET',
     header: {
     'content-type': 'application/json'
     }, // Set the requested header     success: function (res) {
     // success
     ();
     ("JSON:" + );
     if (=="1"){//Get openid successful      ({//Storage openid      key: "openid",
      data: 
      })
     }else{
      ({
      title: 'openid failed to get',
      icon: 'none',
      duration: 2000
      })
     }
     ('Server Return' + );
     ('Server Return' + );
     ('Server Return' + );
     },
     fail: function () {
     // fail
     // ();
     },
     complete: function () {
     // complete
     }
    })
    }
   })
   } else {
   ('Failed to get the user login status!  ' + )
   }
  }
  })
 }
 }

Get openid in the login interface

var app = getApp()
onLoad: function () {
 ('onLoad')
 var that = this
 //Calling the application instance method to obtain global data (function(userInfo){//Get user information  //Update data  ({
  userInfo:userInfo
  })
 })
}

Openid has been obtained through the above steps

Payment method applet

pay() {
 var that = this;
 if ( == 0) {
  return;
 }
 ({//Get the openid stored locally  key: 'openid',
  success: function (res) {
  ()
  ({
   openid:,
  })
  var carArray = ;
  var str="";
  for (var i = 0; i < ; i++) {
   str=str+ carArray[i].num+"indivual" + carArray[i].name+" ";
  }
  ({
   url: '',//Payment interface   data: {
   openid: ,//openid
   total_fee: ,//lump sum   body: str,//Product Description   },
   method:'GET',
   success:function(res){
   (['timeStamp'])
   if(){
    ({
    'timeStamp': ['timeStamp'],
    'nonceStr': ['nonceStr'],
    'package': ['package'],
    'signType': 'MD5',
    'paySign': ['paySign'],
    'success': function (res) {
     ({
     title: 'Payment Successfully',
     icon: 'succes',
     duration: 1000,
     mask: true
     })
     //After payment is successful, the number of purchased items is subtracted from the database     var carArray = ;
     for (var i = 0; i < ; i++) {
     ({
      jiesuan_num: carArray[i].num,
      jiesuan_id: carArray[i].goods_id,
     })
     DeGood(that);
     }
    },
    'fail': function (res) {
     ({
     title: 'Pay failed',
     icon: 'none',
     duration: 1000,
     mask: true
     })
    }
    })
   }
   }
  })
  }
 })
 },

<?php
 include ''; 
 $appid=''; //Mini appid $openid= $_GET['openid']; 
 $mch_id=''; // Merchant ID $key=''; // Merchant 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); 

<?php


/*
  * Mini Program WeChat Payment
  */


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() {
  //Unify single interface  $return = $this->weixinapp();
  return $return;
 }


 //Unify single interface private function unifiedorder() {
  $url = '/pay/unifiedorder';
  $parameters = array(
   'appid' => $this->appid, //Mini Program ID   'mch_id' => $this->mch_id, //Merchant number   'nonce_str' => $this->createNoncestr(), //Random string// 'body' => 'test', //Product description   'body' => $this->body,
// 'out_trade_no' => '2015450806125348', // Merchant Order Number   'out_trade_no'=> $this->out_trade_no,
// 'total_fee' => floatval(0.01 * 100), //Total amount Unit Points   'total_fee' => $this->total_fee,
// 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // Terminal IP   'spbill_create_ip' => '192.168.0.161', //Terminal IP   'notify_url' => '/wxpay/', //Notify address to ensure that the external network can be accessed normally   'openid' => $this->openid, //User ID   'trade_type' => 'JSAPI'//Trade Type  );
  //Unify single signature  $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();
  //Set timeout  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); //Strict verification  //Set header  curl_setopt($ch, CURLOPT_HEADER, FALSE);
  //The result is required to be a string and output to the screen  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  //Post submission method  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);


  //Run curl  $data = curl_exec($ch);
  //Return result  if ($data) {
   curl_close($ch);
   return $data;
  } else {
   $error = curl_errno($ch);
   curl_close($ch);
   throw new WxPayException("Curl error, error code: $error");
  }
 }



 //Convert array to 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;
 }


 // Convert xml into array private function xmlToArray($xml) {


  //Reference of external xml entities is prohibited

  libxml_disable_entity_loader(true);


  $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);


  $val = json_decode(json_encode($xmlstring), true);


  return $val;
 }


 //WeChat mini program interface private function weixinapp() {
  //Unify single interface  $unifiedorder = $this->unifiedorder();
//  print_r($unifiedorder);
  $parameters = array(
   'appId' => $this->appid, //Mini Program ID   'timeStamp' => '' . time() . '', //Time stamp   'nonceStr' => $this->createNoncestr(), //Random string   'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //Data Packet   'signType' => 'MD5'//Signature method  );
  //sign  $parameters['paySign'] = $this->getSign($parameters);
  return $parameters;
 }


 //Function: generate random strings, not longer than 32 bits 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;
 }


 //Function: Generate a signature private function getSign($Obj) {
  foreach ($Obj as $k => $v) {
   $Parameters[$k] = $v;
  }
  //Signature step 1: Sort parameters in dictionary order  ksort($Parameters);
  $String = $this->formatBizQueryParaMap($Parameters, false);
  //Signature step 2: Add KEY after string  $String = $String . "&key=" . $this->key;
  //Signature step 3: MD5 encryption  $String = md5($String);
  //Signature Step 4: All characters are converted to capitalization  $result_ = strtoupper($String);
  return $result_;
 }


 /// Function: Format parameters, the signature process needs to be used 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;
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.