WeChat public account H5 page payment JSAPI

1: In the WeChat environment, we need to obtain the code, and use the code to obtain the openid. When obtaining the openid, there are two parameters: snsapi_base and snsapi_userinfo. The snsapi_base is only for obtaining the openid, and the latter is for obtaining customer authorization. For example: WeChat ID: avatar and other parameters!

Note: At the end of the WeChat link, the state=value can be passed with parameters!

The code expires in five minutes and expires once it is used!

Let's start with the code:

        $appid            = 公众号appid;
        $redirect_uri     = 微信回调链接;
        $snsapi           =snsapi_base//snsapi_userinfo;
        $url              ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$snsapi;
        Header("Location:$url");

2: Get the code value returned by get: cooperate with the appid-secret (obtained in the official account settings) + get the code, use the post to get the openid, and pay the code:

        
$code   =input('get.code');
$appid  =appid值;
$secret =secret值;
$url    ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$back   =$this->geturl($url);//去post拿值

3: At the current position, $back has an openid value, if you still need the continuation parameter under snsapi_userinfo! Customer avatar can be obtained through access_token (obtained value) + openid

Note: This will call the WeChat plug-in to pull the authorization login!

However, when I was developing this time, WeChat seems to have modified the mandatory pull-up authorization interface, which has been changed to prompt authorization at the bottom. This is not very friendly (for developers), and I have not found a way to force the authorization interface. I'll update here if I find it!

$url        ='https://api.weixin.qq.com/sns/userinfo?access_token='.$back['access_token'].'&openid='.$back['openid'].'&lang=zh_CN';
$backWeixin = $this ->geturl($url); //这里用curl  get

 4: After getting the openid value, we can start to pay and prepare!

	    $openid           ='上面获取的openid';
		$appid            ='公众号appid';
		$key              ='支付商户号里api安全里设置';//我目前用的是V2
		$mch_id           ='微信商户号';//注意不要选服务商号
        $total_fee        = 1;  //微信已分计算      
        $body             = '商品名称'; //商品描述
        $out_trade_no     = '订单号'; //订单号
        $nonce_str        =  MD5($out_trade_no);//随机字符串
        $spbill_create_ip = '获取ip'; 
        $trade_type       = 'JSAPI';//交易类型 
        $notify_url       = '回调域名'; 
        $scene_info       ='{"h5_info":{"type":"Wap","wap_url":"域名","wap_name":"名称"}}'; //场景信息
        $signA            = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&openid=$openid&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        $strSignTmp       = $signA."&key=$key"; //拼接字符串
        $sign             = strtoupper(md5($strSignTmp)); // MD5 后转换成大写
        
        
	    $date             =  "<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>
						        <scene_info>$scene_info</scene_info>
						        <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>";

	$dataxml	= $this->http_post("https://api.mch.weixin.qq.com/pay/unifiedorder",$date); 
	$objectxml	= (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); 

5: Up to the previous step, the main value we took is prepay_id; if you have used the post to get the normal value, then we are left with the last 2 steps

 $prepayId   ='上面获取到的值';    
 $pay        = array(
                  'appId' => $appid, 
                  'timeStamp' => '' . time() . '', //时间戳
                  'nonceStr' => $this->createNoncestr(), //随机串
                  'package' => 'prepay_id='.$prepayId, //数据包
                  'signType' => 'MD5'//签名方式
           );

 $pay['paySign'] = $this->getSign($pay);

Here are 2 methods

  
    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=1DKJ48bncxh3jd83ndcdAA23fvcf4g5w";
        //签名步骤三: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;
        }
    
    

6: At this point, we can get all the values ​​in $pay! If you did not report an error, please check step by step!

Next, we will return the value of $pay to the front-end page;



    
   WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId" :'{$vo.appId}', //公众号ID
        "timeStamp" :'{$vo.timeStamp}', //时间戳,当前系统的时间,具体格式,请看API
        "nonceStr" : '{$vo.nonceStr}', //随机串,具体格式请看API
        "package" : '{$vo.package}',//扩展包
        "signType" : "MD5", //微信签名方式:sha1
        "paySign" : '{$vo.paySign}', //微信签名
      },
      function(res){ 
              if(res.err_msg == "get_brand_wcpay_request:ok" ){
                成功跳转
      
                 }else{
          
                失败跳转  
              }
       }); 
    }
    if (typeof WeixinJSBridge == "undefined"){
       if( document.addEventListener ){
           document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
       }else if (document.attachEvent){
           document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
           document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
       }
    }else{
       onBridgeReady();
    }


Note: On the H5 page inside the WeChat environment, WeChat provides 2 payment methods: mine is one, direct payment!

Another payment method is suitable for use in various methods: such as WeChat internal payment, WeChat internal forwarding, WeChat internal what!

Guess you like

Origin blog.csdn.net/munchmills/article/details/126699432