WeChat payment packaged in 2016 is so easy to use
I have been working on WeChat and encountered many pitfalls. I wrote it down today so that everyone can avoid detours. It is my first time to write text, which is a bit crude. If there is anything you don’t understand, you can contact me at QQ1034100429, or send a private message.
getaccesstoken Get access_token
//Initiate payment
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)
sendtpl sends template messages<?php<br />
/**<br />
* Created by PhpStorm.<br />
* User: Administrator<br />
* Date: 2016/4/11<br />
* Time: 22:43<br />
*/<br />
namespace Org;<br />
class Weixin<br />
{<br />
Private $appid; //Appid of WeChat official account<br />
Private $appsecret; //appsecret of WeChat public account<br />
Private $mchid; //The merchant account of the WeChat public account<br />
Private $wechatkey; //Payment key for WeChat official account<br />
private$token;<br />
Public function __construct()<br />
{<br />
$this->appid = C('WEIXIN_APPID');<br>
$this->appsecret = C("WEIXIN_APP_SECRET");<br>
$this->mchid = C("WEIXIN_MCHID");<br>
$this->wechatkey = C("WEIXIN_KEY");<br>
$this->token = C('WEIXIN_APP_TOKEN');<br>
<br>
}<br>
Public function chushi()<br>
{<br>
echo $this->getaccesstoken();<br>
}<br>
Public function checkSignature()<br>
{<br>
$signature = $_GET['signature'];<br>
$timestamp = $_GET['timestamp'];<br>
$nonce = $_GET['nonce'];<br>
$token = $this->token;<br>
$arrtemp = array($token, $timestamp, $nonce);<br>
sort($arrtemp, SORT_STRING);<br>
$arrtemp = implode($arrtemp);<br>
$arrtemp = sha1($arrtemp);<br>
If ($arrtemp == $signature) {<br>
return true;<br>
else {<br>
Return false; <br>
}<br>
}<br>
Public function valid()<br>
{<br>
$echoStr = $_GET['echostr'];<br>
If ($this->checkSignature()) {<br>
echo $echoStr;<br>
exit;<br>
}<br>
}<br>
////According to the returned information, make corresponding processing<br>
// public function responseMsg()<br>
// {<br>
// $postStr = file_get_contents('php://input');<br>
// if (!empty($postStr)){<br>
// /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,<br>
// the best way is to check the validity of xml by yourself */<br>
// libxml_disable_entity_loader(true);<br>
// $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);<br>// $fromUsername = $postObj->FromUserName;<br>
// $toUsername = $postObj->ToUserName;<br>
// $keyword = trim($postObj->Content);<br>
// $msgType = $postObj->MsgType;<br>
// $Event=$postObj->Event;<br>
// $time = time();<br>
// $textTpl = "<xml><br>
// <ToUserName><![CDATA[%s]]></ToUserName><br>
// <FromUserName><![CDATA[%s]]></FromUserName><br>
// <CreateTime>%s</CreateTime><br>
// <MsgType><![CDATA[%s]]></MsgType><br>
// <Content><![CDATA[%s]]></Content><br>
// <FuncFlag>0</FuncFlag><br>
// </xml>";<br>
// if(!empty( $keyword ))<br>
// {<br>
// $msgType = "text";<br>
// $contentStr = "Welcome to wechat world!";<br>
// $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br>
// echo $resultStr;<br>
// }else{<br>
// echo "Input something...";<br>
// }<br>
//<br>
// }else {<br>
// echo "";<br>
// exit;<br>
// }<br>
// }<br>
public function getaccesstoken()<br>
{<br>
$access_token = S('access_token');<br>
if(!empty($access_token)){<br>
<br>
return $access_token;<br>
}else{<br>
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;;<br>
$ret = $this->curlget($url);<br> $ret = json_decode($ret,true);<br>
S('access_token',$ret['access_token'],7100);<br>
<br>
return $ret['access_token'];<br>
}<br>
}<br>
//根据openid拉取用户信息<br>
public function userinfo($openid){<br>
$access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($url),true);<br>
return $userinfo;<br>
}<br>
function p($arr){<br>
echo "<meta charset='utf8'><pre class="brush:php;toolbar:false">";<br>
print_r($arr);<br>
}<br>
function curlget($url)<br>
{<br>
$ch = curl_init();<br>
curl_setopt($ch, CURLOPT_URL, $url);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);<br>
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($ch, CURLOPT_HEADER, 0);<br>
$output = curl_exec($ch);<br>
curl_close($ch);<br>
return $output;<br>
}<br>
public function jingmo($url,$code,$state){<br>
if($code){<br>
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";<br>
$arrtemp = json_decode($this->curlget($url),true);<br>
$ret = $this->getuserinfo($arrtemp['openid'],$arrtemp['access_token']);<br>
return $ret;<br>
}else{<br>
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";<br>
header("Location: $url");<br>
}<br>
}<br>
public function getuserinfo($openid,$user_access_token){<br>
$userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$user_access_token."&openid=".$openid."&lang=zh_CN";<br>
$userinfo = json_decode($this->curlget($userurl),true);<br>
return $userinfo;<br>
}<br>
public function getjsapi_ticket(){<br>
$js_ticket = S("js_ticket");<br>
if(!empty($js_ticket)){<br>
return $js_ticket;<br>
}else{<br> $access_token = $this->getaccesstoken();<br>
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";<br>
$res = json_decode($this->curlget($url),true);<br>
S("js_ticket",$res['ticket'],7100);<br>
return $res['ticket'];<br>
}<br>
}<br>
public function getjssign(){<br>
echo "<meta charset='utf8'>";<br>
$js_ticket = $this->getjsapi_ticket();<br>
$time = time();<br>
$arr = array(<br>
'noncestr'=>md5($time),<br>
'jsapi_ticket'=>$js_ticket,<br>
'timestamp'=>$time,<br>
'url'=>'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],<br>
<br>
);<br>
$this->p($arr);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
echo $i;<br>
}<br>
// echo $string;<br>
$signature =strtolower($string);<br>
$signature = sha1($string);<br>
$jsconfig = array(<br>
'debug'=>true,<br>
'appId'=>$this->appid,<br>
'timestamp'=>$time,<br>
'nonceStr'=>md5($time),<br>
'signature'=>$signature,<br>
' jsApiList'=>"['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ']",<br>
);<br>
$json = json_encode($jsconfig);<br>
return $json;<br>
}<br>
//生成大写签名<br>
function createsign($arr,$biaozhi){<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br> $string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$signtemp = "$string&key=" . $this->wechatkey;<br>
$sign = strtoupper(MD5($signtemp));<br>
$arr[$biaozhi] = $sign;<br>
//$json = json_encode($arr);<br>
return $arr;<br>
}<br>
//支付<br>
<br>
//发起支付<br>
public function sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url)<br>
{<br>
$time = time();<br>
$arr = array(<br>
'appid' => $this->appid,<br>
'mch_id' => $this->mchid,<br>
'nonce_str' => md5($time),<br>
'body' => "kjhk",<br>
'out_trade_no' => $out_trade_no,<br>
'total_fee' => $total_fee,<br>
'spbill_create_ip' => "127.0.0.1",<br>
'notify_url' => $notify_url,<br>
'trade_type' => "JSAPI",<br>
'openid' => $openid,<br>
);<br>
$biaozhi ='sign';<br>
$arr = $this->createsign($arr,$biaozhi);<br>
$xml = "<xml>";<br>
foreach ($arr as $key=>$val) {<br>
$xml.="<".$key.">".$val."</".$key.">";<br>
}<br>
$xml.="</xml>";<br>
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";<br>
$resxml = $this->postCurlTransfer($url,$xml);<br>
$res = simplexml_load_string($resxml);<br>
$cutime = time();<br>
$jsapiarr=array(<br>
'appId'=>$this->appid,<br>
'timeStamp'=>"$cutime",<br>
'nonceStr'=>md5($cutime),<br>
'package'=>"prepay_id=".$res->prepay_id,<br>
'signType'=>"MD5",<br>
);<br> $biaozhi = 'paySign';<br>
$jsapi = $this->createsign($jsapiarr,$biaozhi);<br>
// $jsapijson = json_encode($jsapi);<br>
return $jsapi;<br>
}<br>
public function getpaysign(){<br>
$time = time();<br>
$arr = array(<br>
'appid'=>$this->appid,<br>
'mch_id'=>$this->mchid,<br>
'nonce_str'=>md5($time),<br>
'body'=>"sdf",<br>
'out_trade_no'=>"2016".$time,<br>
'total_fee'=>1,<br>
'spbill_create_ip'=>"127.0.0.1",<br>
'notify_url'=>"http://www.baidu.com",<br>
'trade_type'=>"JSAPI",<br>
);<br>
ksort($arr);<br>
$string="";<br>
$i=1;<br>
foreach($arr as $key=>$val){<br>
if($i==1){<br>
$string.=$key."=".$val;<br>
}else{<br>
$string.="&".$key."=".$val;<br>
}<br>
$i++;<br>
}<br>
$string.="&key=".$this->wechatkey;<br>
$sign = strtoupper(md5($string));<br>
$arr['sign'] = $sign;<br>
return $arr;<br>
}<br>
function Post($curlPost,$url){<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_HEADER, false);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br>
curl_setopt($curl, CURLOPT_NOBODY, true);<br>
curl_setopt($curl, CURLOPT_POST, true);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);<br>
$return_str = curl_exec($curl);<br>
curl_close($curl);<br>
return $return_str;<br>
}<br>
private function postCurlTransfer($url, $data)<br>
{<br>
$curl = curl_init();<br>
curl_setopt($curl, CURLOPT_URL, $url);<br>
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);<br>
curl_setopt($curl, CURLOPT_POST, 1);<br>
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);<br> $str = curl_exec($curl);<br>
curl_close($curl);<br>
<br>
Return $ Str; <br>
}<br>
//Send template message<br>
Public function sendtpl($openid, $url, $template_id, $content, $topcolor="#FF0000")<br>
{<br>
$arr = array(<br>
'touser' => $openid,<br>
‘template_id’ => $template_id,<br>
'url' => $url,<br>
'topcolor' => $topcolor,<br>
'data' => $content,<br>
);<br>
$arrjson = json_encode($arr);<br>
$accesstoken = $this->getAccessToken();<br>
$sendurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accesstoken;<br>
return $this->postCurlTransfer($sendurl, $arrjson);<br>
}<br>
}
The above is a simple package of WeChat payment
If you initiate payment, please first correspond to the information of the WeChat official account.
Including WeChat payment directory
I am here
http://domain name//index.php/Home/Index/
It seems to be this
The process of obtaining access_token<?php<br />
/**<br />
* Created by PhpStorm.<br />
* User: sks<br />
* Date: 16/7/8<br />
* Time: 下午3:54<br />
*/<br />
namespace HomeController;<br />
use CommonControllerHomebaseController;<br />
Class WeixinController extends HomebaseController{<br />
Public function zhanshi(){<br />
$weixin = new OrgWeixin;<br />
$code = $_GET['code'];<br />
$state = $_GET['state'];<br />
$url="";<br />
$userinfo = $weixin->jingmo($url, $code, $state);<br>
Session('userinfo',$userinfo);<br>
if($code) {<br>
header("Location: $state");<br>
}else{<br>
}<br>
}<br>
}
Public function
function.phpfunction getuserinfo(){ //Get user information<br>
Import("weixin");<br>
$weixin = new OrgWeixin;<br>
$info = session('userinfo');<br>
If($info){<br>
Return $ info; <br>
die;<br>
}else {<br>
$state = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];<br>
$code =
$url = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/Weixin/zhanshi');<br>
$url = urlencode($url);<br>
$weixin->jingmo($url, $code, $state);<br>
}<br>
}<br>Test payment
/**
* Created by PhpStorm.
*User: sks
* Date: 16/7/8
* Time: 3:29 pm
*/
namespace HomeController;
use CommonControllerHomebaseController;
use ThinkPage;
Class IndexController extends HomebaseController{
//Test payment
Public function zhifu()
{
$userinfo = getuserinfo(); //Get WeChat user information and call the public function
$openid = $userinfo['openid'];
$time = time();
$title = "I want to pay";
$out_trade_no = date('Y',time()).$time.rand(1000,2000);
$total_fee = 1;
$notify_url = "http://domain name/index.php/Home/Index/paynotify";//Callback URL
$weixin = new OrgWeixin;
$result = $weixin->sendpay($openid, $title, $out_trade_no, $total_fee, $notify_url);
$this->assign('result',$result);
$this->display();
}
//Here is the payment result notification
Public function paynotify(){
$weixin = new OrgWeixin;
$xml = file_get_contents("php://input");
$p = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$arr = $this->object_array($p);
$out_trade_no = $arr['out_trade_no'];
$transaction_id= $arr['transaction_id'];
$openid = $arr['openid'];
$sign = $arr['sign'];
//Processing payment results
unset($arr['sign']);
$biaozhi = "sign";
$ret = $weixin->createsign($arr, $biaozhi);
If($ret['sign'] === $sign) {
$aa = "Success";
else {
$aa = "Failure";
}
$file = './logweixin.txt';//The file name of the file to be written (can be any file name), if the file does not exist, it will be created
$content = $out_trade_no."***".$transaction_id."First written content n";
If($f = file_put_contents($file, $content,FILE_APPEND)){//This function supports version (PHP 5)
echo "Writing successful.
";
}
//The process of processing payment results here
echo "success";
}
Public function getaccesstoken(){
$weixin = new OrgWeixin;
echo $weixin->getaccesstoken();
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Learn about Python programming with introductory code examples Python is an easy-to-learn, yet powerful programming language. For beginners, it is very important to understand the introductory code examples of Python programming. This article will provide you with some concrete code examples to help you get started quickly. Print HelloWorldprint("HelloWorld") This is the simplest code example in Python. The print() function is used to output the specified content

"Go Language Programming Examples: Code Examples in Web Development" With the rapid development of the Internet, Web development has become an indispensable part of various industries. As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications. 1. Simple HTTP Server First, let’s start with a

PHP variables store values during program runtime and are crucial for building dynamic and interactive WEB applications. This article takes an in-depth look at PHP variables and shows them in action with 10 real-life examples. 1. Store user input $username=$_POST["username"];$passWord=$_POST["password"]; This example extracts the username and password from the form submission and stores them in variables for further processing. 2. Set the configuration value $database_host="localhost";$database_username="username";$database_pa

How to use PHP to write the inventory management function code in the inventory management system. Inventory management is an indispensable part of many enterprises. For companies with multiple warehouses, the inventory management function is particularly important. By properly managing and tracking inventory, companies can allocate inventory between different warehouses, optimize operating costs, and improve collaboration efficiency. This article will introduce how to use PHP to write code for inventory warehouse management functions, and provide you with relevant code examples. 1. Establish the database before starting to write the code for the inventory warehouse management function.

The simplest code example of Java bubble sort Bubble sort is a common sorting algorithm. Its basic idea is to gradually adjust the sequence to be sorted into an ordered sequence through the comparison and exchange of adjacent elements. Here is a simple Java code example that demonstrates how to implement bubble sort: publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

Huawei Cloud Edge Computing Interconnection Guide: Java Code Samples to Quickly Implement Interfaces With the rapid development of IoT technology and the rise of edge computing, more and more enterprises are beginning to pay attention to the application of edge computing. Huawei Cloud provides edge computing services, providing enterprises with highly reliable computing resources and a convenient development environment, making edge computing applications easier to implement. This article will introduce how to quickly implement the Huawei Cloud edge computing interface through Java code. First, we need to prepare the development environment. Make sure you have the Java Development Kit installed (

Title: From Beginner to Mastery: Code Implementation of Commonly Used Data Structures in Go Language Data structures play a vital role in programming and are the basis of programming. In the Go language, there are many commonly used data structures, and mastering the implementation of these data structures is crucial to becoming a good programmer. This article will introduce the commonly used data structures in the Go language and give corresponding code examples to help readers from getting started to becoming proficient in these data structures. 1. Array Array is a basic data structure, a group of the same type

Java Selection Sorting Method Code Writing Guide and Examples Selection sorting is a simple and intuitive sorting algorithm. The idea is to select the smallest (or largest) element from the unsorted elements each time and exchange it until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code. Algorithm Principle The basic principle of selection sort is to divide the array to be sorted into two parts, sorted and unsorted. Each time, the smallest (or largest) element is selected from the unsorted part and placed at the end of the sorted part. Repeat the above
