美文网首页web前端工程师
微信小程序支付代码

微信小程序支付代码

作者: 胡永凯 | 来源:发表于2019-08-08 16:50 被阅读0次

    前端html页面:



    前端js页面:

    submitOrder: function () {

                      let _this=this;

                     App._get('pay/answer_payment', {

                                     open_id: _this.data.open_id,

                                     total_price: _this.data.total_price, 

                     },

                     function (result) {

                                      var data=result;

                                      console.log(data);

                                      //  发起微信支付

                                      wx.requestPayment({

                                                 timeStamp: data['timeStamp'],

                                                  nonceStr: data['nonceStr'],

                                                  package: data['package'],

                                                  signType: 'MD5',

                                                   paySign: data['paySign'],

                                                  success: function (res) {

                                                               App._get('book/orderSave',

                                                               {

                                                                       user_id: _this.data.user_id,

                                                                       book_id: _this.data.book_id,

                                                                       book_content: _this.data.book_content,

                                                                       cost: _this.data.total_price,

                                                                        out_trade_no: data['out_trade_no'],

                                                                    }    function (result) {

                                                                           保存订单成功;

                                                                   });

                                                                   App._get('book/mybook',

                                                                   {

                                                                          user_id: _this.data.user_id,

                                                                           book_id: _this.data.book_id,

                                                                     },

                                                                     function (result) {

                                                                          加入书包成功;

                                                                     });

                                                                    wx.navigateBack(); 

                                                      },

                                                     fail: function () {

                                                                     App.showError('订单未支付', function () {

                                                         });

                                        },

                       });

              });

      },

    后台开发者服务器代码:

    public function answer_payment(){

            $open_id = $_GET['open_id'];

            $total_price = $_GET['total_price'];

            $fee = $total_price;//支付费用

            $appid = 'wxdebe20dae6829f79';

            $body = '书云';

            $mch_id =  '1541638811';  //商户号

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

            $notify_url =  'https://www.weixin.qq.com/wxpay/notify.php'; //回调的url

            $openid = $open_id;

            $out_trade_no = $this->order_number($open_id);//商户订单号

            $spbill_create_ip ='101.132.72.105';

            $total_fee =    $fee*100;// 微信支付单位是分,所以这里需要*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>'.$appid.'

               <body>'.$body.'

               <mch_id>'.$mch_id.'

               <nonce_str>'.$nonce_str.'

               <notify_url>'.$notify_url.'

               <openid>'.$openid.'

               <out_trade_no>'.$out_trade_no.'

               <spbill_create_ip>'.$spbill_create_ip.'

               <total_fee>'.$total_fee.'

               <trade_type>'.$trade_type.'

               <sign>'.$sign.'

            </xml> ';

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

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

            $array = $this->fromXml($xml);

            //var_dump($array);

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

                $time = time();

                $tmp=array();//临时数组用于签名

                $tmp['appId'] = $appid;

                $tmp['nonceStr'] = $nonce_str;

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

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

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

                $data['state'] = 200;

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

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

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

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

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

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

            }

          echo json_encode($data);

        }

        //随机32位字符串

        private function nonce_str(){

            $result = '';

            $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';

            for ($i=0;$i<32;$i++){

              $result .= $str[rand(0,48)];

            }

            return $result;

        }

        private function order_number($openid){

            return date('Ymd',time()).time().rand(10,99);//18位

            //return md5($openid.time().rand(10,99));//32位

        }

        //签名 $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 = 'cdsykjyxgs1688510107199101244217';

            $stringSignTemp = $stringA.'&key='.$wx_key;

            return strtoupper(md5($stringSignTemp));

        }

        //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;

        }

        private function fromXml($xml)

    {

            // 禁止引用外部xml实体

            libxml_disable_entity_loader(true);

            return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        }

    相关文章

      网友评论

        本文标题:微信小程序支付代码

        本文链接:https://www.haomeiwen.com/subject/hpnxjctx.html