使用微信JSAPI支付(公众号支付)接口实现微信H5支付功能

导读:

使用过微信支付商户的应该都知道,微信H5支付是比较难申请的,而且费率比较高,微信H5通道的风控也相对比较严,搞不好商户就会被风控清退。本文的思路就是通过微信JSAPI支付(公众号支付)接口来实现H5支付的功能。

有些小白可能会问“H5支付有啥用”?

H5支付用处非常大,很多网站和游戏都需要使用这个H5支付,方便玩家手机支付时,能自动跳转到微信APP,启用微信的支付功能。正是因为H5支付的重要性,所以H5支付通道的风控才比扫码支付要严。

准备工作: 

  1. 已认证的微信小程序(可以淘宝找人代认证,永久免费,不需要每年都年审);
  2. 拥有SSL证书的https安全域名;

思维图: 

 关键代码:

一、后端使用H5拉起小程序

        //微信小程序appid
        $appid=config("wxapp.appid");
    	//微信小程序secret
    	$secret=config("wxapp.secret");
    	//缓存名称
    	$cahcename ="weixinAccessToken-".$appid;
    	//1.获取微信接口调用凭证
        $access_token = getWeixinAccessToken($appid,$secret);
        if(!$access_token){
            exit("获取微信接口调用凭证失败");
        }
        //2.H5跳转到小程序
        $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $access_token;
        $path = "/lionfish_comshop/pages/pay/index";//小程序支付页面
        //传给小程序的参数
        $arr = array(
	        "number" => $params["pay_id"],
	        "money" => $params["money"]
	   );
        $post_data = [
            "jump_wxa" => [
                "path" => $path,
                "query" => http_build_query($arr)
            ],
            "expire_type" => 0,
            "expire_time" => time()+300 //scheme 码的失效时间(5分钟)
        ];
        $post_data = json_encode($post_data);
        $result = weixin_curl_post($url, $post_data);
        //对json数据解码
    	$json = json_decode($result);
    	$arr = get_object_vars($json);
        if($arr["errcode"]!=0){
            //凭证过期,重新获取
            Cache::rm($cahcename);
            exit("请求微信接口失败,请重新提交订单!");
            //printLog("请求微信接口失败,Error:".$arr["errmsg"]);
        }
        //小程序scheme码
        $pay_url = $arr["openlink"];
        if(isMobile()){
		    //手机端跳转到小程序
        	echo buildRequestForm(url('@h5/jump'),["url"=>$pay_url,"number"=>$params['pay_id'],"type"=>2]);
		}else{
		    //电脑端显示扫码
    		$params['pay_url'] = $pay_url;
		    echo buildRequestForm(url('@h5/weixinh5'),$params);
		}

获取微信接口调用凭证

//获取微信接口调用凭证
function getWeixinAccessToken($appid,$secret){
    $cahcename ="weixinAccessToken-".$appid;
	$access_token = Cache::get($cahcename);
	if(empty($access_token)){
    	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='. $secret;
    	//发送HTTPs请求并获取返回的数据
    	 $info = file_get_contents(trim($url));
    	//对json数据解码
    	$json = json_decode($info);
    	$arr = get_object_vars($json);
    	if(isset( $arr['access_token'])){
    		$access_token = $arr['access_token'];
    		$expires_in = $arr['expires_in'];//凭证有效时间,单位秒
    		//设置缓存
    		Cache::set($cahcename,$access_token,$expires_in);
    	}
	}
	return $access_token;
}

需要用到的公共函数方法

/**
 * 建立跳转请求表单
 * @param string $url 数据提交跳转到的URL
 * @param array $data 请求参数数组
 * @param string $method 提交方式:post或get 默认post
 * @return string 提交表单的HTML文本
 */
function buildRequestForm($url, $data, $method = 'post', $button_name = '确定', $show = false) {
	//如果要跳转到链接是当前域名,就验证https
    if(strpos($url,"http://") !== false && strpos($url,$_SERVER['HTTP_HOST']) !== false){
        if(isHttps()){
            $url = str_replace("http://","https://",$url);
        }
    }
    $html = "<form id='requestForm' name='requestForm' action='" . $url . "' method='" . $method . "'>";
    foreach ($data as $key => $val) {
        $html.= "<input type='hidden' name='" . $key . "' value='" . $val . "' />";
    }
    $display = $show ? "style='display:block;'" : "style='display:none;'";
    $html.= "<input type='submit' value='" . $button_name . "' " . $display . "></form>";
    $html.= "<script>document.forms['requestForm'].submit();</script>";
    return $html;
}
/**
 * 发起POST请求微信接口
 * https://api.weixin.qq.com/wxa/generatescheme?access_token=ACCESS_TOKEN
 * 返回结果
 */
function weixin_curl_post($url, $data){
    $ch = curl_init();
    $header = ["Accept-Charset" => "utf-8"];
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return false;
    } else {
        return $tmpInfo;
    }
}
/**
 * 判断是不是手机访问
 */
function isMobile(){
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if(strpos($agent,"comFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") ||         strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){
		return true;
	}
	return false;
}

二、微信小程序端js代码

// index.js
// 获取应用实例
const app = getApp()
Page({
  data: {
    showWebview: true,
    apiurl: "https://18pay.net",
    openid: "",
    order_no: "",
    money: 0,
    tips: "正在拉起微信支付,请稍候!",
  },
  /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
        //获取页面传递过来的参数
        if(!that.isEmpty(options.number)){
            that.setData({
                order_no: options.number
            });  
        }
        if(!that.isEmpty(options.money)){
            that.setData({
                money: options.money
            }); 
        }
        if(!that.isEmpty(that.data.order_no)){
            that.login();
        }
    },
    login() {
        var that = this;
        wx.login({
            success: function(res) {
              if (res.code) {
                //console.log("微信登录凭证:"+res.code);
                wx.request({
                    url: that.data.apiurl+"/Index/Weixin/getopenid.html",
                    method: 'POST',
                    dataType: 'json',
                    data: {
                        'appid':wx.getAccountInfoSync().miniProgram.appId,//当前小程序APPid
                        'code': res.code
                    },
                    success(res) {
                        if(res.data.code==1){
                            //console.log("获取到的openid:"+res.data.openid);
                            that.setData({
                                openid: res.data.openid,
                                showWebview: false
                            });
                            that.onPay();
                        }
                    }
                });
              } else {
                //console.log('用户登录失败' + res.errMsg)
              }
            }
        }) 
    },
    onPay() {
        var that = this;
        if(that.isEmpty(that.data.openid)){
			return;
        }
        if(that.isEmpty(that.data.order_no)){
			return;
        }
        //console.log("openid:"+that.data.openid);
        //console.log("订单编号:"+that.data.order_no);
        /*----------------------向元宝支付平台发起支付请求--------------------*/
        wx.request({
            url: that.data.apiurl+"/Index/Weixin/wxapp.html",
            method: 'POST',
            dataType: 'json',
            data: {
                openid: that.data.openid,
                number: that.data.order_no
            },
            success(res) {
                //success回调的res已经是解析好的json对象,无需再次JSON.parse,二次parse导致的错误产生
                let result = res.data;              
                //小程序拉起支付
                if(result.code == 1){      
                    wx.requestPayment({
                        'timeStamp': result.payinfo.timeStamp,
                        'nonceStr': result.payinfo.nonceStr,
                        'package': result.payinfo.package,
                        'signType': result.payinfo.signType,
                        'paySign': result.payinfo.paySign,
                        'success': function(res) {
                            that.setData({
                                tips: "支付成功",
                                showWebview: true
                            });
                        },
                        'fail': function(res) {
                            that.setData({
                                tips: "支付失败,请重新提交支付订单!",
                                showWebview: true
                            });
                        },
                        'complete': function(res) {
                            that.setData({
                                tips: "支付完成",
                                showWebview: true
                            });
                        }
                    })
                }else{
                    wx.showModal({
                        title: '',
                        content: result.msg,
                        confirmText: '好的',
                        showCancel: false,
                        success(result) {
                            //如果用户点击了确定按钮
                            if(result.confirm) {
                                that.setData({
                                    showWebview: true,
                                    order_no: "",
                                    money:0
                                }); 
                            }
                        }
                    })
                }
            }
        })             
        /*----------------------向元宝支付平台发起支付请求--------------------*/
    },
    isEmpty(content){
        if(content==null || typeof(content)=="undefined" || content=="") {
            return true;
        }else{
            return false;
        }
    },
})

三、获取微信openid

//获取微信openid
	public function getopenid(){
	    $data = input('');
	    try{
    	    !isset($data['code']) && $this->error('缺少code参数');
    	    !isset($data['appid']) && $this->error('缺少appid参数');
    	    $code = trim($data['code']);
    	    $appid = trim($data['appid']);
    		empty($code) && $this->error('code不能为空');
    		empty($appid) && $this->error('appid不能为空');
    		//根据appid去数据库查找secret密钥
    		$wxapp =Db::name("weixinapp")->field('appsecret')->where('appid',$appid)->find();
    		$appsecret  = $wxapp['appsecret'];
    		$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
    		$open_str = file_get_contents($url);
    		$data = json_decode($open_str, true);
    		if(isset($data['openid'])){
    		    $result = array('code' => 1,'openid' =>$data['openid']);
    		    echo json_encode($result);
    		    die();
    		}else{
    		    outputError($data['errmsg']);
    		}
	    } catch (\Exception $e) {
		}
	}

 四、微信小程序发起支付接口

//微信JSAPI支付请求
public function wxapp(){
	 /**
      * 这里的代码省略,请参考下面分享的代码来实现
      */
     //下面的$jsApiParameters参数是公众号支付获取到的结果
    $data = array(
    		    "code" => 1,
    		    "msg"  => "success",
    		    "payinfo" => $jsApiParameters
    		);
    		//printLog("返回给微信小程序的数据:".json_encode($data, JSON_UNESCAPED_UNICODE));
    		header('Content-Type:application/json; charset=utf-8');
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
            die();
}
<?php
header('Content-type:text/html; Charset=utf-8');
$mchid = 'xxxxx';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = 'xxxxx';  //微信支付申请对应的公众号的APPID
$appKey = 'xxxxx';   //微信支付申请对应的公众号的APP Key
$apiKey = 'xxxxx';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
//①、获取用户openid
$wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey);
$openId = $wxPay->GetOpenid();      //获取openid
if(!$openId) exit('获取openid失败');
//②、统一下单
$outTradeNo = uniqid();     //你自己的商品订单号
$payAmount = 0.01;          //付款金额,单位:元
$orderName = '支付测试';    //订单标题
$notifyUrl = 'https://www.xxx.com/wx/notify.php';     //付款成功后的回调地址(不要有问号)
$payTime = time();      //付款时间
$jsApiParameters = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);
$jsApiParameters = json_encode($jsApiParameters);
?>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>微信支付样例-支付</title>
        <script type="text/javascript">
            //调用微信JS api 支付
            function jsApiCall()
            {
                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest',
                    <?php echo $jsApiParameters; ?>,
                    function(res){
                        WeixinJSBridge.log(res.err_msg);
						if(res.err_msg=='get_brand_wcpay_request:ok'){
							alert('支付成功!');
						}else{
							alert('支付失败:'+res.err_code+res.err_desc+res.err_msg);
						}
                    }
                );
            }
            function callpay()
            {
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                    }
                }else{
                    jsApiCall();
                }
            }
        </script>
    </head>
    <body>
    <br/>
    <font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px"><?php echo $payAmount?>元</span>钱</b></font><br/><br/>
    <div align="center">
        <button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onclick="callpay()" >立即支付</button>
    </div>
    </body>
    </html>
<?php
class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $appKey;
    protected $apiKey;
    public $data = null;
    public function __construct($mchid, $appid, $appKey,$key)
    {
        $this->mchid = $mchid; //https://pay.weixin.qq.com 产品中心-开发配置-商户号
        $this->appid = $appid; //微信支付申请对应的公众号的APPID
        $this->appKey = $appKey; //微信支付申请对应的公众号的APP Key
        $this->apiKey = $key;   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
    }
    /**
     * 通过跳转获取用户的openid,跳转流程如下:
     * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code
     * @return 用户的openid
     */
    public function GetOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
			$uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
			if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
            $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码,以获取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }
    /**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        $res = self::curlGet($url);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }
    /**
     * 构造获取open和access_toke的url地址
     * @param string $code,微信跳转带回的code
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->appKey;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url,需要url编码
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * 统一下单
     * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 支付时间
     * @return string
     */
    public function createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        //$orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $notifyUrl,
            'openid' => $openid,            //rade_type=JSAPI,此参数必传
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => '127.0.0.1',
            'total_fee' => floatval($totalFee) * 100,       //单位 转为分
            'trade_type' => 'JSAPI',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);	    
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",        //这里是字符串的时间戳,不是int,所以需加引号
            "nonceStr" => self::createNonceStr(),
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
    }
    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}