小程序支付全代码

                           

/*
调起微信支付
@param 支付价格,不填写默认为1分钱
*/
function pay(total_fee) {

var total_fee = total_fee;
wx.login({
success: res => {

       //code 用于获取openID的条件之一
var code = res.code;
wx.request({
url: '后台地址/index.php',
method: "POST",
data: {
total_fee:total_fee,
code: code,
},
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
success: function (res) { //后端返回的数据
var data = res.data;
console.log(data);
console.log(data["timeStamp"]);
wx.requestPayment({
timeStamp: data['timeStamp'],
nonceStr: data['nonceStr'],
package: data['package'],
signType: data['signType'],
paySign: data['paySign'],
success: function (res) {
wx.showModal({
title: '支付成功',
content: '',
})
},
fail: function (res) {
console.log(res);
}
})
}
});


}
})
}


后端代码:

index.php

        //获取openid
        if(I("post.code"))
        {
            $code=I("post.code");
            $WX_APPID = '小程序id';
            $WX_SECRET = '小程序key';
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code";
            $infos = json_decode(file_get_contents($url));
            $openid = $infos->openid;
        }
        if(I("post.total_fee"))
        {
            $total_fee=I("post.total_fee");
        }
        else
        {
            $total_fee=1;
        }
        
    $appid =        '小程序id';//如果是公众号 就是公众号的appid
    $body =         '小程序支付';
    $mch_id =       '商户号';
    $nonce_str =    $this->nonce_str();//随机字符串
    $notify_url =   ‘回调地址自己填写’';
    $openid =      $openid;
    $out_trade_no = time();//商户订单号
    $spbill_create_ip = '服务器ip';
    $total_fee =    $total_fee;//因为充值金额最小是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 = '<xml>
           <appid>'.$appid.'</appid>
           <body>'.$body.'</body>
           <mch_id>'.$mch_id.'</mch_id>
           <nonce_str>'.$nonce_str.'</nonce_str>
           <notify_url>'.$notify_url.'</notify_url>
           <openid>'.$openid.'</openid>
           <out_trade_no>'.$out_trade_no.'</out_trade_no>
           <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
           <total_fee>'.$total_fee.'</total_fee>
           <trade_type>'.$trade_type.'</trade_type>
           <sign>'.$sign.'</sign>
        </xml> ';
    //统一接口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['state'] = 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['state'] = 0;
        $data['text'] = "错误";
        $data['RETURN_CODE'] = $array['RETURN_CODE'];
        $data['RETURN_MSG'] = $array['RETURN_MSG'];
    }
    echo json_encode($data); //小程序需要的数据 返回前端

}

  public function nonce_str(){
    $result = '';
    $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
    for ($i=0;$i<32;$i++){
        $result .= $str[rand(0,48)];
    }
    return $result;
}



//签名函数
public function sign($data){
    $stringA = '';
    foreach ($data as $key=>$value){
        if(!$value) continue;
        if($stringA) $stringA .= '&'.$key."=".$value;
        else $stringA = $key."=".$value;
    }
    $wx_key = 'lijinwenlijinwenlijinwenlijinwen';//申请支付后有给予一个商户账号和密码,登陆后自己设置key
    $stringSignTemp = $stringA.'&key='.$wx_key;//申请支付后有给予一个商户账号和密码,登陆后自己设置key 
    return strtoupper(md5($stringSignTemp));
}


//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;
}
--------------------- 
作者:he_Lucian 
来源:CSDN 
原文:https://blog.csdn.net/u012729832/article/details/79698788 
版权声明:本文为博主原创文章,转载请附上博文链接!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值